main.py 520 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743
  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. api_keys,
  22. archive_purge,
  23. archives,
  24. auth,
  25. bug_report,
  26. camera,
  27. camwall,
  28. cloud,
  29. connected_apps,
  30. discovery,
  31. external_links,
  32. filaments,
  33. finance,
  34. firmware,
  35. github_backup,
  36. groups,
  37. ha_sensors,
  38. inventory,
  39. kprofiles,
  40. labels,
  41. library,
  42. library_tags,
  43. library_trash,
  44. library_variants,
  45. local_backup,
  46. local_presets,
  47. location_ha_sensors,
  48. maintenance,
  49. makerworld,
  50. metrics,
  51. mfa,
  52. notification_templates,
  53. notifications,
  54. obico,
  55. orca_cloud,
  56. pending_uploads,
  57. pipeline_runs,
  58. print_log,
  59. print_queue,
  60. printer_sensor_history,
  61. printers,
  62. projects,
  63. scheduled_dryings,
  64. settings as settings_routes,
  65. slice_jobs,
  66. slicer_pipelines,
  67. slicer_presets,
  68. smart_plugs,
  69. sponsor_prompt,
  70. spoolbuddy,
  71. spoolman,
  72. spoolman_inventory,
  73. support,
  74. system,
  75. updates,
  76. user_notifications,
  77. users,
  78. virtual_printers,
  79. webhook,
  80. websocket,
  81. )
  82. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  83. from backend.app.api.routes.support import init_debug_logging
  84. from backend.app.core.config import APP_VERSION, settings as app_settings
  85. from backend.app.core.database import async_session, engine, init_db
  86. from backend.app.core.tasks import spawn_background_task
  87. from backend.app.core.websocket import ws_manager
  88. from backend.app.services import print_dispatch_context, slot_unlink_grace
  89. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  90. from backend.app.services.archive_purge import archive_purge_service
  91. from backend.app.services.bambu_ftp import (
  92. FileNotOnPrinterError,
  93. cache_3mf_download,
  94. clear_3mf_cache,
  95. download_file_async,
  96. download_file_try_paths_async,
  97. ftps_handshake_blocked,
  98. get_cached_3mf,
  99. get_ftp_retry_settings,
  100. normalize_3mf_name,
  101. with_ftp_retry,
  102. )
  103. from backend.app.services.bambu_mqtt import PrinterState
  104. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  105. from backend.app.services.github_backup import github_backup_service
  106. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  107. from backend.app.services.homeassistant import homeassistant_service
  108. from backend.app.services.library_trash import library_trash_service
  109. from backend.app.services.local_backup import local_backup_service
  110. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  111. from backend.app.services.mqtt_relay import mqtt_relay
  112. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  113. from backend.app.services.notification_service import notification_service
  114. from backend.app.services.obico_detection import obico_detection_service
  115. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  116. from backend.app.services.print_scheduler import scheduler as print_scheduler
  117. from backend.app.services.print_storage import (
  118. REASON_FTP_TRANSFER_FAILED,
  119. REASON_FTPS_COOLOFF,
  120. external_storage_present,
  121. ftp_probe_paths,
  122. print_file_reachable_over_ftp,
  123. )
  124. from backend.app.services.printer_manager import (
  125. init_printer_connections,
  126. parse_plate_id,
  127. printer_manager,
  128. printer_state_to_dict,
  129. resolve_plate_id,
  130. )
  131. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  132. from backend.app.services.slot_nozzle import (
  133. nozzle_diameter_for_extruder,
  134. nozzle_flow_for_extruder,
  135. resolve_slot_nozzle,
  136. )
  137. from backend.app.services.smart_plug_manager import smart_plug_manager
  138. from backend.app.services.spool_assignment_notifications import (
  139. notify_missing_spool_assignments_on_print_start,
  140. )
  141. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  142. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  143. from backend.app.services.spoolman_tracking import (
  144. cleanup_tracking as _cleanup_spoolman_tracking,
  145. report_usage as _report_spoolman_usage,
  146. store_print_data as _store_spoolman_print_data,
  147. )
  148. from backend.app.services.tasmota import tasmota_service
  149. from backend.app.services.telegram_reactions import telegram_reaction_poller
  150. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  151. from backend.app.utils.ams_humidity import ams_humidity_percent
  152. from backend.app.utils.filament_types import printer_filament_type
  153. from backend.app.utils.fts_routing import extruder_for_inlet
  154. from backend.app.utils.local_time import utcnow_naive
  155. from backend.app.utils.print_jobs import is_internal_printer_job
  156. # =============================================================================
  157. # Dependency Check - runs before other imports to give helpful error messages
  158. # =============================================================================
  159. def _start_error_server(missing_packages: list):
  160. """Start a minimal HTTP server to display dependency errors in browser."""
  161. import os
  162. import signal
  163. from http.server import BaseHTTPRequestHandler, HTTPServer
  164. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  165. html = f"""<!DOCTYPE html>
  166. <html>
  167. <head>
  168. <title>Bambuddy - Setup Required</title>
  169. <style>
  170. body {{
  171. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  172. background: #0f172a; color: #e2e8f0;
  173. display: flex; justify-content: center; align-items: center;
  174. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  175. }}
  176. .container {{
  177. background: #1e293b; border-radius: 12px; padding: 40px;
  178. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  179. }}
  180. h1 {{ color: #f87171; margin-bottom: 10px; }}
  181. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  182. .packages {{
  183. background: #0f172a; border-radius: 8px; padding: 20px;
  184. margin: 20px 0; text-align: left;
  185. }}
  186. .packages ul {{ margin: 0; padding-left: 20px; }}
  187. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  188. .command {{
  189. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  190. margin: 15px 0; font-family: monospace; color: #4ade80;
  191. text-align: left; overflow-x: auto;
  192. }}
  193. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  194. </style>
  195. </head>
  196. <body>
  197. <div class="container">
  198. <h1>Setup Required</h1>
  199. <h2>Missing Python packages</h2>
  200. <div class="packages"><ul>{packages_html}</ul></div>
  201. <p>To fix, run this command on your server:</p>
  202. <div class="command">pip install -r requirements.txt</div>
  203. <p>Or if using a virtual environment:</p>
  204. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  205. <p class="note">After installing, restart Bambuddy:<br>
  206. <code>sudo systemctl restart bambuddy</code></p>
  207. </div>
  208. </body>
  209. </html>"""
  210. class ErrorHandler(BaseHTTPRequestHandler):
  211. def do_GET(self):
  212. self.send_response(503)
  213. self.send_header("Content-type", "text/html")
  214. self.end_headers()
  215. self.wfile.write(html.encode())
  216. def log_message(self, format, *args):
  217. print(f"[Error Server] {args[0]}")
  218. port = int(os.environ.get("PORT", 8000))
  219. print(f"\nStarting error server on http://0.0.0.0:{port}")
  220. print("Visit this URL in your browser to see the error details.\n")
  221. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  222. def shutdown(signum, frame):
  223. print("\nShutting down error server...")
  224. raise SystemExit(0)
  225. signal.signal(signal.SIGTERM, shutdown)
  226. signal.signal(signal.SIGINT, shutdown)
  227. server.serve_forever()
  228. def check_dependencies():
  229. """Check that all required packages are installed."""
  230. missing = []
  231. # Map of import name -> package name (for pip install)
  232. required = {
  233. "jwt": "PyJWT",
  234. "fastapi": "fastapi",
  235. "uvicorn": "uvicorn",
  236. "sqlalchemy": "sqlalchemy",
  237. "aiosqlite": "aiosqlite",
  238. "pydantic": "pydantic",
  239. "paho.mqtt": "paho-mqtt",
  240. }
  241. for module, package in required.items():
  242. try:
  243. __import__(module)
  244. except ImportError:
  245. missing.append(package)
  246. if missing:
  247. print("\n" + "=" * 60)
  248. print("ERROR: Missing required Python packages!")
  249. print("=" * 60)
  250. print(f"\nMissing packages: {', '.join(missing)}")
  251. print("\nTo fix, run:")
  252. print(" pip install -r requirements.txt")
  253. print("\nOr if using a virtual environment:")
  254. print(" ./venv/bin/pip install -r requirements.txt")
  255. print("=" * 60 + "\n")
  256. _start_error_server(missing)
  257. check_dependencies()
  258. # =============================================================================
  259. # Import settings first for logging configuration
  260. # Configure logging based on settings
  261. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  262. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  263. log_level = getattr(logging, log_level_str, logging.INFO)
  264. # Trace ID column ([-] when no request scope is active — startup, MQTT
  265. # callbacks, scheduled tasks not chained from a request — so the column
  266. # stays visually aligned and missing values are obvious in grep). See
  267. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  268. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  269. # Create root logger
  270. root_logger = logging.getLogger()
  271. root_logger.setLevel(log_level)
  272. # Trace-ID injection: this filter populates record.trace_id from the
  273. # per-request ContextVar so the format string above can reference it.
  274. # Attached to each HANDLER (not the root logger) because Python's
  275. # logging semantics only invoke a logger's filters on records that
  276. # *originated* at that logger — records propagated up from child
  277. # loggers (every named logger in the app) never trigger root's filter.
  278. # Putting it on the handlers means every record any handler emits gets
  279. # trace_id injected just before the formatter runs, regardless of which
  280. # logger created the record. Without this, the formatter raises
  281. # KeyError on every child-logger record and the record is silently
  282. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  283. # partially" bug we hit. See backend/app/core/trace.py for the
  284. # ContextVar the filter reads.
  285. from backend.app.core.trace import TraceIDFilter
  286. _trace_id_filter = TraceIDFilter()
  287. # Console handler - always enabled
  288. console_handler = logging.StreamHandler()
  289. console_handler.setLevel(log_level)
  290. console_handler.setFormatter(logging.Formatter(log_format))
  291. console_handler.addFilter(_trace_id_filter)
  292. root_logger.addHandler(console_handler)
  293. # File handler - only in production or if explicitly enabled
  294. if app_settings.log_to_file:
  295. log_file = app_settings.log_dir / "bambuddy.log"
  296. file_handler = RotatingFileHandler(
  297. log_file,
  298. maxBytes=app_settings.log_max_bytes,
  299. backupCount=app_settings.log_backup_count,
  300. encoding="utf-8",
  301. )
  302. file_handler.setLevel(log_level)
  303. file_handler.setFormatter(logging.Formatter(log_format))
  304. file_handler.addFilter(_trace_id_filter)
  305. root_logger.addHandler(file_handler)
  306. logging.info("Logging to file: %s", log_file)
  307. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  308. # access logger with propagate=False by default, so without this attach
  309. # there is no on-disk record of which endpoint triggered a server-state
  310. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  311. # for exactly this reason. Filtered to write methods only
  312. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  313. # frontend don't churn the rotation window faster than it's useful.
  314. from backend.app.core.logging_filters import (
  315. CancelledPoolNoiseFilter,
  316. WriteRequestsOnlyFilter,
  317. )
  318. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  319. uvicorn_access_logger.addHandler(file_handler)
  320. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  321. # Uvicorn's access logger has propagate=False (its own default), so the
  322. # root-attached TraceIDFilter never sees these records. Attach a
  323. # second instance directly so HTTP access lines carry the same trace
  324. # ID column as the application logs they correlate with.
  325. uvicorn_access_logger.addFilter(TraceIDFilter())
  326. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  327. # BaseHTTPMiddleware cancelling the inner task scope on client
  328. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  329. # underlying transaction leak; this filter only suppresses the residual
  330. # log records that pre-existing pools still emit during their cleanup.
  331. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  332. # Reduce noise from third-party libraries in production
  333. if not app_settings.debug:
  334. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  335. logging.getLogger("httpcore").setLevel(logging.WARNING)
  336. logging.getLogger("httpx").setLevel(logging.WARNING)
  337. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  338. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  339. # Track active prints: {(printer_id, filename): archive_id}
  340. _active_prints: dict[tuple[int, str], int] = {}
  341. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  342. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  343. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  344. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  345. # instead of running its own grab-now chain when present, so the finish photo
  346. # captures the better-framed pre-bed-drop moment without us having to force
  347. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  348. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  349. #
  350. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  351. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  352. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  353. # bank and the others are not — so the consumer can't tell them apart and
  354. # must not rotate again.
  355. _stage22_finish_frames: dict[int, bytes] = {}
  356. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  357. # `finally` block (whether it captured a frame or not). The consumer in
  358. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  359. # so the FINISH-state fallback path — where moment and completion are dispatched
  360. # back-to-back — doesn't race past the producer with an empty pop, and the
  361. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  362. # grab (Bambu printers allow only one RTSP client at a time).
  363. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  364. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  365. # layer-change and on print-progress advances (#2547) while the model is still
  366. # printing, then consumed by the FINISH-state finish-photo path when the
  367. # dispatcher recorded that it injected End G-code into this print. Bambu
  368. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  369. # plate-swap) has run, so a live grab there would capture the swapped/empty
  370. # plate.
  371. #
  372. # The load-bearing property: both drivers are print telemetry that stops before
  373. # the End G-code executes — no further layer_num increases, and mc_percent
  374. # freezes — so the last banked frame is always the finished print before the
  375. # swap. Anything added as a third driver must hold that same property.
  376. _inprint_frame_bank: dict[int, bytes] = {}
  377. # Monotonic timestamp of the last banked frame per printer — throttles banking
  378. # so tall prints don't add a camera grab on every layer.
  379. _inprint_frame_bank_ts: dict[int, float] = {}
  380. # Minimum seconds between banked frames, except the final object layer which
  381. # always refreshes for the best framing.
  382. _INPRINT_BANK_MIN_INTERVAL = 25.0
  383. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  384. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  385. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  386. # the first connected status update for that connection; transitions back
  387. # to False whenever we observe `state.connected = False` so the next
  388. # reconnect re-arms reconciliation. Keyed by printer_id.
  389. _printer_reconciled_since_connect: dict[int, bool] = {}
  390. # Same edge, same keying, for priming the printer's calibration table exactly
  391. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  392. # is otherwise filled only when someone opens the Profiles page or Configure
  393. # Slot, when a GitHub backup runs, or when the printer happens to answer
  394. # somebody else's query on the report topic. Until then the AMS slot card has
  395. # no K value to show on the printers whose trays carry none of their own
  396. # (#2854 — H2-series report cali_idx and nothing more).
  397. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  398. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  399. # {(printer_id, filename): archive_id}
  400. _expected_prints: dict[tuple[int, str], int] = {}
  401. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  402. # Used by usage tracker to map 3MF slots to physical AMS trays
  403. _print_ams_mappings: dict[int, list[int]] = {}
  404. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  405. _print_cost_center_ids: dict[int, int] = {}
  406. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  407. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  408. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  409. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  410. # for the queue path. Cleared on print completion or TTL eviction.
  411. _print_plate_ids: dict[int, int] = {}
  412. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  413. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  414. _last_progress_milestone: dict[int, int] = {}
  415. # Track whether first layer complete notification has been sent for current print
  416. _first_layer_notified: dict[int, bool] = {}
  417. # Track whether we already sent a kill-switch stop for the current unauthorized print
  418. _unauthorized_print_kill_sent: set[int] = set()
  419. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  420. # lookup briefly so an unknown active print does not query the database on
  421. # every status frame. A short TTL keeps settings changes responsive.
  422. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  423. _kill_switch_setting_cache: tuple[bool, float] | None = None
  424. # Provider notification started when the kill switch stops a print. The later
  425. # MQTT print-complete callback awaits this task and only sends its regular
  426. # provider notification when the immediate attempt failed.
  427. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  428. # Track HMS errors that have been notified: {printer_id: set of error codes}
  429. # This prevents sending duplicate notifications for the same error
  430. _notified_hms_errors: dict[int, set[str]] = {}
  431. # Track when HMS errors were last seen: {printer_id: timestamp}
  432. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  433. _hms_last_seen: dict[int, float] = {}
  434. _HMS_CLEAR_GRACE_SECONDS = 30.0
  435. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  436. # Used for snapshot-diff detection at print completion
  437. _timelapse_baselines: dict[int, set[str]] = {}
  438. # Track printers waiting for bed to cool after print completion.
  439. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  440. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  441. _bed_cool_waiters: dict[int, dict] = {}
  442. # Track printers where the user explicitly stopped the print from the queue UI.
  443. # When on_print_complete fires with status "failed" for these printers we treat it
  444. # as "cancelled" (stopped by user) so the correct notification email is sent.
  445. _user_stopped_printers: set[int] = set()
  446. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  447. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  448. # holds the previous observation so we only fire on the True → False edge (a
  449. # False → False repeat doesn't notify; an initial False at startup doesn't
  450. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  451. # holds the per-printer pending asyncio task that fires the notification
  452. # after a debounce window — cancelled if the printer reconnects before the
  453. # window elapses, so transient MQTT blips don't flood the user.
  454. _printer_last_connected: dict[int, bool] = {}
  455. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  456. # Debounce: a printer must stay offline this long before we notify. Sized
  457. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  458. # so a single stale-trigger cooldown isn't enough to fire — only a real
  459. # offline that survives one reconnect attempt notifies.
  460. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  461. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  462. # when status="failed" to label the print's failure_reason in archives.
  463. #
  464. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  465. # which is wrong on two counts:
  466. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  467. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  468. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  469. # the public wiki) as part of its user-cancel sequence. Matching on the module
  470. # alone caused user-cancellations to be archived as "Layer shift" failures.
  471. # We now match by full short code only — anything not in this map leaves
  472. # failure_reason=None rather than guessing.
  473. # Values are the canonical camelCase failure-reason keys, NOT display labels
  474. # (issue #2974). The vocabulary is enforced on writes by
  475. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  476. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  477. # Statistics breakdown. Storing a label here instead put a second spelling of
  478. # the same cause into one column: the Failure Analysis widget groups on the raw
  479. # value, so a print the backend classified and an identical one a user
  480. # classified counted as two different reasons, and the label form could never
  481. # be translated because there was no key for ``t()`` to resolve.
  482. _HMS_FAILURE_REASONS: dict[str, str] = {
  483. # Layer shift / step loss
  484. "0300_4057": "layerShift",
  485. "0300_4068": "layerShift",
  486. "0300_800C": "layerShift",
  487. # Filament runout (printer-side & per-AMS-slot)
  488. "0300_8004": "filamentRunout",
  489. "0700_8011": "filamentRunout",
  490. "0701_8011": "filamentRunout",
  491. "0702_8011": "filamentRunout",
  492. "0703_8011": "filamentRunout",
  493. "0704_8011": "filamentRunout",
  494. "0705_8011": "filamentRunout",
  495. "0706_8011": "filamentRunout",
  496. "0707_8011": "filamentRunout",
  497. "07FF_8011": "filamentRunout",
  498. # Clogged nozzle / extruder
  499. "0300_4006": "cloggedNozzle",
  500. "0300_8016": "cloggedNozzle",
  501. "0300_801C": "cloggedNozzle",
  502. "0700_8003": "cloggedNozzle",
  503. "0700_8007": "cloggedNozzle",
  504. "0700_8013": "cloggedNozzle",
  505. "0701_8003": "cloggedNozzle",
  506. "0701_8007": "cloggedNozzle",
  507. "0701_8013": "cloggedNozzle",
  508. "0702_8003": "cloggedNozzle",
  509. # AI print monitoring — spaghetti / the model coming off the plate.
  510. # `spaghettiDetached` is a key the archive editor already offers for this
  511. # failure mode, not a new one, so a derived reason opens the dropdown on
  512. # that option rather than blank — and survives the next save, which clears
  513. # any value the editor does not recognise.
  514. #
  515. # A module-0x0C row is safe here despite the warning above: that warning is
  516. # about matching on the module alone, and 0C00_8042 is a full short code
  517. # with a documented meaning ("The AI print monitor has detected a spaghetti
  518. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  519. # cannot collide.
  520. #
  521. # 0300_8003's own text ends "before continuing your print", but on an X2D
  522. # it arrives with the print already paused, offering only
  523. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  524. #
  525. # Two neighbours are left out on purpose, so this does not get re-derived:
  526. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  527. # reads as a warning about a print that is still running, not a halt.
  528. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  529. # the waste chute. That is not the print failing.
  530. #
  531. # That line is drawn from the text, not from `severity`, because severity
  532. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  533. # module/error word with no level in it, and bambu_mqtt.py gives every
  534. # print_error entry a flat severity=3. Matching on the short code alone is
  535. # the right shape for derive_failure_reason, not an omission.
  536. "0300_8003": "spaghettiDetached",
  537. "0C00_8042": "spaghettiDetached",
  538. }
  539. def _hms_short_code(attr: int, code: int | str) -> str:
  540. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  541. if isinstance(code, str):
  542. code_int = int(code.replace("0x", ""), 16) if code else 0
  543. else:
  544. code_int = int(code or 0)
  545. attr_int = int(attr or 0)
  546. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  547. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  548. """Derive the failure_reason key for an archived print.
  549. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  550. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  551. no HMS code matches (don't guess — null is honest). The keys are the
  552. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  553. translated at render time.
  554. """
  555. if status in ("aborted", "cancelled"):
  556. return "userCancelled"
  557. if status != "failed":
  558. return None
  559. for err in hms_errors or []:
  560. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  561. if short_code in _HMS_FAILURE_REASONS:
  562. return _HMS_FAILURE_REASONS[short_code]
  563. return None
  564. # Track created_by_id for expected prints so the user email can be sent even when
  565. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  566. # {(printer_id, filename): created_by_id}
  567. _expected_print_creators: dict[tuple[int, str], int] = {}
  568. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  569. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  570. # updates for the same printer in quick succession (~30 ms apart, observed in
  571. # the wild on H2D + dual AMS).
  572. #
  573. # Without this serialisation, two concurrent on_ams_change callbacks each read
  574. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  575. # the second commit hits
  576. # IntegrityError: duplicate key value violates unique constraint
  577. # "spool_assignment_printer_id_ams_id_tray_id_key"
  578. # SQLite's WAL serial-write semantics had been silently swallowing the race
  579. # until optional Postgres support landed (asyncpg allows true concurrent
  580. # transactions and surfaces the constraint violation).
  581. #
  582. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  583. # assign) are inside the lock. The Spoolman sync block further down stays
  584. # concurrent because it's network-bound and idempotent.
  585. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  586. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  587. """Return the per-printer assignment lock, creating it on first use."""
  588. lock = _ams_assignment_locks.get(printer_id)
  589. if lock is None:
  590. lock = asyncio.Lock()
  591. _ams_assignment_locks[printer_id] = lock
  592. return lock
  593. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  594. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  595. # tag tuple changes for the slot. Cleared when the slot is reported empty
  596. # so remove + reinsert reliably re-prompts the UI.
  597. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  598. async def _broadcast_unknown_tag(
  599. *,
  600. printer_id: int,
  601. ams_id: int,
  602. tray_id: int,
  603. tag_uid: str,
  604. tray_uuid: str,
  605. tray_type: str | None = None,
  606. tray_color: str | None = None,
  607. tray_sub_brands: str | None = None,
  608. tray_count: int | None = None,
  609. ) -> None:
  610. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  611. _logger = logging.getLogger(__name__)
  612. slot_key = (ams_id, tray_id)
  613. tag_key = (tag_uid or "", tray_uuid or "")
  614. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  615. if per_printer.get(slot_key) == tag_key:
  616. _logger.debug(
  617. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  618. printer_id,
  619. ams_id,
  620. tray_id,
  621. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  622. )
  623. return
  624. _logger.info(
  625. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  626. printer_id,
  627. ams_id,
  628. tray_id,
  629. tray_type,
  630. tray_color,
  631. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  632. )
  633. # Broadcast first; only commit the dedup if the WS write succeeds.
  634. # If broadcast raises, the next MQTT push retries instead of being
  635. # permanently silenced by a poisoned dedup entry.
  636. await ws_manager.broadcast(
  637. {
  638. "type": "unknown_tag",
  639. "printer_id": printer_id,
  640. "ams_id": ams_id,
  641. "tray_id": tray_id,
  642. "tag_uid": tag_uid,
  643. "tray_uuid": tray_uuid,
  644. "tray_type": tray_type,
  645. "tray_color": tray_color,
  646. "tray_sub_brands": tray_sub_brands,
  647. "tray_count": tray_count,
  648. }
  649. )
  650. per_printer[slot_key] = tag_key
  651. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  652. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  653. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  654. if per_printer is None:
  655. return
  656. per_printer.pop((ams_id, tray_id), None)
  657. # TTL for expected-print entries: evict registrations older than this to prevent
  658. # unbounded growth when a print is registered but never starts (e.g. printer
  659. # disconnect, app restart, print started from the printer panel).
  660. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  661. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  662. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  663. # Cleanup loop interval
  664. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  665. _expected_prints_cleanup_task: asyncio.Task | None = None
  666. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  667. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  668. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  669. possible_keys: list[tuple[int, str]] = []
  670. filename = (state.gcode_file or state.current_print or "").strip()
  671. subtask_name = (state.subtask_name or "").strip()
  672. if subtask_name:
  673. possible_keys.append((printer_id, subtask_name))
  674. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  675. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  676. if filename:
  677. base_name = filename.rsplit("/", 1)[-1]
  678. if base_name.endswith(".gcode.3mf"):
  679. root_name = base_name[: -len(".gcode.3mf")]
  680. possible_keys.append((printer_id, root_name))
  681. possible_keys.append((printer_id, base_name))
  682. possible_keys.append((printer_id, f"{root_name}.gcode"))
  683. possible_keys.append((printer_id, f"{root_name}.3mf"))
  684. elif base_name.endswith(".3mf"):
  685. root_name = base_name[: -len(".3mf")]
  686. possible_keys.append((printer_id, root_name))
  687. possible_keys.append((printer_id, base_name))
  688. elif base_name.endswith(".gcode"):
  689. root_name = base_name[: -len(".gcode")]
  690. possible_keys.append((printer_id, root_name))
  691. possible_keys.append((printer_id, f"{root_name}.3mf"))
  692. possible_keys.append((printer_id, base_name))
  693. else:
  694. possible_keys.append((printer_id, base_name))
  695. possible_keys.append((printer_id, f"{base_name}.3mf"))
  696. return possible_keys
  697. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  698. """Check the cheap, process-local print ownership signals."""
  699. if printer_manager.get_current_print_user(printer_id):
  700. return True
  701. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  702. async def _is_printer_kill_switch_enabled_cached() -> bool:
  703. """Return the kill-switch setting without querying on every MQTT frame."""
  704. global _kill_switch_setting_cache
  705. now = time.monotonic()
  706. if _kill_switch_setting_cache is not None:
  707. enabled, expires_at = _kill_switch_setting_cache
  708. if now < expires_at:
  709. return enabled
  710. async with async_session() as db:
  711. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  712. enabled = await is_printer_kill_switch_enabled(db)
  713. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  714. return enabled
  715. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  716. """Resolve whether the current print was started by Bambuddy.
  717. ``None`` means identity is not yet safe to decide. The kill switch must
  718. defer in that case: stopping a print is irreversible, and the first status
  719. frames after a restart may arrive before all subtask fields are populated.
  720. """
  721. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  722. return True
  723. possible_keys = _build_status_print_keys(printer_id, state)
  724. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  725. # is on disk. subtask_id is minted per print and pins the answer to the job
  726. # actually running, rather than to an unrelated one that reuses a filename.
  727. raw_subtask_id = getattr(state, "subtask_id", None)
  728. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  729. if subtask_id in ("", "0"):
  730. return None
  731. from backend.app.models.archive import PrintArchive
  732. result = await db.execute(
  733. select(PrintArchive)
  734. .where(
  735. PrintArchive.printer_id == printer_id,
  736. PrintArchive.status == "printing",
  737. PrintArchive.subtask_id == subtask_id,
  738. )
  739. .order_by(PrintArchive.created_at.desc())
  740. .limit(1)
  741. )
  742. archive = result.scalar_one_or_none()
  743. # An archive row on its own proves nothing: `on_print_start` archives every
  744. # print it observes, including ones started from Bambu Studio or Handy, and
  745. # stamps them with the same status and subtask_id. Authorizing on its mere
  746. # existence would disable the kill switch the moment the 3MF finishes
  747. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  748. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  749. # (carried over from the queue item that started it).
  750. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  751. # Rehydrate the fast in-memory path for subsequent status frames. Include
  752. # both the archive filename and every normalized key reported by MQTT.
  753. _active_prints[(printer_id, archive.filename)] = archive.id
  754. for key in possible_keys:
  755. _active_prints[key] = archive.id
  756. return True
  757. # No dispatch marker. Before calling this someone else's print, check whether
  758. # Bambuddy has a job of its own running on this printer: a library-file
  759. # dispatch has no archive at send time, and an archive created seconds later
  760. # by `on_print_start` carries neither marker. The queue row, which the
  761. # scheduler commits to status="printing" before the MQTT send, is the one
  762. # durable record every Bambuddy print has. It cannot be tied to this
  763. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  764. # print is irreversible, and refusing to act costs nothing but a log line.
  765. from backend.app.models.print_queue import PrintQueueItem
  766. dispatched_here = await db.scalar(
  767. select(PrintQueueItem.id)
  768. .where(
  769. PrintQueueItem.printer_id == printer_id,
  770. PrintQueueItem.status == "printing",
  771. )
  772. .limit(1)
  773. )
  774. if dispatched_here is not None:
  775. return None
  776. return False
  777. async def _send_kill_switch_provider_notification(
  778. printer_id: int,
  779. printer_name: str,
  780. data: dict,
  781. ) -> bool:
  782. """Send the immediate print-stopped provider notification.
  783. Returning a success flag lets the normal MQTT completion path retry when
  784. this early notification could not be delivered.
  785. """
  786. logger = logging.getLogger(__name__)
  787. try:
  788. async with async_session() as db:
  789. await notification_service.on_print_complete(
  790. printer_id,
  791. printer_name,
  792. "stopped",
  793. data,
  794. db,
  795. )
  796. return True
  797. except Exception as e:
  798. logger.warning(
  799. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  800. printer_id,
  801. e,
  802. )
  803. return False
  804. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  805. """Wait for an immediate kill-switch notification, if one was scheduled."""
  806. if task is None:
  807. return False
  808. try:
  809. return await task
  810. except Exception as e:
  811. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  812. return False
  813. async def _get_plug_energy(plug, db) -> dict | None:
  814. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  815. For HA plugs, configures the service with current settings from DB.
  816. For MQTT plugs, returns data from the subscription service.
  817. For REST plugs, polls the status URL with JSON path extraction.
  818. """
  819. if plug.plug_type == "homeassistant":
  820. from backend.app.api.routes.settings import get_homeassistant_settings
  821. ha_settings = await get_homeassistant_settings(db)
  822. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  823. return await homeassistant_service.get_energy(plug)
  824. elif plug.plug_type == "mqtt":
  825. # MQTT plugs report "today" energy, not lifetime total
  826. # For per-print tracking, we use "today" as the counter (resets at midnight)
  827. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  828. if mqtt_data:
  829. return {
  830. "power": mqtt_data.power,
  831. "today": mqtt_data.energy,
  832. "total": mqtt_data.energy, # Use today as total for per-print calculations
  833. }
  834. return None
  835. elif plug.plug_type == "rest":
  836. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  837. return await rest_smart_plug_service.get_energy(plug)
  838. else:
  839. return await tasmota_service.get_energy(plug)
  840. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  841. """Capture the smart plug lifetime counter on the archive at print start.
  842. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  843. tracking survives a backend restart mid-print. The print-end handler reads
  844. this value back from the DB and computes the delta against the current
  845. plug counter.
  846. """
  847. _logger = logging.getLogger(__name__)
  848. try:
  849. candidates = await energy_plug_candidates(db, printer_id)
  850. if not candidates:
  851. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  852. return False
  853. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  854. if selected is None:
  855. # Naming the plugs matters here: with several linked to one printer
  856. # this is the difference between "the meter is offline" and "you
  857. # linked only accessories" (#2859).
  858. _logger.warning(
  859. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  860. printer_id,
  861. archive.id,
  862. ", ".join(plug.name for plug in candidates),
  863. )
  864. return False
  865. plug, energy = selected
  866. archive.energy_start_kwh = float(energy["total"])
  867. await db.commit()
  868. _logger.info(
  869. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  870. f" ({context})" if context else "",
  871. archive.id,
  872. plug.name,
  873. energy["total"],
  874. )
  875. return True
  876. except Exception as e:
  877. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  878. return False
  879. def register_expected_print(
  880. printer_id: int,
  881. filename: str,
  882. archive_id: int,
  883. ams_mapping: list[int] | None = None,
  884. created_by_id: int | None = None,
  885. cost_center_id: int | None = None,
  886. plate_id: int | None = None,
  887. ):
  888. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  889. # Store with multiple filename variations to catch different naming patterns
  890. _expected_prints[(printer_id, filename)] = archive_id
  891. # Also store without .3mf extension if present
  892. if filename.endswith(".3mf"):
  893. base = filename[:-4]
  894. _expected_prints[(printer_id, base)] = archive_id
  895. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  896. # Store AMS mapping for usage tracking at print completion
  897. if ams_mapping is not None:
  898. _print_ams_mappings[archive_id] = ams_mapping
  899. if cost_center_id is not None:
  900. _print_cost_center_ids[archive_id] = cost_center_id
  901. # Store plate_id for usage tracking when this is a single-plate dispatch from
  902. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  903. # file's filament total to the spool instead of just the printed plate (#1697).
  904. if plate_id is not None:
  905. _print_plate_ids[archive_id] = plate_id
  906. # Store created_by_id so the user start email can be sent even when the archive
  907. # itself has no created_by_id (e.g. library-file-based queue prints)
  908. if created_by_id is not None:
  909. _expected_print_creators[(printer_id, filename)] = created_by_id
  910. if filename.endswith(".3mf"):
  911. base = filename[:-4]
  912. _expected_print_creators[(printer_id, base)] = created_by_id
  913. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  914. # Record registration time for TTL-based eviction
  915. _registered_at = time.monotonic()
  916. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  917. if filename.endswith(".3mf"):
  918. base = filename[:-4]
  919. _expected_print_registered_at[(printer_id, base)] = _registered_at
  920. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  921. logging.getLogger(__name__).info(
  922. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  923. )
  924. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  925. """Undo :func:`register_expected_print` when the print never went out.
  926. Registration has to happen *before* the MQTT print command, because the
  927. printer can report the print before the line after the send executes. So
  928. every path that registers and then fails to send — a cancel winning the
  929. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  930. between — leaves an expectation for a print that will never arrive.
  931. The TTL sweep evicts those after two hours, which is far longer than it
  932. takes a user to react to a failed dispatch by pressing print again: that
  933. reprint would be folded into the *old* archive and take the stale
  934. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  935. Mirrors the sweep's rules, including the one that is easy to get wrong:
  936. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  937. file, so they may only be dropped once no live key still points at that
  938. archive.
  939. """
  940. keys = [(printer_id, filename)]
  941. if filename.endswith(".3mf"):
  942. base = filename[:-4]
  943. keys.append((printer_id, base))
  944. keys.append((printer_id, f"{base}.gcode"))
  945. removed = False
  946. for key in keys:
  947. if _expected_prints.pop(key, None) is not None:
  948. removed = True
  949. _expected_print_creators.pop(key, None)
  950. _expected_print_registered_at.pop(key, None)
  951. if archive_id not in set(_expected_prints.values()):
  952. _print_ams_mappings.pop(archive_id, None)
  953. _print_plate_ids.pop(archive_id, None)
  954. if removed:
  955. logging.getLogger(__name__).info(
  956. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  957. printer_id,
  958. filename,
  959. archive_id,
  960. )
  961. def _compute_run_filament_grams(
  962. status: str,
  963. archive_filament_used_grams: float | None,
  964. progress: float | int | None,
  965. usage_results: list[dict] | None,
  966. ) -> float | None:
  967. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  968. Priority for every status:
  969. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  970. weight delta — same source that drives "Total Consumed" on the
  971. Inventory page, so Stats and Inventory totals stay aligned).
  972. 2. For ``completed``: the slicer estimate (no tracker available, fall
  973. back to the canonical "this print used X" value).
  974. 3. For partial statuses: ``estimate * progress%``.
  975. 4. ``None`` if nothing is known.
  976. """
  977. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  978. if tracked_grams > 0:
  979. return round(tracked_grams, 1)
  980. if status == "completed":
  981. return archive_filament_used_grams
  982. if archive_filament_used_grams:
  983. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  984. if scale > 0:
  985. return round(archive_filament_used_grams * scale, 1)
  986. return None
  987. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  988. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  989. stored_ams_mapping = data.get("ams_mapping")
  990. if not stored_ams_mapping and archive_id:
  991. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  992. return stored_ams_mapping
  993. def _get_start_plate_id(archive_id: int | None) -> int | None:
  994. """Resolve plate_id for print start without consuming stored direct-Print state.
  995. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  996. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  997. read it back at print-start without popping (the entry is popped on print
  998. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  999. """
  1000. if archive_id is None:
  1001. return None
  1002. return _print_plate_ids.get(archive_id)
  1003. def _partial_progress_scale(progress: int | float | None) -> float:
  1004. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1005. Used by every site that multiplies a "would-have-used" slicer estimate
  1006. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1007. so the three sites in ``_background_notifications`` (and the per-plate
  1008. override helper) can't drift apart on the coercion shape.
  1009. """
  1010. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1011. def _scope_notification_archive_data_to_plate(
  1012. archive_data: dict,
  1013. archive_file_path: str | None,
  1014. plate_id: int | None,
  1015. print_status: str,
  1016. progress: int | float | None,
  1017. base_dir: Path,
  1018. ) -> dict:
  1019. """Override summed-across-plates totals in ``archive_data`` with the values
  1020. for ``plate_id`` so the completion notification reports what was actually
  1021. printed, not the whole project (#1785).
  1022. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1023. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1024. the archive card's "whole project" headline, wrong for the completion
  1025. notification of a single-plate print. The queue UI already re-reads the
  1026. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1027. notification payload (filament grams, time estimate, per-slot breakdown).
  1028. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1029. no per-plate values — in every fail case the original ``archive_data`` is
  1030. returned unchanged so the notification still sends.
  1031. """
  1032. if plate_id is None or not archive_file_path:
  1033. return archive_data
  1034. from backend.app.utils.threemf_tools import (
  1035. extract_filament_usage_from_3mf,
  1036. extract_print_time_from_3mf,
  1037. )
  1038. archive_path = base_dir / archive_file_path
  1039. if not archive_path.exists():
  1040. return archive_data
  1041. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1042. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1043. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1044. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1045. if plate_time:
  1046. archive_data["print_time_seconds"] = plate_time
  1047. # Gate both the grams headline AND the per-slot breakdown on the same
  1048. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1049. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1050. # to the project-level grams the archive columns already provide rather
  1051. # than ship a project-level headline next to an all-zero per-plate
  1052. # breakdown.
  1053. if plate_grams > 0:
  1054. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1055. archive_data["filament_slots"] = [
  1056. {
  1057. "slot_id": s.get("slot_id"),
  1058. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1059. "type": s.get("type", ""),
  1060. "color": s.get("color", ""),
  1061. }
  1062. for s in plate_slots
  1063. ]
  1064. return archive_data
  1065. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1066. """Best-effort filament metadata from the MQTT print-start snapshot.
  1067. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1068. file during print, see #1533) so the fallback PrintArchive still has
  1069. enough filament info to support the inventory views and AMS-expansion
  1070. planning the operator opens it for. Returns a dict with optional
  1071. ``filament_type`` and ``filament_color`` keys in the same
  1072. comma-separated format the 3MF extractor produces, so the rest of the
  1073. codebase treats the fallback archive identically to a normal one.
  1074. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1075. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1076. entries). When supplied, only the slots actually consumed by this
  1077. print contribute. Without it the function falls back to every loaded
  1078. AMS slot — less accurate but still useful.
  1079. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1080. that the unit tests pass directly, AND the on_print_start callback
  1081. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1082. bambu_mqtt service hands to main.py at runtime. The original
  1083. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1084. handled the inner shape and silently returned ``{}`` for every real
  1085. print start, leaving fallback archives' filament fields NULL — the
  1086. exact regression the fix was meant to close. Reported with a log
  1087. proving the AMS state was right there at
  1088. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1089. """
  1090. result: dict[str, str] = {}
  1091. # Look at the on_print_start wrapper first, then the inner shape.
  1092. raw_data = (data or {}).get("raw_data")
  1093. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1094. if not isinstance(ams_root, dict):
  1095. ams_root = (data or {}).get("ams") or {}
  1096. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1097. if not isinstance(ams_units, list) or not ams_units:
  1098. return result
  1099. # Map global tray id (unit * 4 + tray) → (type, color).
  1100. loaded: dict[int, tuple[str, str]] = {}
  1101. for unit in ams_units:
  1102. if not isinstance(unit, dict):
  1103. continue
  1104. try:
  1105. unit_id = int(unit.get("id", 0))
  1106. except (TypeError, ValueError):
  1107. continue
  1108. for tray in unit.get("tray") or []:
  1109. if not isinstance(tray, dict):
  1110. continue
  1111. try:
  1112. tray_id = int(tray.get("id", 0))
  1113. except (TypeError, ValueError):
  1114. continue
  1115. ttype = (tray.get("tray_type") or "").strip()
  1116. tcolor = (tray.get("tray_color") or "").strip().upper()
  1117. if not ttype:
  1118. continue # Empty / unloaded slot.
  1119. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1120. if not loaded:
  1121. return result
  1122. if ams_mapping:
  1123. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1124. filaments = [loaded[g] for g in used_ids if g in loaded]
  1125. if not filaments:
  1126. return result # Mapping points entirely at slots we have no data for.
  1127. else:
  1128. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1129. types_joined = ",".join(f[0] for f in filaments)
  1130. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1131. # Column limits per backend/app/models/archive.py: filament_type=50,
  1132. # filament_color=200.
  1133. if types_joined:
  1134. result["filament_type"] = types_joined[:50]
  1135. if colors_joined:
  1136. result["filament_color"] = colors_joined[:200]
  1137. return result
  1138. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1139. """Start a layer-timelapse session for *archive_id* when the printer has
  1140. an external camera configured. Returns True if a session was started.
  1141. Three call sites in on_print_start (expected-archive promotion, fallback
  1142. archive creation, fresh-archive creation) used to inline this same
  1143. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1144. on the first pass). Centralising the conditional + call here makes the
  1145. contract testable in isolation and keeps the three sites locked in step.
  1146. """
  1147. if not (printer.external_camera_enabled and printer.external_camera_url):
  1148. return False
  1149. from backend.app.services.layer_timelapse import start_session
  1150. start_session(
  1151. printer_id,
  1152. archive_id,
  1153. printer.external_camera_url,
  1154. printer.external_camera_type or "mjpeg",
  1155. snapshot_url=printer.external_camera_snapshot_url,
  1156. rotation=getattr(printer, "camera_rotation", 0),
  1157. )
  1158. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1159. return True
  1160. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1161. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1162. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1163. — since #2926 — the description the parser already resolved, which is preferred
  1164. when present so the queue's failure reason reads the same as the status
  1165. response. The short code still produces the bracketed label, and still
  1166. resolves the sentence for a caller whose entries predate the field. An entry
  1167. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1168. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1169. label when no description is on file. Returns None for an empty list so
  1170. callers can leave error_message unset.
  1171. """
  1172. if not hms_errors:
  1173. return None
  1174. from backend.app.services.hms_errors import get_error_description
  1175. parts: list[str] = []
  1176. for err in hms_errors:
  1177. try:
  1178. # `_hms_short_code` rather than a local derivation: this one used to
  1179. # format the error without masking it to 16 bits, so an `hms[]` entry
  1180. # whose code carries an alert-level group produced a five-digit label
  1181. # like "0500_3000A" — not a code the user can look up, and never a
  1182. # catalogue key, so the sentence was lost with it.
  1183. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1184. except (TypeError, ValueError):
  1185. continue
  1186. description = err.get("description") or get_error_description(short_code)
  1187. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1188. # groups and is not a code anyone can look up; its full code in the
  1189. # printer screen's four groups is (#2728).
  1190. full_code = str(err.get("full_code") or "")
  1191. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1192. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1193. return "; ".join(parts) if parts else None
  1194. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1195. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1196. print completes successfully. Gated to status=='completed': failed, cancelled
  1197. and aborted prints do not count as usage. Caller is responsible for committing
  1198. the session. No-op when the queue item has no linked library file (e.g. reprints
  1199. from an archive). See #1008."""
  1200. if queue_status != "completed" or item.library_file_id is None:
  1201. return
  1202. from backend.app.models.library import LibraryFile
  1203. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1204. if lib_file is None:
  1205. return
  1206. lib_file.print_count = (lib_file.print_count or 0) + 1
  1207. lib_file.last_printed_at = datetime.now(timezone.utc)
  1208. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1209. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1210. When on_print_complete fires with status 'failed' for a printer in this set we
  1211. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1212. rather than a 'print failed' notification.
  1213. """
  1214. _user_stopped_printers.add(printer_id)
  1215. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1216. _last_status_broadcast: dict[int, str] = {}
  1217. # Track printers where we've updated nozzle_count
  1218. _nozzle_count_updated: set[int] = set()
  1219. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1220. """Wait the debounce window then fire `on_printer_offline` if the printer
  1221. is still offline.
  1222. Scheduled by `on_printer_status_change` on the connected → disconnected
  1223. edge (#1752). Cancelled by the same handler if the printer reconnects
  1224. before the window elapses, so a single MQTT blip + recovery doesn't
  1225. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1226. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1227. route through the same status-change callback, so this covers both.
  1228. """
  1229. logger = logging.getLogger(__name__)
  1230. try:
  1231. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1232. still_offline = not printer_manager.is_connected(printer_id)
  1233. logger.info(
  1234. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1235. printer_id,
  1236. still_offline,
  1237. )
  1238. if not still_offline:
  1239. return
  1240. async with async_session() as db:
  1241. from backend.app.models.printer import Printer
  1242. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1243. printer = result.scalar_one_or_none()
  1244. if not printer:
  1245. logger.warning(
  1246. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1247. printer_id,
  1248. )
  1249. return
  1250. logger.info(
  1251. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1252. printer_id,
  1253. printer.name,
  1254. )
  1255. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1256. except asyncio.CancelledError:
  1257. raise
  1258. except Exception as e:
  1259. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1260. finally:
  1261. _printer_offline_notify_tasks.pop(printer_id, None)
  1262. def _hms_notify_key(error) -> str:
  1263. """What identifies a fault for notification de-duplication.
  1264. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1265. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1266. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1267. and -0006 together) shared a key and only the first was ever notified. An
  1268. entry without a full code falls back to attr and code together.
  1269. """
  1270. full_code = getattr(error, "full_code", "") or ""
  1271. if full_code:
  1272. return full_code.upper()
  1273. return f"{error.attr:08X}:{error.code}"
  1274. def _hms_fault_counts(error) -> bool:
  1275. """Whether a fault counts as a problem: the same rule the frontend's
  1276. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1277. It counts when Bambu publishes text for it or it offers action buttons, and
  1278. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1279. no actions does not count: those are things like "the top cover is open" or
  1280. "the chamber is hot, fan speed increased", which a printer can hold through
  1281. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1282. it always has; those are prompts such as "unable to start drying" (#2728).
  1283. """
  1284. if error.severity < 1:
  1285. return False
  1286. has_actions = bool(getattr(error, "actions", None))
  1287. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1288. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1289. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1290. """The new faults that count (see ``_hms_fault_counts``).
  1291. These go to the MQTT relay; the caller also needs a description before it
  1292. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1293. used to read ``severity >= 2`` when severity held the part byte; on the real
  1294. level that would drop the task-stopping errors (#2728).
  1295. """
  1296. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1297. def _take_new_hms_faults(printer_id: int, errors: list) -> list:
  1298. """The faults on this printer not notified yet, and record them as notified.
  1299. Tracking is updated before anything is sent, so concurrent status callbacks
  1300. cannot notify the same fault twice. The set is replaced, not extended: a
  1301. fault that clears and later returns is notified again, and the grace period
  1302. in the caller keeps a fault that flickers off for a moment from doing that.
  1303. """
  1304. current = {_hms_notify_key(e) for e in errors}
  1305. new = current - _notified_hms_errors.get(printer_id, set())
  1306. _notified_hms_errors[printer_id] = current
  1307. _hms_last_seen[printer_id] = time.time()
  1308. return _hms_errors_to_notify(errors, new)
  1309. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1310. """Handle printer status changes - broadcast via WebSocket."""
  1311. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1312. # transitions disconnected → connected — which covers both Bambuddy
  1313. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1314. # `reconcile_stale_active_prints` exactly once for this connection so
  1315. # any archive still in `status="printing"` that can't actually be
  1316. # running anymore (printer IDLE / different subtask / empty subtask)
  1317. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1318. # finished during a disconnect window + a smart-plug power cycle
  1319. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1320. # next boot. Reconciliation runs concurrently — it must not block the
  1321. # WebSocket dedup / broadcast logic below, and the connected edge is
  1322. # marked True BEFORE the await so concurrent status updates inside
  1323. # the same connection don't re-trigger reconciliation.
  1324. #
  1325. # Wait for a real push_status before reconciling (#1679): MQTT
  1326. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1327. # the connection, BEFORE `_request_push_all` round-trips. At that
  1328. # instant the `PrinterState` is still on construction defaults — most
  1329. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1330. # If reconcile spawns here, every in-flight archive falls through to
  1331. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1332. # creates a duplicate archive on the real PRINT COMPLETE and
  1333. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1334. # keeps the #1542 mechanism intact: once the first real push_status
  1335. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1336. # fires again with the flag still False — reconcile then runs against
  1337. # actual evidence.
  1338. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1339. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1340. _printer_reconciled_since_connect[printer_id] = True
  1341. spawn_background_task(
  1342. reconcile_stale_active_prints(printer_id),
  1343. name=f"reconcile-stale-prints-{printer_id}",
  1344. )
  1345. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1346. # Re-arm so the next reconnect triggers reconciliation again.
  1347. _printer_reconciled_since_connect[printer_id] = False
  1348. # Same edge, for the calibration table the AMS card reads its K values from.
  1349. #
  1350. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1351. # tables to ask for. A `state_known` gate alone is not enough: the first
  1352. # real push_status is what makes the state known, and the nozzle fields do
  1353. # not always arrive in it. Latching there would spend this connection's one
  1354. # attempt on a printer that could not yet say what was fitted.
  1355. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1356. if (
  1357. state.connected
  1358. and state_known
  1359. and nozzle_known
  1360. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1361. ):
  1362. _printer_kprofiles_primed_since_connect[printer_id] = True
  1363. spawn_background_task(
  1364. prime_kprofile_table(printer_id),
  1365. name=f"prime-kprofiles-{printer_id}",
  1366. )
  1367. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1368. _printer_kprofiles_primed_since_connect[printer_id] = False
  1369. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1370. # connected → disconnected. The "back online" channel is already covered
  1371. # by the print-failure notification (firmware reports gcode_state=FAILED
  1372. # on reconnect of an interrupted print), so we don't add a symmetric
  1373. # online event here.
  1374. prev_connected = _printer_last_connected.get(printer_id)
  1375. _printer_last_connected[printer_id] = state.connected
  1376. if prev_connected is True and not state.connected:
  1377. existing = _printer_offline_notify_tasks.get(printer_id)
  1378. if existing is None or existing.done():
  1379. logging.getLogger(__name__).info(
  1380. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1381. printer_id,
  1382. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1383. )
  1384. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1385. _maybe_notify_printer_offline(printer_id),
  1386. name=f"printer-offline-notify-{printer_id}",
  1387. )
  1388. elif state.connected:
  1389. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1390. if pending is not None and not pending.done():
  1391. logging.getLogger(__name__).info(
  1392. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1393. printer_id,
  1394. )
  1395. pending.cancel()
  1396. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1397. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1398. temps = state.temperatures or {}
  1399. nozzle_temp = round(temps.get("nozzle", 0))
  1400. bed_temp = round(temps.get("bed", 0))
  1401. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1402. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1403. # Auto-detect dual-nozzle printers from MQTT temperature data
  1404. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1405. _nozzle_count_updated.add(printer_id)
  1406. # Update nozzle_count in database
  1407. async with async_session() as db:
  1408. from backend.app.models.printer import Printer
  1409. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1410. printer = result.scalar_one_or_none()
  1411. if printer and printer.nozzle_count != 2:
  1412. printer.nozzle_count = 2
  1413. await db.commit()
  1414. logging.getLogger(__name__).info(
  1415. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1416. )
  1417. # Include target temps for heating phase detection
  1418. bed_target = round(temps.get("bed_target", 0))
  1419. nozzle_target = round(temps.get("nozzle_target", 0))
  1420. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1421. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1422. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1423. #
  1424. # dry_countdown_stalled rides along because it is the one drying signal the
  1425. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1426. # dry_time stopped moving, so on the frame that flips it every other member
  1427. # of this key is identical and the push would be deduplicated away. Mid-print
  1428. # a temperature would eventually break the tie, but a parked command on an
  1429. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1430. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1431. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1432. ams_dry_key = (
  1433. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1434. if state.raw_data
  1435. else ()
  1436. )
  1437. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1438. #
  1439. # The filament identity fields are here because Configure Slot writes
  1440. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1441. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1442. # matched, this function returned before broadcasting, and the card kept
  1443. # showing the old filament until the 30s fallback poll or a page reload —
  1444. # even though the configure route asks the printer for a fresh pushall and
  1445. # that push does carry the new values. Reset always worked, because it
  1446. # clears tray_type.
  1447. #
  1448. # These fields only change when someone configures a slot or swaps a spool,
  1449. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1450. ams_tray_key = (
  1451. tuple(
  1452. (
  1453. t.get("id"),
  1454. t.get("tray_type", ""),
  1455. t.get("state"),
  1456. t.get("tray_color", ""),
  1457. t.get("tray_info_idx", ""),
  1458. t.get("tray_sub_brands", ""),
  1459. t.get("cali_idx"),
  1460. )
  1461. for a in (state.raw_data.get("ams") or [])
  1462. for t in a.get("tray", [])
  1463. )
  1464. if state.raw_data
  1465. else ()
  1466. )
  1467. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1468. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1469. # in the AMS change-hash (tray fields only, and widening that would fire
  1470. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1471. # screen changed no key at all and the card's inlet badges sat stale until a
  1472. # reload. Like the filament-backup flag, these only move when someone
  1473. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1474. fts_key = (
  1475. state.fila_switch.installed if state.fila_switch else False,
  1476. tuple(sorted(state.ams_switch_inlet.items())),
  1477. # Which hotend holds which slot. Unlike the two above this does move
  1478. # mid-print, on every filament change — but only between discrete slots,
  1479. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1480. # it live: it decides which hotend the Load dialog may offer and whether
  1481. # Unload has anything to act on.
  1482. tuple(
  1483. sorted(
  1484. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1485. # Sort on the extruder id alone: the other members are nullable
  1486. # and comparing None with an int raises.
  1487. key=lambda entry: entry[0],
  1488. )
  1489. ),
  1490. )
  1491. status_key = (
  1492. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1493. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1494. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1495. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1496. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1497. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1498. )
  1499. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1500. if not is_active_print:
  1501. _unauthorized_print_kill_sent.discard(printer_id)
  1502. elif printer_id in _unauthorized_print_kill_sent:
  1503. # stop_print() was already sent for this print; avoid all further
  1504. # ownership and settings work until the printer leaves an active state.
  1505. pass
  1506. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1507. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1508. _unauthorized_print_kill_sent.discard(printer_id)
  1509. else:
  1510. kill_switch_enabled = False
  1511. authorization: bool | None = None
  1512. status_logger = logging.getLogger(__name__)
  1513. try:
  1514. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1515. if kill_switch_enabled:
  1516. async with async_session() as db:
  1517. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1518. except Exception as e:
  1519. # Fail safe: a database/reconciliation error must never turn into an
  1520. # irreversible stop of a print whose ownership is still unknown.
  1521. authorization = None
  1522. status_logger.warning(
  1523. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1524. )
  1525. if not kill_switch_enabled or authorization is True:
  1526. _unauthorized_print_kill_sent.discard(printer_id)
  1527. elif authorization is None:
  1528. _unauthorized_print_kill_sent.discard(printer_id)
  1529. status_logger.debug(
  1530. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1531. printer_id,
  1532. )
  1533. else:
  1534. try:
  1535. stopped = printer_manager.stop_print(printer_id)
  1536. if stopped:
  1537. _unauthorized_print_kill_sent.add(printer_id)
  1538. printer_info = printer_manager.get_printer(printer_id)
  1539. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1540. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1541. notification_data = {
  1542. "status": "stopped",
  1543. "filename": state.gcode_file or state.current_print or "",
  1544. "subtask_name": state.subtask_name or "",
  1545. "progress": state.progress,
  1546. "reason": "unauthorized_print",
  1547. }
  1548. status_logger.warning(
  1549. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1550. printer_id,
  1551. state.state,
  1552. )
  1553. try:
  1554. await ws_manager.broadcast(
  1555. {
  1556. "type": "kill_switch_triggered",
  1557. "printer_id": printer_id,
  1558. "printer_name": printer_name,
  1559. "filename": filename,
  1560. "reason": "unauthorized_print",
  1561. }
  1562. )
  1563. except Exception as e:
  1564. status_logger.warning(
  1565. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1566. )
  1567. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1568. if previous_task is not None and not previous_task.done():
  1569. previous_task.cancel()
  1570. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1571. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1572. name=f"kill-switch-notification-{printer_id}",
  1573. )
  1574. else:
  1575. status_logger.warning(
  1576. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1577. printer_id,
  1578. state.state,
  1579. )
  1580. except Exception as e:
  1581. status_logger.warning(
  1582. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1583. )
  1584. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1585. try:
  1586. printer_info = printer_manager.get_printer(printer_id)
  1587. if printer_info:
  1588. await mqtt_relay.on_printer_status(
  1589. printer_id,
  1590. state,
  1591. printer_info.name,
  1592. printer_info.serial_number,
  1593. printer_manager.is_awaiting_plate_clear(printer_id),
  1594. )
  1595. except Exception:
  1596. pass # Don't fail status callback if MQTT fails
  1597. if _last_status_broadcast.get(printer_id) == status_key:
  1598. return # No change, skip WebSocket broadcast
  1599. _last_status_broadcast[printer_id] = status_key
  1600. # Check for progress milestone notifications (25%, 50%, 75%)
  1601. progress = state.progress or 0
  1602. is_printing = state.state in ("RUNNING", "PRINTING")
  1603. if is_printing and progress > 0:
  1604. # Determine which milestone we've reached
  1605. current_milestone = 0
  1606. if progress >= 75:
  1607. current_milestone = 75
  1608. elif progress >= 50:
  1609. current_milestone = 50
  1610. elif progress >= 25:
  1611. current_milestone = 25
  1612. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1613. # If we've crossed a new milestone, send notification
  1614. if current_milestone > last_milestone:
  1615. _last_progress_milestone[printer_id] = current_milestone
  1616. try:
  1617. from backend.app.models.printer import Printer
  1618. # Read the printer in a short session and release the connection
  1619. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1620. # pinned a pooled connection per milestone, per printer (issue #2572).
  1621. async with async_session() as db:
  1622. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1623. printer = result.scalar_one_or_none()
  1624. printer_name = printer.name if printer else f"Printer {printer_id}"
  1625. filename = state.subtask_name or state.gcode_file or "Unknown"
  1626. # remaining_time is in minutes, convert to seconds for notification
  1627. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1628. # Capture camera snapshot for notification image attachment (no DB held).
  1629. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1630. # Notification send needs a session (provider/template lookups).
  1631. async with async_session() as db:
  1632. await notification_service.on_print_progress(
  1633. printer_id,
  1634. printer_name,
  1635. filename,
  1636. current_milestone,
  1637. db,
  1638. remaining_time_seconds,
  1639. image_data=image_data,
  1640. )
  1641. except Exception as e:
  1642. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1643. elif progress < 5:
  1644. # Reset milestone tracking when print restarts or new print begins
  1645. _last_progress_milestone[printer_id] = 0
  1646. _first_layer_notified[printer_id] = False
  1647. # HMS error codes that should not trigger notifications even though they
  1648. # have known descriptions (e.g. user-initiated actions, not real errors).
  1649. _HMS_NOTIFICATION_SUPPRESS = {
  1650. "0500_400E", # Printing was cancelled (user action, not an error)
  1651. }
  1652. # Check for new HMS errors and send notifications
  1653. current_hms_errors = getattr(state, "hms_errors", []) or []
  1654. if current_hms_errors:
  1655. new_errors = _take_new_hms_faults(printer_id, current_hms_errors)
  1656. if new_errors:
  1657. try:
  1658. from backend.app.models.printer import Printer
  1659. # Read the printer in a short session and release the connection
  1660. # BEFORE the ~15s camera snapshot below (issue #2572).
  1661. async with async_session() as db:
  1662. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1663. printer = result.scalar_one_or_none()
  1664. printer_name = printer.name if printer else f"Printer {printer_id}"
  1665. # Format error details for notification
  1666. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1667. module_names = {
  1668. 0x03: "Print/Task",
  1669. 0x05: "Nozzle/Extruder",
  1670. 0x07: "AMS/Filament",
  1671. 0x0C: "Motion Controller",
  1672. 0x12: "Chamber",
  1673. }
  1674. # Capture camera snapshot once for all error notifications (no DB held).
  1675. error_image_data = await _capture_snapshot_for_notification(
  1676. printer_id, printer, logging.getLogger(__name__)
  1677. )
  1678. # Notification sends need a session (provider/template lookups).
  1679. async with async_session() as db:
  1680. sent_count = 0
  1681. for error in new_errors:
  1682. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1683. # Build short code like "0700_8010"
  1684. # Mask to 16 bits to handle printers that send larger values
  1685. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1686. error_code_masked = error_code_int & 0xFFFF
  1687. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1688. # Only notify for errors Bambu publishes text for — printers
  1689. # send undocumented codes that aren't real errors, and Bambu
  1690. # lists some with empty text. Resolved at parse time (#2926);
  1691. # short_code is still needed for the suppression set below.
  1692. description = error.description
  1693. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1694. continue
  1695. error_type = f"{module_name} Error"
  1696. error_detail = description
  1697. await notification_service.on_printer_error(
  1698. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1699. )
  1700. sent_count += 1
  1701. if sent_count:
  1702. logging.getLogger(__name__).info(
  1703. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1704. )
  1705. # Also publish to MQTT relay (no DB): every new fault that
  1706. # counts, with or without text, the same set the UI counts.
  1707. printer_info = printer_manager.get_printer(printer_id)
  1708. if printer_info:
  1709. errors_data = [
  1710. {
  1711. "code": e.code,
  1712. "attr": e.attr,
  1713. "module": e.module,
  1714. "severity": e.severity,
  1715. }
  1716. for e in new_errors
  1717. ]
  1718. await mqtt_relay.on_printer_error(
  1719. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1720. )
  1721. except Exception as e:
  1722. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1723. else:
  1724. # No HMS errors — only clear tracking after a grace period to prevent
  1725. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1726. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1727. # on/off every few seconds as conditions fluctuate around thresholds.
  1728. if printer_id in _notified_hms_errors:
  1729. last_seen = _hms_last_seen.get(printer_id, 0)
  1730. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1731. _notified_hms_errors.pop(printer_id, None)
  1732. _hms_last_seen.pop(printer_id, None)
  1733. await ws_manager.send_printer_status(
  1734. printer_id,
  1735. printer_state_to_dict(
  1736. state,
  1737. printer_id,
  1738. printer_manager.get_model(printer_id),
  1739. printer_manager.get_drying_targets(printer_id),
  1740. ),
  1741. )
  1742. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1743. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1744. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1745. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1746. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1747. K-profiles are per-nozzle and the printer's calibration table is numbered
  1748. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1749. switch's other inlet therefore silently invalidates every configured slot in
  1750. it: the index stays put and now resolves against the other nozzle's table.
  1751. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1752. and 0.020 on the right kept the left profile after the move, and a manual
  1753. RFID re-read only re-asserted the same wrong one.
  1754. Configuring a slot is a deliberate preparation step, so this re-selects
  1755. rather than re-configures: only the calibration binding moves, and only for
  1756. slots whose spool already has a stored profile for the new nozzle. A slot
  1757. Bambuddy knows nothing about is left exactly as the operator left it.
  1758. """
  1759. logger = logging.getLogger(__name__)
  1760. target_extruder = extruder_for_inlet(inlet)
  1761. if target_extruder is None:
  1762. return
  1763. client = printer_manager.get_client(printer_id)
  1764. state = printer_manager.get_status(printer_id)
  1765. if not client or not state or not state.raw_data:
  1766. return
  1767. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1768. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1769. # the nozzle width, which changes both the K profile to select and the
  1770. # preset the slot should carry.
  1771. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1772. ams_raw = state.raw_data.get("ams")
  1773. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1774. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1775. if not unit:
  1776. return
  1777. try:
  1778. async with async_session() as db:
  1779. for tray in unit.get("tray", []):
  1780. tray_id = int(tray.get("id", -1))
  1781. if tray_id < 0 or not tray.get("tray_type"):
  1782. continue
  1783. current_idx = tray.get("cali_idx")
  1784. profile = await find_slot_kprofile_for_extruder(
  1785. db,
  1786. printer_id,
  1787. ams_id,
  1788. tray_id,
  1789. target_extruder,
  1790. nozzle_diameter,
  1791. printer_manager.get_model(printer_id),
  1792. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1793. )
  1794. if profile is None or profile.cali_idx is None:
  1795. continue
  1796. if current_idx == profile.cali_idx:
  1797. continue # Already on the right one.
  1798. logger.info(
  1799. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1800. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1801. printer_id,
  1802. ams_id,
  1803. tray_id,
  1804. inlet,
  1805. target_extruder,
  1806. profile.name,
  1807. current_idx,
  1808. profile.cali_idx,
  1809. profile.k_value,
  1810. )
  1811. client.extrusion_cali_sel(
  1812. ams_id=ams_id,
  1813. tray_id=tray_id,
  1814. cali_idx=profile.cali_idx,
  1815. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1816. nozzle_diameter=nozzle_diameter,
  1817. )
  1818. except Exception as e:
  1819. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1820. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  1821. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  1822. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  1823. from the delayed re-check -- which is why it takes the AMS data and print
  1824. state as arguments instead of reading them from the push (#3186).
  1825. """
  1826. logger = logging.getLogger(__name__)
  1827. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1828. # Auto-unlink spool assignments with stale fingerprints. Under the
  1829. # per-printer assignment lock since #3186: the held-removal re-check runs
  1830. # this outside any MQTT push, so it can now overlap one.
  1831. try:
  1832. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1833. from sqlalchemy.orm import selectinload
  1834. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1835. from backend.app.models.spool import Spool as _Spool
  1836. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1837. from backend.app.services.ams_slot_presence import spool_present
  1838. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1839. # Built-in assignments only. Since #2812 they survive a switch to
  1840. # Spoolman mode rather than being deleted by it, and this pass ends
  1841. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1842. # time as the AMS contents changed under the other mode, undoing the
  1843. # preservation more slowly but just as completely.
  1844. assignments = []
  1845. if not await spoolman_owns_assignments(db):
  1846. result = await db.execute(
  1847. select(SA)
  1848. .where(SA.printer_id == printer_id)
  1849. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1850. )
  1851. assignments = result.scalars().all()
  1852. # ``printing_now`` (top of this function) keeps a runout from
  1853. # unlinking the spool that fed the print — the next idle-time pass
  1854. # unlinks it if the user really did take it out.
  1855. stale = []
  1856. # Removals this pass is holding rather than unlinking (#3186).
  1857. held: set[tuple] = set()
  1858. for assignment in assignments:
  1859. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1860. if assignment.ams_id == 255:
  1861. ps = printer_manager.get_status(printer_id)
  1862. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1863. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1864. current_tray = None
  1865. for vt in vt_tray_raw:
  1866. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1867. current_tray = vt
  1868. break
  1869. if not current_tray:
  1870. # vt_tray data may not have arrived yet — keep assignment
  1871. continue
  1872. else:
  1873. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1874. if not current_tray:
  1875. if printing_now:
  1876. logger.info(
  1877. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1878. assignment.spool_id,
  1879. assignment.ams_id,
  1880. assignment.tray_id,
  1881. )
  1882. continue
  1883. # A whole AMS unit can drop out of one push and come back in
  1884. # the next; only a slot that stays gone is a removal (#3186).
  1885. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  1886. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  1887. held.add(hold_key)
  1888. logger.info(
  1889. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  1890. "unlinking if it is still gone in %ds",
  1891. assignment.spool_id,
  1892. assignment.ams_id,
  1893. assignment.tray_id,
  1894. int(slot_unlink_grace.GRACE_SECONDS),
  1895. )
  1896. continue
  1897. logger.info(
  1898. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1899. assignment.spool_id,
  1900. assignment.ams_id,
  1901. assignment.tray_id,
  1902. )
  1903. stale.append(assignment) # Slot empty
  1904. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1905. # A Bambu Lab spool is in this slot — check if it's the same spool
  1906. # that's currently assigned. If yes, keep the assignment (avoids
  1907. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1908. # the printer's filament preset on every startup).
  1909. tray_uuid = current_tray.get("tray_uuid", "")
  1910. tag_uid = current_tray.get("tag_uid", "")
  1911. spool = assignment.spool
  1912. spool_matches = False
  1913. if spool:
  1914. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1915. spool.tag_uid
  1916. and tag_uid
  1917. and tag_uid != "0000000000000000"
  1918. and spool.tag_uid.upper() == tag_uid.upper()
  1919. ):
  1920. spool_matches = True
  1921. if spool_matches:
  1922. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1923. cur_color = current_tray.get("tray_color", "")
  1924. cur_type = current_tray.get("tray_type", "")
  1925. fp_color = assignment.fingerprint_color or ""
  1926. fp_type = assignment.fingerprint_type or ""
  1927. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1928. assignment.fingerprint_color = cur_color
  1929. assignment.fingerprint_type = cur_type
  1930. logger.debug(
  1931. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1932. assignment.spool_id,
  1933. assignment.ams_id,
  1934. assignment.tray_id,
  1935. )
  1936. continue
  1937. # Different BL spool or unrecognized — unlink so auto-assign can match
  1938. logger.info(
  1939. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1940. assignment.spool_id,
  1941. assignment.ams_id,
  1942. assignment.tray_id,
  1943. tray_uuid,
  1944. )
  1945. stale.append(assignment)
  1946. else:
  1947. cur_color = current_tray.get("tray_color", "")
  1948. cur_type = current_tray.get("tray_type", "")
  1949. cur_state = current_tray.get("state")
  1950. fp_color = assignment.fingerprint_color or ""
  1951. fp_type = assignment.fingerprint_type or ""
  1952. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1953. # the slot was empty when the user pre-assigned via SpoolBuddy
  1954. # (the firmware drops ams_filament_setting on empty slots, so
  1955. # MQTT was deferred). The moment any filament gets inserted
  1956. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1957. # reconfigured spool — fire the deferred configuration.
  1958. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1959. # extruder" code) OR, on firmwares that don't use the state
  1960. # enum meaningfully, a non-empty tray_type when state is
  1961. # NOT one of the firmware's explicit empty signals (9, 10).
  1962. # state-only was wrong for firmwares that never set 11 — A1
  1963. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1964. # always report state=3 — so the replay never fired for them
  1965. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1966. # explicit "empty" signals authoritative over any stale
  1967. # tray_type that might survive the relay's auto-clearing.
  1968. #
  1969. # tray_exist_bits comes first because that guard cannot tell
  1970. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  1971. # writes state=9 when the bit is 0 and leaves it there when the
  1972. # bit returns. A non-RFID spool inserted into a pre-assigned
  1973. # slot brings no tray_type with it, so the stale 9 made this
  1974. # expression false forever and the deferred config never fired
  1975. # — the deadlock #1322 removed from the assign path, still in
  1976. # place here (#3084, #3100).
  1977. loaded = spool_present(current_tray) is True or (
  1978. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1979. )
  1980. if not fp_type.strip() and loaded and assignment.spool:
  1981. try:
  1982. from backend.app.api.routes.inventory import (
  1983. apply_spool_to_slot_via_mqtt,
  1984. )
  1985. await apply_spool_to_slot_via_mqtt(
  1986. db=db,
  1987. current_user=None,
  1988. spool=assignment.spool,
  1989. printer_id=printer_id,
  1990. ams_id=assignment.ams_id,
  1991. tray_id=assignment.tray_id,
  1992. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1993. current_tray_type=cur_type,
  1994. )
  1995. logger.info(
  1996. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1997. assignment.spool_id,
  1998. printer_id,
  1999. assignment.ams_id,
  2000. assignment.tray_id,
  2001. )
  2002. except Exception:
  2003. logger.exception(
  2004. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2005. assignment.spool_id,
  2006. printer_id,
  2007. assignment.ams_id,
  2008. assignment.tray_id,
  2009. )
  2010. assignment.fingerprint_color = cur_color
  2011. assignment.fingerprint_type = cur_type
  2012. continue
  2013. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2014. # Blank tray data mid-print is a runout, not a swap: the
  2015. # firmware clears colour and type when it unloads a spool
  2016. # it just emptied. Unlinking here would erase the record
  2017. # of which spool fed the print so far.
  2018. if printing_now and not cur_color.strip() and not cur_type.strip():
  2019. logger.info(
  2020. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2021. "(runout?)",
  2022. assignment.spool_id,
  2023. assignment.ams_id,
  2024. assignment.tray_id,
  2025. )
  2026. continue
  2027. # Same reasoning off the print, on firmware's own say-so:
  2028. # a blank tray report from a slot whose tray_exist_bits
  2029. # bit is set describes a spool the AMS cannot identify —
  2030. # a non-RFID one, or one whose slot was reset — not a
  2031. # spool that was taken out. Deleting the assignment there
  2032. # threw away the identity the user had supplied, which is
  2033. # the only place it existed (#3100). A slot the bit calls
  2034. # empty, or one that carries no bit at all, still unlinks.
  2035. #
  2036. # Unless the slot was reported empty first: a removal
  2037. # already held means a spool came out and another went
  2038. # in, so the blank report keeps the hold running below
  2039. # rather than cancelling it (#3186).
  2040. if (
  2041. spool_present(current_tray) is True
  2042. and not cur_color.strip()
  2043. and not cur_type.strip()
  2044. and not slot_unlink_grace.is_held(
  2045. printer_id,
  2046. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2047. )
  2048. ):
  2049. logger.info(
  2050. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2051. "tray reports no filament data yet",
  2052. assignment.spool_id,
  2053. assignment.ams_id,
  2054. assignment.tray_id,
  2055. )
  2056. continue
  2057. # A blank report the presence bit does not vouch for is
  2058. # still only one push. An idle X1C cleared a whole AMS
  2059. # unit's bits, colour and type for a moment and lost
  2060. # four saved assignments that way (#3186); unlink only
  2061. # if the slot is still blank after the grace period.
  2062. if not cur_color.strip() and not cur_type.strip():
  2063. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2064. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2065. held.add(hold_key)
  2066. logger.info(
  2067. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2068. "unlinking if it is still blank in %ds",
  2069. assignment.spool_id,
  2070. assignment.ams_id,
  2071. assignment.tray_id,
  2072. int(slot_unlink_grace.GRACE_SECONDS),
  2073. )
  2074. continue
  2075. # Fingerprint mismatch — but check if tray now matches the
  2076. # assigned spool (e.g. auto-configure changed the tray).
  2077. # Both sides are reduced to the type the slot can carry
  2078. # before comparing: the assign path writes that rather
  2079. # than the spool's raw material (#2902), so a spool whose
  2080. # material is a product line — "PLA+", "HTPLA" — reports
  2081. # back as "PLA" and would otherwise fail this check and
  2082. # be auto-unlinked from the slot it was just assigned to.
  2083. # Reducing the printer's side too keeps slots configured
  2084. # by an older Bambuddy, still reporting "PLA+", matching.
  2085. spool = assignment.spool
  2086. if spool:
  2087. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2088. # Two ways the assign path can have arrived at the
  2089. # slot's type, so both count as "we wrote this".
  2090. # The material column is one; the spool's preset is
  2091. # the other, and it outranks the material when the
  2092. # spool has one -- a spool whose material says PLA
  2093. # and whose preset is "Bambu PLA Aero" puts
  2094. # PLA-AERO in the slot (#2902). Read from the stored
  2095. # preset name rather than resolving the preset,
  2096. # because this runs on every AMS push and a cloud
  2097. # lookup here would be both slow and unavailable on
  2098. # the unauthenticated replay path.
  2099. spool_types = {printer_filament_type(spool.material).upper()}
  2100. if spool.slicer_filament_name:
  2101. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2102. # An imported local preset stores its type outright,
  2103. # which is what the assign path used -- and the name
  2104. # above may be unset. One keyed read, and only on a
  2105. # mismatch, which is rare.
  2106. #
  2107. # slicer_filament is free text up to fifty characters,
  2108. # so the digits have to be checked against the range
  2109. # of the integer primary key they are about to be
  2110. # compared with. Postgres raises on an out-of-range
  2111. # integer rather than simply not matching, and that
  2112. # would poison this session and abandon the rest of
  2113. # the cleanup pass.
  2114. lp_ref = (spool.slicer_filament or "").strip()
  2115. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2116. from backend.app.models.local_preset import LocalPreset as _LP
  2117. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2118. if lp_type:
  2119. spool_types.add(printer_filament_type(lp_type).upper())
  2120. if (
  2121. _colors_similar(cur_color, spool_color)
  2122. and printer_filament_type(cur_type).upper() in spool_types
  2123. ):
  2124. logger.info(
  2125. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2126. assignment.spool_id,
  2127. assignment.ams_id,
  2128. assignment.tray_id,
  2129. )
  2130. assignment.fingerprint_color = cur_color
  2131. assignment.fingerprint_type = cur_type
  2132. continue
  2133. logger.info(
  2134. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2135. assignment.spool_id,
  2136. assignment.ams_id,
  2137. assignment.tray_id,
  2138. cur_color,
  2139. cur_type,
  2140. fp_color,
  2141. fp_type,
  2142. spool.rgba if spool else "?",
  2143. spool.material if spool else "?",
  2144. )
  2145. stale.append(assignment) # Spool changed
  2146. slot_unlink_grace.settle(printer_id, "inventory", held)
  2147. # Snapshot slots before delete — ORM attribute access after the
  2148. # commit would refresh against a deleted row.
  2149. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2150. for a in stale:
  2151. await db.delete(a)
  2152. if stale:
  2153. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2154. # Commit any changes (stale deletions and/or fingerprint updates)
  2155. await db.commit()
  2156. # Tell open browsers the assignment is gone (#2575). Only the manual
  2157. # REST assign/unassign endpoints broadcast this event; without it the
  2158. # frontend's spool-assignments cache keeps rendering the unlinked
  2159. # spool on the slot until an unrelated refetch — which reads exactly
  2160. # like "the fix didn't work" (reporter verified: a browser refresh
  2161. # after the swap showed the correct state all along).
  2162. for ams_id, tray_id in unlinked_slots:
  2163. await ws_manager.broadcast(
  2164. {
  2165. "type": "spool_assignment_changed",
  2166. "printer_id": printer_id,
  2167. "ams_id": ams_id,
  2168. "tray_id": tray_id,
  2169. }
  2170. )
  2171. except Exception as e:
  2172. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2173. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2174. """Delete Spoolman slot rows whose held removal has run its grace period.
  2175. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2176. talks to Spoolman for every tray; this only needs the local rows, so it
  2177. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2178. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2179. not in a slot the presence bit calls occupied -- and nothing else.
  2180. """
  2181. logger = logging.getLogger(__name__)
  2182. try:
  2183. async with async_session() as db:
  2184. from backend.app.api.routes.settings import get_setting
  2185. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2186. from backend.app.services.ams_slot_presence import spool_present
  2187. enabled = await get_setting(db, "spoolman_enabled")
  2188. if not enabled or enabled.lower() != "true":
  2189. return
  2190. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2191. if sync_mode and sync_mode != "auto":
  2192. return
  2193. trays: dict[tuple[int, int], dict] = {}
  2194. for ams_unit in ams_data or []:
  2195. if not isinstance(ams_unit, dict):
  2196. continue
  2197. for tray in ams_unit.get("tray", []):
  2198. if isinstance(tray, dict):
  2199. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2200. rows = (
  2201. (
  2202. await db.execute(
  2203. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2204. )
  2205. )
  2206. .scalars()
  2207. .all()
  2208. )
  2209. held: set[tuple] = set()
  2210. expired: list[tuple[int, int]] = []
  2211. for row in rows:
  2212. tray = trays.get((row.ams_id, row.tray_id))
  2213. if tray is None or printing_now:
  2214. continue
  2215. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2216. continue
  2217. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2218. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2219. continue
  2220. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2221. expired.append((row.ams_id, row.tray_id))
  2222. else:
  2223. held.add(hold_key)
  2224. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2225. if not expired:
  2226. return
  2227. # A statement rather than ORM deletes, like the sync pass: the two
  2228. # can overlap, and a row the other already removed must not fail
  2229. # this commit.
  2230. for ams_id, tray_id in expired:
  2231. await db.execute(
  2232. delete(SpoolmanSlotAssignment).where(
  2233. SpoolmanSlotAssignment.printer_id == printer_id,
  2234. SpoolmanSlotAssignment.ams_id == ams_id,
  2235. SpoolmanSlotAssignment.tray_id == tray_id,
  2236. )
  2237. )
  2238. await db.commit()
  2239. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2240. for ams_id, tray_id in expired:
  2241. await ws_manager.broadcast(
  2242. {
  2243. "type": "spool_assignment_changed",
  2244. "printer_id": printer_id,
  2245. "ams_id": ams_id,
  2246. "tray_id": tray_id,
  2247. }
  2248. )
  2249. except Exception as e:
  2250. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2251. async def _recheck_held_unlinks(printer_id: int) -> None:
  2252. """Re-run just the slot cleanup against the printer's current AMS state.
  2253. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2254. passes otherwise run only when the AMS hash changes, and a slot that went
  2255. empty and stayed empty may never change it again.
  2256. """
  2257. status = printer_manager.get_status(printer_id)
  2258. # A disconnected printer's state is its last report, not a new one: acting
  2259. # on it would "confirm" a removal nobody has seen for the whole grace
  2260. # period. Leave the holds; the first push after reconnecting decides.
  2261. if status is None or not status.connected:
  2262. return
  2263. ams_raw = status.raw_data.get("ams")
  2264. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2265. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2266. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2267. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2268. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2269. async def on_ams_change(printer_id: int, ams_data: list):
  2270. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2271. logger = logging.getLogger(__name__)
  2272. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2273. # on_print_complete may pop _active_sessions during our awaits (#880).
  2274. from backend.app.services.usage_tracker import _active_sessions
  2275. _print_active = printer_id in _active_sessions
  2276. # A slot that reports empty while a print is running is a filament runout,
  2277. # not a spool swap: the spool is still physically in the AMS, just
  2278. # consumed. Dropping either inventory backend's slot link there loses the
  2279. # only record of which spool fed the print, so the completion path can't
  2280. # charge the runout segment to anything. Both cleanup passes below consult
  2281. # this; computed once, up front, so neither depends on the other having run.
  2282. _unlink_state = printer_manager.get_status(printer_id)
  2283. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2284. # MQTT relay - publish AMS change
  2285. try:
  2286. printer_info = printer_manager.get_printer(printer_id)
  2287. if printer_info:
  2288. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2289. except Exception:
  2290. pass # Don't fail AMS callback if MQTT fails
  2291. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2292. # This ensures frontend gets immediate updates when AMS slots are configured
  2293. try:
  2294. state = printer_manager.get_status(printer_id)
  2295. if state:
  2296. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2297. await ws_manager.send_printer_status(
  2298. printer_id,
  2299. printer_state_to_dict(
  2300. state,
  2301. printer_id,
  2302. printer_manager.get_model(printer_id),
  2303. printer_manager.get_drying_targets(printer_id),
  2304. ),
  2305. )
  2306. except Exception as e:
  2307. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2308. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2309. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2310. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2311. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2312. # "no existing assignment" for the same (printer, ams, tray) and race to
  2313. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2314. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2315. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2316. try:
  2317. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2318. from sqlalchemy.orm import selectinload
  2319. from backend.app.api.routes.settings import get_setting
  2320. from backend.app.models.spool import Spool
  2321. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2322. from backend.app.services.spool_tag_matcher import (
  2323. auto_assign_spool,
  2324. create_spool_from_tray,
  2325. find_matching_untagged_spool,
  2326. get_spool_by_tag,
  2327. is_bambu_tag,
  2328. is_valid_tag,
  2329. link_tag_to_inventory_spool,
  2330. )
  2331. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2332. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2333. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2334. if not _spoolman_on or _spoolman_on.lower() != "true":
  2335. for ams_unit in ams_data:
  2336. if not isinstance(ams_unit, dict):
  2337. continue
  2338. ams_id = int(ams_unit.get("id", 0))
  2339. for tray in ams_unit.get("tray", []):
  2340. if not isinstance(tray, dict):
  2341. continue
  2342. tray_id = int(tray.get("id", 0))
  2343. tag_uid = tray.get("tag_uid", "")
  2344. tray_uuid = tray.get("tray_uuid", "")
  2345. tray_info_idx = tray.get("tray_info_idx", "")
  2346. if not tray.get("tray_type"):
  2347. # Slot reported empty — drop any cached unknown-tag
  2348. # broadcast so reinserting the same spool re-prompts.
  2349. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2350. continue # Empty slot
  2351. # Check if assignment already exists for this slot
  2352. existing = await db.execute(
  2353. select(SA)
  2354. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2355. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2356. )
  2357. existing_assignment = existing.scalar_one_or_none()
  2358. if existing_assignment:
  2359. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2360. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2361. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2362. # Skip during active prints: the usage tracker handles deduction
  2363. # precisely via 3MF data on print completion. Without this guard the
  2364. # AMS remain% SET and the usage tracker ADD both fire from the same
  2365. # MQTT message, doubling the deduction (#880).
  2366. if _print_active:
  2367. continue
  2368. remain_raw = tray.get("remain")
  2369. if (
  2370. remain_raw is not None
  2371. and existing_assignment.spool
  2372. and not existing_assignment.spool.weight_locked
  2373. ):
  2374. try:
  2375. remain_val = int(remain_raw)
  2376. except (TypeError, ValueError):
  2377. remain_val = -1
  2378. if 1 <= remain_val <= 100:
  2379. lw = existing_assignment.spool.label_weight or 1000
  2380. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2381. current_used = existing_assignment.spool.weight_used or 0
  2382. if new_used > current_used + 1:
  2383. logger.info(
  2384. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2385. existing_assignment.spool_id,
  2386. current_used,
  2387. new_used,
  2388. remain_val,
  2389. )
  2390. existing_assignment.spool.weight_used = new_used
  2391. await db.commit()
  2392. # Re-apply stored K-profile when the live tray's
  2393. # cali_idx drifted from the spool's stored profile.
  2394. # This catches "reset slot → re-read" and any other
  2395. # path where the firmware loses the user's K-profile
  2396. # selection while the SpoolAssignment row persists.
  2397. # Per the maintainer's rule: any time a spool tag is
  2398. # identified and matches inventory, the slot must be
  2399. # configured with the spool's stored settings. Without
  2400. # this block the existing-assignment branch only ran
  2401. # weight-sync and let the firmware-default cali_idx win.
  2402. try:
  2403. spool = existing_assignment.spool
  2404. if (
  2405. spool is not None
  2406. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2407. and spool.k_profiles
  2408. ):
  2409. state = printer_manager.get_status(printer_id)
  2410. slot_nozzle = resolve_slot_nozzle(
  2411. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2412. )
  2413. nozzle_diameter = slot_nozzle.diameter
  2414. slot_extruder = slot_nozzle.extruder
  2415. # Prefer exact extruder match, fall back to
  2416. # extruder-agnostic kp for the same printer +
  2417. # nozzle. Avoids hard-skipping when the AMS is
  2418. # mapped differently than at calibration time.
  2419. matching_kp = None
  2420. fallback_kp = None
  2421. for kp in spool.k_profiles:
  2422. if (
  2423. kp.printer_id != printer_id
  2424. or kp.nozzle_diameter != nozzle_diameter
  2425. or kp.cali_idx is None
  2426. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2427. ):
  2428. continue
  2429. if (
  2430. slot_extruder is not None
  2431. and kp.extruder is not None
  2432. and kp.extruder == slot_extruder
  2433. ):
  2434. matching_kp = kp
  2435. break
  2436. if fallback_kp is None:
  2437. fallback_kp = kp
  2438. chosen_kp = matching_kp or fallback_kp
  2439. if chosen_kp is not None:
  2440. live_cali_idx = tray.get("cali_idx")
  2441. # Only fire MQTT when the printer's live
  2442. # cali_idx differs from the stored value.
  2443. # Avoids spamming the broker on every
  2444. # MQTT push during steady-state operation.
  2445. if live_cali_idx != chosen_kp.cali_idx:
  2446. client = printer_manager.get_client(printer_id)
  2447. if client:
  2448. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2449. client.extrusion_cali_sel(
  2450. ams_id=ams_id,
  2451. tray_id=tray_id,
  2452. cali_idx=chosen_kp.cali_idx,
  2453. filament_id=cali_filament_id,
  2454. nozzle_diameter=nozzle_diameter,
  2455. )
  2456. logger.info(
  2457. "Re-applied K-profile cali_idx=%d for spool %d "
  2458. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2459. chosen_kp.cali_idx,
  2460. spool.id,
  2461. printer_id,
  2462. ams_id,
  2463. tray_id,
  2464. live_cali_idx,
  2465. )
  2466. except Exception:
  2467. logger.exception(
  2468. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2469. printer_id,
  2470. ams_id,
  2471. tray_id,
  2472. )
  2473. continue
  2474. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2475. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2476. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2477. if not spool:
  2478. # Try matching an untagged inventory spool (same material/color)
  2479. spool = await find_matching_untagged_spool(db, tray)
  2480. if spool:
  2481. await link_tag_to_inventory_spool(db, spool, tray)
  2482. elif _auto_add_unknown:
  2483. spool = await create_spool_from_tray(db, tray)
  2484. else:
  2485. # Auto-add disabled: surface the slot so the
  2486. # user can add it manually via the UI.
  2487. await _broadcast_unknown_tag(
  2488. printer_id=printer_id,
  2489. ams_id=ams_id,
  2490. tray_id=tray_id,
  2491. tag_uid=tag_uid,
  2492. tray_uuid=tray_uuid,
  2493. tray_type=tray.get("tray_type"),
  2494. tray_color=tray.get("tray_color"),
  2495. tray_sub_brands=tray.get("tray_sub_brands"),
  2496. tray_count=len(ams_unit.get("tray", [])),
  2497. )
  2498. continue
  2499. # Slot matched (existing tag, untagged inventory
  2500. # match, or freshly auto-created spool) — drop any
  2501. # stale dedup so a future tag swap re-prompts.
  2502. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2503. await auto_assign_spool(
  2504. printer_id,
  2505. ams_id,
  2506. tray_id,
  2507. spool,
  2508. printer_manager,
  2509. db,
  2510. tray_info_idx=tray_info_idx,
  2511. )
  2512. await db.commit()
  2513. await ws_manager.broadcast(
  2514. {
  2515. "type": "spool_auto_assigned",
  2516. "printer_id": printer_id,
  2517. "ams_id": ams_id,
  2518. "tray_id": tray_id,
  2519. "spool_id": spool.id,
  2520. }
  2521. )
  2522. logger.info(
  2523. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2524. spool.id,
  2525. printer_id,
  2526. ams_id,
  2527. tray_id,
  2528. )
  2529. elif is_valid_tag(tag_uid, tray_uuid):
  2530. # Non-BL spool with some tag — let user choose
  2531. await _broadcast_unknown_tag(
  2532. printer_id=printer_id,
  2533. ams_id=ams_id,
  2534. tray_id=tray_id,
  2535. tag_uid=tag_uid,
  2536. tray_uuid=tray_uuid,
  2537. tray_type=tray.get("tray_type"),
  2538. tray_color=tray.get("tray_color"),
  2539. tray_sub_brands=tray.get("tray_sub_brands"),
  2540. tray_count=len(ams_unit.get("tray", [])),
  2541. )
  2542. # No-tag slots (generic non-RFID filament) are left alone:
  2543. # nothing to identify, prompting "+ Add" would just create
  2544. # ghost spools with empty tags on every confirm.
  2545. except Exception as e:
  2546. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2547. try:
  2548. async with async_session() as db:
  2549. from backend.app.api.routes.settings import get_setting
  2550. from backend.app.models.printer import Printer
  2551. # Check if Spoolman is enabled
  2552. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2553. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2554. return
  2555. # Check sync mode
  2556. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2557. if sync_mode and sync_mode != "auto":
  2558. return # Only sync on auto mode
  2559. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2560. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2561. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2562. # always owned by per-print tracking, never by AMS auto-sync. The
  2563. # setting is still read by the settings UI for backwards compat but
  2564. # has no effect on the sync path here.
  2565. # Get Spoolman URL
  2566. spoolman_url = await get_setting(db, "spoolman_url")
  2567. if not spoolman_url:
  2568. return
  2569. # Get or create Spoolman client
  2570. client = await get_spoolman_client()
  2571. if not client:
  2572. try:
  2573. client = await init_spoolman_client(spoolman_url)
  2574. except ValueError as exc:
  2575. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2576. return
  2577. # Check if Spoolman is reachable
  2578. if not await client.health_check():
  2579. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2580. return
  2581. # Get printer name for location
  2582. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2583. printer = result.scalar_one_or_none()
  2584. printer_name = printer.name if printer else f"Printer {printer_id}"
  2585. # OPTIMIZATION: Fetch all spools once before processing trays
  2586. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2587. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2588. try:
  2589. cached_spools = await client.get_spools()
  2590. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2591. except Exception as e:
  2592. logger.error(
  2593. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2594. printer_id,
  2595. e,
  2596. )
  2597. return
  2598. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2599. from sqlalchemy.orm import selectinload
  2600. from backend.app.models.spool_assignment import SpoolAssignment
  2601. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2602. from backend.app.services.ams_slot_presence import spool_present
  2603. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2604. # Built-in remaining weight, used by sync_ams_tray only when the
  2605. # firmware reports an unusable remain%/tray_weight for a slot.
  2606. #
  2607. # Left empty since #2812. This block runs in Spoolman mode only,
  2608. # and until then the built-in table was emptied on the switch, so
  2609. # there was never anything here to read and the fallback was inert.
  2610. # Preserving those rows makes it live again, and it is keyed by slot
  2611. # rather than by spool: after a mode switch the tray may well hold
  2612. # different filament, and ``create_spool`` writes ``remaining_weight``
  2613. # unconditionally, so a stale figure would be seeded into a brand new
  2614. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2615. # intent survives for whoever revisits the cross-mode fallback.
  2616. inventory_weights: dict[tuple[int, int], float] = {}
  2617. if not await spoolman_owns_assignments(db):
  2618. try:
  2619. assign_result = await db.execute(
  2620. select(SpoolAssignment)
  2621. .options(selectinload(SpoolAssignment.spool))
  2622. .where(SpoolAssignment.printer_id == printer_id)
  2623. )
  2624. for assignment in assign_result.scalars().all():
  2625. spool = assignment.spool
  2626. if spool and spool.label_weight > 0:
  2627. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2628. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2629. except Exception as e:
  2630. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2631. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2632. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2633. try:
  2634. slot_result = await db.execute(
  2635. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2636. )
  2637. for slot in slot_result.scalars().all():
  2638. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2639. except Exception as e:
  2640. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2641. # Sync each AMS tray and collect slot changes for DB persistence
  2642. synced = 0
  2643. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2644. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2645. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2646. for ams_unit in ams_data:
  2647. if not isinstance(ams_unit, dict):
  2648. continue
  2649. ams_id = int(ams_unit.get("id", 0))
  2650. trays = ams_unit.get("tray", [])
  2651. for tray_data in trays:
  2652. if not isinstance(tray_data, dict):
  2653. continue
  2654. tray_id_raw = int(tray_data.get("id", 0))
  2655. tray = client.parse_ams_tray(ams_id, tray_data)
  2656. if not tray:
  2657. # Empty tray slot — record for local assignment cleanup
  2658. # and drop any cached unknown-tag broadcast so a
  2659. # reinserted spool re-prompts.
  2660. #
  2661. # Not during a running print: a slot that empties there
  2662. # is a filament runout, and the spool is still in the
  2663. # AMS. `spoolman_slot_assignments` is how a tag-less
  2664. # spool assigned through the Bambuddy UI is resolved at
  2665. # completion (#1459), so deleting the row mid-print
  2666. # loses the runout segment's usage — the same failure
  2667. # the internal inventory's auto-unlink had.
  2668. #
  2669. # Nor when firmware's presence bit says the slot is
  2670. # occupied. parse_ams_tray calls a tray with no type or
  2671. # no colour empty, and a spool the AMS cannot read has
  2672. # neither until something configures it — so a tag-less
  2673. # spool assigned through the UI had its row deleted by
  2674. # the first idle push after it was inserted. Same
  2675. # deletion as the internal inventory's in #3100, same
  2676. # answer, so the two modes stay in step.
  2677. #
  2678. # And only once the slot has stayed empty for the grace
  2679. # period -- the internal inventory's #3186 answer, for
  2680. # the same one-push blank.
  2681. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2682. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2683. if not printing_now and (
  2684. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2685. ):
  2686. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2687. empty_slots.append((ams_id, tray_id_raw))
  2688. else:
  2689. spoolman_held.add(hold_key)
  2690. logger.info(
  2691. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2692. "unlinking if it is still empty in %ds",
  2693. ams_id,
  2694. tray_id_raw,
  2695. linked_spool,
  2696. int(slot_unlink_grace.GRACE_SECONDS),
  2697. )
  2698. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2699. continue
  2700. spool_tag = (
  2701. tray.tray_uuid
  2702. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2703. else tray.tag_uid
  2704. )
  2705. # Provide the hint only when no RFID is available
  2706. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2707. try:
  2708. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2709. result = await client.sync_ams_tray(
  2710. tray,
  2711. printer_name,
  2712. db,
  2713. # Per-print tracking is the only weight writer (#1119).
  2714. # AMS auto-sync still maintains spool metadata / slot
  2715. # assignments but no longer touches remaining_weight.
  2716. disable_weight_sync=True,
  2717. cached_spools=cached_spools,
  2718. inventory_remaining=inv_remaining,
  2719. spoolman_spool_id_hint=hint,
  2720. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2721. )
  2722. if result is None and spool_tag and not auto_add_unknown_rfid:
  2723. # Spoolman skipped auto-create per user setting — surface
  2724. # the slot so the UI can offer "+ Add to inventory".
  2725. await _broadcast_unknown_tag(
  2726. printer_id=printer_id,
  2727. ams_id=ams_id,
  2728. tray_id=tray.tray_id,
  2729. tag_uid=tray.tag_uid or "",
  2730. tray_uuid=tray.tray_uuid or "",
  2731. tray_type=tray.tray_type,
  2732. tray_color=tray.tray_color,
  2733. tray_sub_brands=tray.tray_sub_brands,
  2734. tray_count=len(trays),
  2735. )
  2736. elif result:
  2737. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2738. if result:
  2739. synced += 1
  2740. if result.get("id"):
  2741. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2742. # If a new spool was created, add it to the cache
  2743. # so subsequent trays can find it if they reference the same tag
  2744. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2745. if not spool_exists:
  2746. cached_spools.append(result)
  2747. logger.debug(
  2748. "[Printer %s] Added newly created spool %s to cache",
  2749. printer_id,
  2750. result["id"],
  2751. )
  2752. # Reconcile slot_preset_mappings (the same row internal
  2753. # mode keeps in sync via inventory + spool_tag_matcher).
  2754. # Without this the slot card surfaces the previous spool's
  2755. # preset name — same bug shape, different inventory mode.
  2756. from backend.app.services.slot_preset_writer import (
  2757. upsert_slot_preset_for_spoolman_spool,
  2758. )
  2759. await upsert_slot_preset_for_spoolman_spool(
  2760. db=db,
  2761. spoolman_spool=result,
  2762. tray_info_idx=tray.tray_info_idx or "",
  2763. tray_sub_brands=tray.tray_sub_brands or "",
  2764. tray_type=tray.tray_type or "",
  2765. printer_id=printer_id,
  2766. ams_id=ams_id,
  2767. tray_id=tray.tray_id,
  2768. )
  2769. except Exception as e:
  2770. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2771. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2772. if synced > 0:
  2773. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2774. # Persist slot assignment changes to the local table
  2775. if slot_changes or empty_slots:
  2776. try:
  2777. for ams_id, tray_id, spool_id in slot_changes:
  2778. await db.execute(
  2779. text(
  2780. "INSERT INTO spoolman_slot_assignments"
  2781. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2782. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2783. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2784. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2785. ),
  2786. {
  2787. "printer_id": printer_id,
  2788. "ams_id": ams_id,
  2789. "tray_id": tray_id,
  2790. "spool_id": spool_id,
  2791. },
  2792. )
  2793. for ams_id, tray_id in empty_slots:
  2794. await db.execute(
  2795. delete(SpoolmanSlotAssignment).where(
  2796. SpoolmanSlotAssignment.printer_id == printer_id,
  2797. SpoolmanSlotAssignment.ams_id == ams_id,
  2798. SpoolmanSlotAssignment.tray_id == tray_id,
  2799. )
  2800. )
  2801. await db.commit()
  2802. except Exception as e:
  2803. await db.rollback()
  2804. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2805. else:
  2806. # Tell open browsers the slot changed. This loop rewrites
  2807. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2808. # above, and the AMS slot card reads that row ahead of the
  2809. # live tray_info_idx -- so with no event the card keeps
  2810. # showing the previous spool's preset name. Internal mode
  2811. # raises spool_auto_assigned for the same reason; this loop
  2812. # broadcast nothing at all, which made Spoolman mode the
  2813. # worse half of the same bug. On the else branch so a
  2814. # failed commit stays silent and a broadcast failure cannot
  2815. # roll back rows that are already committed.
  2816. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2817. await ws_manager.broadcast(
  2818. {
  2819. "type": "spool_assignment_changed",
  2820. "printer_id": printer_id,
  2821. "ams_id": ams_id,
  2822. "tray_id": tray_id,
  2823. }
  2824. )
  2825. except Exception as e:
  2826. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2827. # Largest finish photo attached to a notification; a bigger one is still linked.
  2828. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  2829. async def _finish_photo_for_notification(
  2830. db, archive, archive_id: int, filename: str
  2831. ) -> tuple[str | None, bytes | None]:
  2832. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  2833. With authentication off the link is the archive's own photo route, as it
  2834. always was: it opens without a login and doesn't expire. With
  2835. authentication on that route needs a media token, which nothing tapping a
  2836. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  2837. link only ever answered 401. The photo is then saved as a notification
  2838. photo as well (utils/notification_photos.py) and the link points there: an
  2839. unguessable name that opens this one photo and nothing else, for 3 days.
  2840. The link is relative when no External URL is set. Bytes over
  2841. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  2842. ``(None, None)`` when the photo can't be found.
  2843. """
  2844. from backend.app.api.routes.settings import get_setting
  2845. from backend.app.core.auth import is_auth_enabled
  2846. from backend.app.utils.archive_paths import find_archive_photo
  2847. from backend.app.utils.notification_photos import save_notification_photo
  2848. log = logging.getLogger(__name__)
  2849. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  2850. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  2851. photo_bytes: bytes | None = None
  2852. try:
  2853. photo_path = find_archive_photo(archive, filename)
  2854. if photo_path is not None:
  2855. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2856. except Exception as e:
  2857. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2858. try:
  2859. auth_on = await is_auth_enabled(db)
  2860. except Exception:
  2861. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  2862. if auth_on:
  2863. url = None
  2864. if photo_bytes:
  2865. try:
  2866. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  2867. url = f"{base}/api/v1/notifications/photos/{name}"
  2868. except Exception as e:
  2869. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  2870. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  2871. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  2872. return url, None
  2873. if photo_bytes:
  2874. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2875. return url, photo_bytes
  2876. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2877. """Capture a camera snapshot for notification image attachment.
  2878. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2879. Uses: external camera > buffered frame > fresh capture.
  2880. """
  2881. if not printer:
  2882. return None
  2883. try:
  2884. from backend.app.api.routes.settings import get_setting
  2885. async with async_session() as db:
  2886. capture_enabled = await get_setting(db, "capture_finish_photo")
  2887. if capture_enabled is not None and capture_enabled.lower() != "true":
  2888. return None
  2889. # Try external camera first
  2890. if printer.external_camera_enabled and printer.external_camera_url:
  2891. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2892. from backend.app.api.routes.camera import live_frame_for_capture
  2893. from backend.app.services.external_camera import capture_frame
  2894. # An external camera allows one reader, so capturing while a viewer
  2895. # is attached fails (#2707). A None here falls through to the paths
  2896. # below exactly as a failed capture did.
  2897. defer, buffered = live_frame_for_capture(printer_id)
  2898. if defer:
  2899. frame_data = buffered
  2900. else:
  2901. frame_data = await capture_frame(
  2902. printer.external_camera_url,
  2903. printer.external_camera_type or "mjpeg",
  2904. snapshot_url=printer.external_camera_snapshot_url,
  2905. )
  2906. if frame_data and len(frame_data) <= 2_500_000:
  2907. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2908. return _apply_camera_rotation(frame_data, printer, logger)
  2909. # Try buffered frame from active stream
  2910. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2911. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2912. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2913. buffered_frame = get_buffered_frame(printer_id)
  2914. if (active_for_printer or active_chamber) and buffered_frame:
  2915. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2916. if len(buffered_frame) <= 2_500_000:
  2917. return _apply_camera_rotation(buffered_frame, printer, logger)
  2918. # Fresh capture from printer camera
  2919. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2920. from backend.app.services.camera import capture_camera_frame_bytes
  2921. frame_data = await capture_camera_frame_bytes(
  2922. printer.ip_address, printer.access_code, printer.model, timeout=15
  2923. )
  2924. if frame_data and len(frame_data) <= 2_500_000:
  2925. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2926. return _apply_camera_rotation(frame_data, printer, logger)
  2927. except Exception as e:
  2928. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2929. return None
  2930. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2931. """#1867: bank a recent in-print camera frame for the finish photo.
  2932. Called on every layer change and (#2547) on every print-progress advance.
  2933. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2934. path has a pre-End-G-code image for prints that end with a plate swap.
  2935. Both drivers are print telemetry that stops the instant printing ends: no
  2936. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2937. plate swap) executes. So the last banked frame is always the finished print,
  2938. never the swapped plate — that property is what the #1867 path relies on and
  2939. it must survive any change to the throttle below.
  2940. Layer changes alone were not enough: they stop when the *final* layer
  2941. begins, which on a three-minute last layer left the bank stale by the whole
  2942. length of that layer (#2547). Progress keeps ticking through it.
  2943. Best-effort: any failure just leaves the previous banked frame.
  2944. """
  2945. logger = logging.getLogger(__name__)
  2946. client = printer_manager.get_client(printer_id)
  2947. state = client.state if client else None
  2948. if not state or state.state != "RUNNING":
  2949. return
  2950. # Only during actual extrusion — firmware ticks layer_num during the
  2951. # pre-print calibration sequence, whose sub-stages are non-zero.
  2952. if state.mc_print_sub_stage not in (None, 0):
  2953. return
  2954. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2955. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2956. # now that progress advances also drive banking, that exemption would fire a
  2957. # camera grab on every percent tick of the last layer. Bambu printers accept
  2958. # one RTSP client at a time, so each grab contends with the live view.
  2959. now = time.monotonic()
  2960. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2961. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2962. return
  2963. total = state.total_layers or 0
  2964. try:
  2965. async with async_session() as db:
  2966. from backend.app.models.printer import Printer
  2967. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2968. printer = result.scalar_one_or_none()
  2969. if not printer:
  2970. return
  2971. # Reuses the notification snapshot path, which honours the
  2972. # `capture_finish_photo` setting (returns None when disabled) so we
  2973. # don't bank frames the user never asked for.
  2974. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2975. if frame:
  2976. _inprint_frame_bank[printer_id] = frame
  2977. _inprint_frame_bank_ts[printer_id] = now
  2978. logger.debug(
  2979. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2980. printer_id,
  2981. layer_num,
  2982. total,
  2983. len(frame),
  2984. )
  2985. except Exception as e:
  2986. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2987. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2988. """Apply camera rotation to snapshot image if configured."""
  2989. from backend.app.services.camera import apply_camera_rotation
  2990. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2991. async def _send_print_start_notification(
  2992. printer_id: int,
  2993. data: dict,
  2994. archive_data: dict | None = None,
  2995. logger=None,
  2996. ):
  2997. """Helper to send print start notification with optional archive data."""
  2998. if logger is None:
  2999. logger = logging.getLogger(__name__)
  3000. try:
  3001. async with async_session() as db:
  3002. from backend.app.models.printer import Printer
  3003. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3004. printer = result.scalar_one_or_none()
  3005. printer_name = printer.name if printer else f"Printer {printer_id}"
  3006. # Capture camera snapshot for notification image attachment
  3007. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3008. if image_data:
  3009. if archive_data is None:
  3010. archive_data = {}
  3011. archive_data["image_data"] = image_data
  3012. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3013. # Send user-specific email notification for print start
  3014. if archive_data and archive_data.get("created_by_id"):
  3015. await notification_service.send_user_print_email(
  3016. event_type="user_print_start",
  3017. created_by_id=archive_data["created_by_id"],
  3018. printer_name=printer_name,
  3019. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3020. db=db,
  3021. )
  3022. except Exception as e:
  3023. logger.warning("Notification on_print_start failed: %s", e)
  3024. async def _dispatch_user_print_email(
  3025. status: str,
  3026. created_by_id: int | None,
  3027. printer_name: str,
  3028. filename: str,
  3029. db,
  3030. image_data: bytes | None = None,
  3031. finish_photo_url: str | None = None,
  3032. ) -> None:
  3033. """Send a user-specific print-completion email based on print status.
  3034. Maps the normalised print status to the correct event type and delegates
  3035. to :meth:`NotificationService.send_user_print_email`. A single helper
  3036. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3037. "stopped"`` dispatch block at every call site.
  3038. Does nothing if *created_by_id* is ``None``.
  3039. """
  3040. if created_by_id is None:
  3041. return
  3042. if status == "completed":
  3043. event_type = "user_print_complete"
  3044. elif status == "failed":
  3045. event_type = "user_print_failed"
  3046. elif status in ("stopped", "aborted", "cancelled"):
  3047. event_type = "user_print_stopped"
  3048. else:
  3049. return
  3050. await notification_service.send_user_print_email(
  3051. event_type=event_type,
  3052. created_by_id=created_by_id,
  3053. printer_name=printer_name,
  3054. filename=filename,
  3055. db=db,
  3056. image_data=image_data,
  3057. finish_photo_url=finish_photo_url,
  3058. )
  3059. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3060. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3061. try:
  3062. from backend.app.services.archive import extract_printable_objects_from_archive
  3063. client = printer_manager.get_client(printer_id)
  3064. if not client:
  3065. return
  3066. # Extract with positions for UI overlay, scoped to the plate that
  3067. # is printing — resolve_plate_id is the same resolver /cover uses,
  3068. # so the object list can't disagree with the thumbnail it is drawn
  3069. # over (#2522).
  3070. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3071. app_settings.base_dir / archive.file_path,
  3072. plate_number=resolve_plate_id(client.state),
  3073. )
  3074. if printable_objects:
  3075. client.state.printable_objects = printable_objects
  3076. client.state.printable_objects_bbox_all = bbox_all
  3077. client.state.skipped_objects = []
  3078. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3079. except Exception as e:
  3080. logger.debug("Failed to extract printable objects from archive: %s", e)
  3081. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3082. """Put the skip-objects list back after a restart mid-print.
  3083. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3084. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3085. which the #1304 guard suppresses on the first RUNNING push after startup.
  3086. Everything else this hook restores (the archive, the usage-tracking session,
  3087. the timelapse baseline) was already handled; the object list was not, so a
  3088. restart mid-print took skip-objects away for the rest of that print.
  3089. Nothing recovered it either: the printer card gates its Skip button on the
  3090. object count, and the one endpoint that can rebuild the list is reachable
  3091. only from the modal that button opens.
  3092. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3093. leftover ``status="printing"`` row from a completion we never saw cannot
  3094. hand this print someone else's objects. Without one, nothing is loaded
  3095. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3096. case on demand.
  3097. """
  3098. client = printer_manager.get_client(printer_id)
  3099. if client is None or client.state.printable_objects:
  3100. return
  3101. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3102. if subtask_id in ("", "0"):
  3103. return
  3104. from backend.app.models.archive import PrintArchive
  3105. archive = await db.scalar(
  3106. select(PrintArchive)
  3107. .where(
  3108. PrintArchive.printer_id == printer_id,
  3109. PrintArchive.status == "printing",
  3110. PrintArchive.subtask_id == subtask_id,
  3111. )
  3112. .order_by(PrintArchive.created_at.desc())
  3113. .limit(1)
  3114. )
  3115. if archive is not None:
  3116. _load_objects_from_archive(archive, printer_id, logger)
  3117. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3118. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3119. # past it; the second covers a handshake that failed again on the way back and
  3120. # armed a fresh one. Module-level so tests can shrink them.
  3121. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3122. # Retry ladder for the other temporary give-up: the file service answered and
  3123. # the transfer still did not finish, which at print start is usually the printer
  3124. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3125. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3126. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3127. # two cover a printer that stays busy well into the print.
  3128. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3129. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3130. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3131. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3132. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3133. # by view, so two views race), the cool-off retry task, and print completion.
  3134. # Without this they each read file_path == "" and each run a full copy, so the row
  3135. # ends up pointing at one timestamped directory while the others sit orphaned.
  3136. #
  3137. # Keyed by printer rather than archive because a printer runs one print at a time,
  3138. # which makes the two equally strong here — and it bounds the dict by printer
  3139. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3140. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3141. # resuming, so "no waiters" is not a question this API can answer.
  3142. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3143. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3144. """Fill in a no-3MF archive from a 3MF that turned up later.
  3145. Returns True when the row was upgraded. Safe to call speculatively: it
  3146. verifies the archive still exists, is still a fallback, and that the file
  3147. is a readable 3MF before touching anything.
  3148. Serialised per printer — see ``_fallback_recovery_locks``.
  3149. """
  3150. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3151. async with lock:
  3152. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3153. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3154. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3155. import zipfile
  3156. from backend.app.models.archive import PrintArchive
  3157. from backend.app.services.archive import ArchiveService
  3158. logger = logging.getLogger(__name__)
  3159. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3160. return False
  3161. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3162. # A truncated or half-written download is worse than no download: it
  3163. # would replace an honest empty archive with wrong metadata.
  3164. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3165. return False
  3166. async with async_session() as db:
  3167. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3168. if archive is None or archive.deleted_at is not None:
  3169. return False
  3170. if archive.file_path:
  3171. # Already recovered, or never was a fallback. Either way there is a
  3172. # real 3MF attached and overwriting it is not this function's job.
  3173. return False
  3174. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3175. service = ArchiveService(db)
  3176. recovered = await service.archive_print(
  3177. printer_id=printer_id,
  3178. source_file=source_3mf,
  3179. print_data={**print_data, "status": archive.status or "printing"},
  3180. subtask_id=archive.subtask_id,
  3181. update_archive_id=archive.id,
  3182. )
  3183. if recovered is None:
  3184. return False
  3185. logger.info(
  3186. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3187. archive_id,
  3188. source_3mf,
  3189. recovered.file_size,
  3190. )
  3191. # `archive_updated`, not `archive_created` — the row was already on the
  3192. # Archives page as an empty card and is now filled in, not new.
  3193. await ws_manager.send_archive_updated(
  3194. {
  3195. "id": recovered.id,
  3196. "printer_id": recovered.printer_id,
  3197. "filename": recovered.filename,
  3198. "print_name": recovered.print_name,
  3199. "status": recovered.status,
  3200. }
  3201. )
  3202. return True
  3203. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3204. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3205. Called from the paths that pull a 3MF for a print that is already under way
  3206. — chiefly the cover endpoint, which downloads the very file the archive flow
  3207. could not get and, before #2957, used it for a thumbnail and nothing else.
  3208. The bytes are already local, so this costs a parse and a row update.
  3209. No-op when the running print has a real archive, which is the common case.
  3210. """
  3211. from backend.app.models.archive import PrintArchive
  3212. logger = logging.getLogger(__name__)
  3213. # `_active_prints` is keyed on the raw names seen at print start — the
  3214. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3215. # Callers here arrive with whichever variant their own path produced, so
  3216. # match on the same normalization the download cache uses rather than on an
  3217. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3218. # endpoint find an archive registered under "Desktop_Goose".
  3219. wanted = normalize_3mf_name(name)
  3220. archive_id = None
  3221. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3222. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3223. archive_id = value
  3224. break
  3225. if archive_id is None:
  3226. return False
  3227. async with async_session() as db:
  3228. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3229. # Cheap pre-check so the common case (a normal archive) does no work.
  3230. if archive is None or archive.file_path or archive.deleted_at is not None:
  3231. return False
  3232. try:
  3233. return await _recover_fallback_archive(archive_id, path, printer_id)
  3234. except Exception as e:
  3235. # Recovery is opportunistic. A failure here must never take down the
  3236. # caller, which is usually just trying to render a thumbnail.
  3237. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3238. return False
  3239. def _schedule_fallback_3mf_retry(
  3240. printer_id: int,
  3241. archive_id: int,
  3242. filenames: list[str],
  3243. delays: tuple[float, ...] | None = None,
  3244. reason: str = REASON_FTPS_COOLOFF,
  3245. ) -> None:
  3246. """Re-attempt the 3MF download after a temporary give-up.
  3247. ``reason`` says which give-up this is, and picks the default ladder: an
  3248. FTPS cool-off has to be waited out, while a transfer that timed out under
  3249. contention is worth asking about again straight away (#3063). It is only
  3250. read for the ladder and the log line -- the retry itself is identical, since
  3251. in both cases the file is on the printer and the last attempt at it failed
  3252. for a reason that does not last.
  3253. """
  3254. logger = logging.getLogger(__name__)
  3255. if delays is None:
  3256. delays = (
  3257. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3258. if reason == REASON_FTP_TRANSFER_FAILED
  3259. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3260. )
  3261. async def _retry() -> None:
  3262. from backend.app.models.archive import PrintArchive
  3263. from backend.app.models.printer import Printer
  3264. for delay in delays:
  3265. await asyncio.sleep(delay)
  3266. async with async_session() as db:
  3267. archive = (
  3268. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3269. ).scalar_one_or_none()
  3270. if archive is None or archive.deleted_at is not None or archive.file_path:
  3271. return
  3272. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3273. if printer is None:
  3274. return
  3275. # Read the fields while the session is open rather than touching
  3276. # a detached instance minutes later, mid-download.
  3277. printer_ip = printer.ip_address
  3278. printer_code = printer.access_code
  3279. printer_model = printer.model
  3280. # Someone else may have fetched it in the meantime — the cover
  3281. # endpoint routinely does, and its copy is the same bytes.
  3282. for name in filenames:
  3283. cached = get_cached_3mf(printer_id, name)
  3284. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3285. return
  3286. if ftps_handshake_blocked(printer_ip):
  3287. logger.info(
  3288. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3289. printer_id,
  3290. archive_id,
  3291. )
  3292. continue
  3293. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3294. for candidate in filenames:
  3295. # Bare name only. These come from the print-start flow, which
  3296. # already strips the path, but the local temp write must not
  3297. # depend on that holding for every future caller — a name that
  3298. # is absolute or contains ".." would otherwise escape the data
  3299. # volume via the `/` operator.
  3300. name = Path(candidate).name
  3301. if not name or name in (".", ".."):
  3302. continue
  3303. if not name.endswith(".3mf"):
  3304. name = f"{name}.3mf"
  3305. temp_path = app_settings.archive_dir / "temp" / name
  3306. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3307. try:
  3308. hit = await download_file_try_paths_async(
  3309. printer_ip,
  3310. printer_code,
  3311. ftp_probe_paths(name),
  3312. temp_path,
  3313. socket_timeout=ftp_timeout,
  3314. printer_model=printer_model,
  3315. )
  3316. except Exception as e:
  3317. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3318. continue
  3319. if not hit:
  3320. continue
  3321. cache_3mf_download(printer_id, name, temp_path)
  3322. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3323. return
  3324. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3325. async def _guarded() -> None:
  3326. try:
  3327. await _retry()
  3328. except asyncio.CancelledError:
  3329. raise
  3330. except Exception as e:
  3331. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3332. finally:
  3333. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3334. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3335. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3336. if existing and not existing.done():
  3337. existing.cancel()
  3338. task = asyncio.create_task(_guarded())
  3339. _fallback_3mf_retry_tasks[printer_id] = task
  3340. logger.info(
  3341. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3342. archive_id,
  3343. reason,
  3344. printer_id,
  3345. ", ".join(f"{d:g}s" for d in delays),
  3346. )
  3347. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3348. """Whether an archive created here should ask for the print's outcome (#1898).
  3349. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3350. branches below: a queued job already has its archive and takes the
  3351. expected-print branch, where the queue item's own ``confirm_outcome``
  3352. decides. The queue is still consulted, because a restart mid-print empties
  3353. ``_expected_prints`` — without the check the setting could override a queue
  3354. item that deliberately has the flag off. Any failure answers "don't ask":
  3355. an unwanted prompt is worse than a missing one, and this must never be the
  3356. reason a print goes unarchived.
  3357. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3358. leaves one behind when a completion cannot be matched to it
  3359. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3360. only takes it back once the printer has sat connected and terminal for
  3361. minutes. Until then every screen-started print on that printer would
  3362. silently lose its prompt, so the row is held against ``observed_name`` by
  3363. the same comparison a completion uses: a positive disagreement means the row
  3364. is about some other run and this print is external after all.
  3365. """
  3366. logger = logging.getLogger(__name__)
  3367. try:
  3368. # A savepoint rather than a rollback of the caller's transaction on
  3369. # failure: a failed statement leaves the transaction unusable, but a
  3370. # full rollback also expires every object the caller has loaded (the
  3371. # printer, the archive it just created), and on an async session the
  3372. # next attribute read then raises instead of reloading. Everything here
  3373. # is a read, so undoing the savepoint loses nothing.
  3374. async with db.begin_nested():
  3375. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3376. except Exception as e:
  3377. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3378. return False
  3379. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3380. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3381. from backend.app.api.routes.settings import get_setting, setting_is_true
  3382. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3383. return False
  3384. from backend.app.models.print_queue import PrintQueueItem
  3385. dispatched_here = await db.scalar(
  3386. select(PrintQueueItem)
  3387. .where(
  3388. PrintQueueItem.printer_id == printer_id,
  3389. PrintQueueItem.status == "printing",
  3390. )
  3391. .limit(1)
  3392. )
  3393. if dispatched_here is None:
  3394. return True
  3395. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3396. observed = (observed_name or "").strip()
  3397. if not expected or not observed or _subtask_names_match(expected, observed):
  3398. logger.info(
  3399. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3400. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3401. printer_id,
  3402. dispatched_here.id,
  3403. )
  3404. return False
  3405. logger.info(
  3406. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3407. "%r; treating this as an externally started print.",
  3408. dispatched_here.id,
  3409. printer_id,
  3410. expected,
  3411. observed,
  3412. )
  3413. return True
  3414. async def _dispatch_outcome_confirmation_safely(
  3415. db,
  3416. printer_id: int,
  3417. printer_name: str,
  3418. data: dict,
  3419. archive_id: int,
  3420. archive_data: dict | None = None,
  3421. ) -> None:
  3422. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3423. The completion task sends the per-user print email on the same session
  3424. right after the prompt. A failed statement in the prompt leaves that
  3425. session needing a rollback, and without one the email step fails with
  3426. PendingRollbackError; the prompt is the optional part, so it must not be
  3427. the reason the email never goes out.
  3428. """
  3429. try:
  3430. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3431. except Exception as e:
  3432. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3433. try:
  3434. await db.rollback()
  3435. except Exception:
  3436. pass
  3437. async def dispatch_outcome_confirmation(
  3438. db,
  3439. printer_id: int,
  3440. printer_name: str,
  3441. data: dict,
  3442. archive_id: int,
  3443. archive_data: dict | None = None,
  3444. ) -> bool:
  3445. """Emit the post-print outcome prompt for a completed archive (#1898).
  3446. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3447. queue item, or from ``confirm_outcome_external_prints`` for a print
  3448. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3449. question still open. Mints the per-archive capability token the one-tap
  3450. verdict links carry.
  3451. Lives here rather than inline in ``on_print_complete``'s notification task
  3452. because that task swallows every exception: extracted, the gate and the two
  3453. emissions can be driven by a test, which is the only thing standing between
  3454. a regression here and a farm that quietly stops asking.
  3455. Returns whether a prompt was sent.
  3456. """
  3457. logger = logging.getLogger(__name__)
  3458. from backend.app.models.archive import PrintArchive
  3459. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3460. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3461. return False
  3462. import secrets as _secrets
  3463. # A spent token stays on the row so the one-tap route can recognise it, so
  3464. # "has a token" no longer means "answerable". A prompt going out now needs a
  3465. # live one: mint a new token whenever the stored one is already spent, or
  3466. # every button in the new message would land on the already-answered page.
  3467. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3468. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3469. confirm_archive.confirm_token_used_at = None
  3470. await db.commit()
  3471. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3472. base = await get_external_base_url(db)
  3473. if not await get_setting(db, "external_url"):
  3474. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3475. # absolute URL, so an unconfigured install used to get a message body
  3476. # with two unusable relative paths and no buttons at all. The shared
  3477. # fallback at least produces tappable links; say which setting makes
  3478. # them resolve from a phone.
  3479. logger.warning(
  3480. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3481. "Set Settings → External URL so they resolve away from this host.",
  3482. base,
  3483. )
  3484. token = confirm_archive.confirm_token
  3485. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3486. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3487. confirm_url = f"{base}/archives?confirm={archive_id}"
  3488. await ws_manager.send_print_confirm_request(
  3489. printer_id,
  3490. {
  3491. "archive_id": archive_id,
  3492. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3493. },
  3494. )
  3495. await notification_service.on_print_confirm_request(
  3496. printer_id,
  3497. printer_name,
  3498. data,
  3499. db,
  3500. archive_data=archive_data,
  3501. good_url=good_url,
  3502. reject_url=reject_url,
  3503. confirm_url=confirm_url,
  3504. archive_id=archive_id,
  3505. )
  3506. return True
  3507. async def on_print_start(printer_id: int, data: dict):
  3508. """Handle print start - archive the 3MF file immediately."""
  3509. logger = logging.getLogger(__name__)
  3510. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3511. # Clear any stale user-stopped flag from previous print cycles
  3512. _user_stopped_printers.discard(printer_id)
  3513. _kill_switch_notification_tasks.pop(printer_id, None)
  3514. # #1721: drop any leftover pre-captured finish frame from a prior print
  3515. # so a never-consumed cache entry can't bleed into the new print's photo.
  3516. _stage22_finish_frames.pop(printer_id, None)
  3517. # #1867: same for the in-print frame bank — a queued print must not reuse
  3518. # the previous job's banked frame.
  3519. _inprint_frame_bank.pop(printer_id, None)
  3520. _inprint_frame_bank_ts.pop(printer_id, None)
  3521. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3522. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3523. # print's flag instead of inheriting it.
  3524. print_dispatch_context.adopt(printer_id)
  3525. # Cancel any active bed cooldown waiter for this printer
  3526. if _bed_cool_waiters.pop(printer_id, None):
  3527. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3528. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3529. from backend.app.api.routes.printers import clear_cover_cache
  3530. clear_cover_cache(printer_id)
  3531. await ws_manager.send_print_start(printer_id, data)
  3532. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3533. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3534. # MQTT relay - publish print start
  3535. try:
  3536. printer_info = printer_manager.get_printer(printer_id)
  3537. if printer_info:
  3538. await mqtt_relay.on_print_start(
  3539. printer_id,
  3540. printer_info.name,
  3541. printer_info.serial_number,
  3542. data.get("filename", ""),
  3543. data.get("subtask_name", ""),
  3544. )
  3545. except Exception:
  3546. pass # Don't fail print start callback if MQTT fails
  3547. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3548. # and mapping, and the seeded tray-change log.
  3549. #
  3550. # Unconditional, for both inventory backends. This only *captures* — the
  3551. # writing is still split, with the internal tracker skipped at completion
  3552. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3553. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3554. # tray-change log, and that log is the only record of which spool fed
  3555. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3556. # it on one side only would leave Spoolman users with the mid-print
  3557. # restart bug this fixes for everyone else.
  3558. try:
  3559. async with async_session() as db:
  3560. from backend.app.api.routes.settings import get_setting
  3561. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3562. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3563. await usage_on_print_start(
  3564. printer_id,
  3565. data,
  3566. printer_manager,
  3567. db=db,
  3568. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3569. )
  3570. except Exception as e:
  3571. logger.warning("Usage tracker on_print_start failed: %s", e)
  3572. # Track if notification was sent (to avoid sending twice)
  3573. notification_sent = False
  3574. # Smart plug automation: turn on plug when print starts
  3575. try:
  3576. async with async_session() as db:
  3577. await smart_plug_manager.on_print_start(printer_id, db)
  3578. except Exception as e:
  3579. logger.warning("Smart plug on_print_start failed: %s", e)
  3580. async with async_session() as db:
  3581. from backend.app.models.printer import Printer
  3582. from backend.app.services.bambu_ftp import list_files_async
  3583. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3584. printer = result.scalar_one_or_none()
  3585. # Plate detection check - pause if objects detected on build plate
  3586. logger.info(
  3587. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3588. )
  3589. if printer and printer.plate_detection_enabled:
  3590. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3591. # Release the pooled DB connection before the plate-detection camera
  3592. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3593. # printer SELECT has run so far — nothing to persist — so this commit
  3594. # is a data-noop that ends the read transaction and returns the
  3595. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3596. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3597. # archive lookups below re-acquire a fresh connection on next execute.
  3598. await db.commit()
  3599. try:
  3600. from backend.app.services.plate_detection import check_plate_empty
  3601. # Build ROI tuple from printer settings if available
  3602. roi = None
  3603. if all(
  3604. [
  3605. printer.plate_detection_roi_x is not None,
  3606. printer.plate_detection_roi_y is not None,
  3607. printer.plate_detection_roi_w is not None,
  3608. printer.plate_detection_roi_h is not None,
  3609. ]
  3610. ):
  3611. roi = (
  3612. printer.plate_detection_roi_x,
  3613. printer.plate_detection_roi_y,
  3614. printer.plate_detection_roi_w,
  3615. printer.plate_detection_roi_h,
  3616. )
  3617. # Auto-turn on chamber light if it's off for better detection
  3618. light_was_off = False
  3619. client = printer_manager.get_client(printer_id)
  3620. if client and client.state:
  3621. light_was_off = not client.state.chamber_light
  3622. if light_was_off:
  3623. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3624. client.set_chamber_light(True)
  3625. # Wait for light to physically turn on and camera to adjust exposure
  3626. await asyncio.sleep(2.5)
  3627. plate_photo_data = None
  3628. objects_detected = False
  3629. try:
  3630. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3631. plate_result = await check_plate_empty(
  3632. printer_id=printer_id,
  3633. ip_address=printer.ip_address,
  3634. access_code=printer.access_code,
  3635. model=printer.model,
  3636. include_debug_image=False,
  3637. external_camera_url=printer.external_camera_url,
  3638. external_camera_type=printer.external_camera_type,
  3639. use_external=printer.external_camera_enabled,
  3640. roi=roi,
  3641. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3642. )
  3643. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3644. if objects_detected:
  3645. # Objects detected - pause the print!
  3646. logger.warning(
  3647. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3648. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3649. )
  3650. pause_client = printer_manager.get_client(printer_id)
  3651. if pause_client:
  3652. pause_client.pause_print()
  3653. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3654. # Snapshot while the light's still on — restoring it first
  3655. # would leave the notification with a dark photo.
  3656. try:
  3657. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3658. except Exception as snap_err:
  3659. logger.warning(
  3660. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3661. )
  3662. finally:
  3663. # Restore chamber light to original state as soon as the
  3664. # camera is done with it, whatever happened above.
  3665. if light_was_off and client:
  3666. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3667. try:
  3668. client.set_chamber_light(False)
  3669. except Exception as light_err:
  3670. logger.warning(
  3671. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3672. printer_id,
  3673. light_err,
  3674. )
  3675. if objects_detected:
  3676. # Send notification about plate not empty
  3677. await ws_manager.broadcast(
  3678. {
  3679. "type": "plate_not_empty",
  3680. "printer_id": printer_id,
  3681. "printer_name": printer.name,
  3682. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3683. }
  3684. )
  3685. # Also send push notification
  3686. try:
  3687. await notification_service.on_plate_not_empty(
  3688. printer_id=printer_id,
  3689. printer_name=printer.name,
  3690. db=db,
  3691. difference_percent=plate_result.difference_percent,
  3692. image_data=plate_photo_data,
  3693. )
  3694. except Exception as notif_err:
  3695. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3696. else:
  3697. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3698. except Exception as plate_err:
  3699. # Don't block print on plate detection errors
  3700. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3701. if not printer:
  3702. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3703. if not notification_sent:
  3704. await _send_print_start_notification(printer_id, data, logger=logger)
  3705. return
  3706. if not printer.auto_archive:
  3707. # auto-archive disabled — check if there's an expected print (dispatched
  3708. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3709. # If so, fall through to the expected-print handling below so the archive
  3710. # is tracked in _active_prints and usage tracking works at completion.
  3711. _fn = data.get("filename", "")
  3712. _sn = data.get("subtask_name", "")
  3713. _check_keys: list[tuple[int, str]] = []
  3714. if _sn:
  3715. _check_keys += [
  3716. (printer_id, _sn),
  3717. (printer_id, f"{_sn}.3mf"),
  3718. (printer_id, f"{_sn}.gcode.3mf"),
  3719. ]
  3720. if _fn:
  3721. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3722. _check_keys.append((printer_id, _base_fn))
  3723. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3724. _check_keys += [
  3725. (printer_id, _no_archive_base),
  3726. (printer_id, f"{_no_archive_base}.3mf"),
  3727. ]
  3728. _has_expected = any(k in _expected_prints for k in _check_keys)
  3729. if not _has_expected:
  3730. # No expected print — truly external print (started from slicer/touchscreen)
  3731. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3732. if not notification_sent:
  3733. _no_archive_creator: int | None = None
  3734. for _key in _check_keys:
  3735. _expected_prints.pop(_key, None)
  3736. _expected_print_registered_at.pop(_key, None)
  3737. popped_creator = _expected_print_creators.pop(_key, None)
  3738. if _no_archive_creator is None:
  3739. _no_archive_creator = popped_creator
  3740. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3741. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3742. return
  3743. else:
  3744. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3745. # Get the filename and subtask_name
  3746. filename = data.get("filename", "")
  3747. subtask_name = data.get("subtask_name", "")
  3748. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3749. # present, it lets us match an archive across a backend restart (#972):
  3750. # same id → same print → resume the existing row instead of cancelling
  3751. # it and recreating from scratch (which loses started_at). Treat "0"
  3752. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3753. raw_mqtt = data.get("raw_data") or {}
  3754. subtask_id = raw_mqtt.get("subtask_id")
  3755. if subtask_id is not None:
  3756. subtask_id = str(subtask_id).strip()
  3757. if subtask_id in ("", "0"):
  3758. subtask_id = None
  3759. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3760. # Skip the printer's own jobs — a calibration run is not a user's print.
  3761. # See is_internal_printer_job for what counts and why both fields are
  3762. # tested; the pressure-advance line reports as a subtask name with no
  3763. # /usr/ path, which the old prefix-only test here missed entirely.
  3764. #
  3765. # No notification either. The event describes the printer calibrating
  3766. # itself, so "Print started" is as wrong as the archive was, and the
  3767. # matching completion is suppressed in on_print_complete for the same
  3768. # reason.
  3769. if is_internal_printer_job(filename, subtask_name):
  3770. logger.info(
  3771. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3772. filename,
  3773. subtask_name,
  3774. )
  3775. return
  3776. if not filename and not subtask_name:
  3777. # Send notification without archive data (no filename)
  3778. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3779. if not notification_sent:
  3780. await _send_print_start_notification(printer_id, data, logger=logger)
  3781. return
  3782. # Check if this is an expected print from reprint/scheduled
  3783. # Build list of possible keys to check
  3784. expected_keys = []
  3785. if subtask_name:
  3786. expected_keys.append((printer_id, subtask_name))
  3787. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3788. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3789. if filename:
  3790. fname = filename.split("/")[-1] if "/" in filename else filename
  3791. expected_keys.append((printer_id, fname))
  3792. # Strip extensions to match
  3793. base = fname.replace(".gcode", "").replace(".3mf", "")
  3794. expected_keys.append((printer_id, base))
  3795. expected_keys.append((printer_id, f"{base}.3mf"))
  3796. expected_archive_id = None
  3797. for key in expected_keys:
  3798. expected_archive_id = _expected_prints.pop(key, None)
  3799. _expected_print_registered_at.pop(key, None)
  3800. if expected_archive_id:
  3801. # Clean up other possible keys for this print
  3802. for other_key in expected_keys:
  3803. _expected_prints.pop(other_key, None)
  3804. _expected_print_registered_at.pop(other_key, None)
  3805. break
  3806. if expected_archive_id:
  3807. # This is a reprint/scheduled print - use existing archive, don't create new one
  3808. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3809. from backend.app.models.archive import PrintArchive
  3810. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3811. archive = result.scalar_one_or_none()
  3812. if archive:
  3813. # Update archive status to printing
  3814. archive.status = "printing"
  3815. archive.started_at = datetime.now(timezone.utc)
  3816. # The previous run's answer is still on this row and the
  3817. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3818. # so without a reset the second run inherits the first run's
  3819. # verdict: no prompt at all, and a green "good" badge on a run
  3820. # nobody ever judged.
  3821. if archive.confirm_requested:
  3822. archive.user_verdict = None
  3823. archive.user_verdict_source = None
  3824. archive.user_verdict_at = None
  3825. archive.confirm_token = None
  3826. archive.confirm_token_used_at = None
  3827. # Reprint of an archive reuses the source row. Without resetting
  3828. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3829. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3830. # extracts the *original* print's last frame, which then ships in
  3831. # the completion notification (#1707). Clear the path so the
  3832. # scanner runs fresh; also unlink the old video file so reprints
  3833. # don't accumulate orphans in the archive directory. Photos list
  3834. # is left alone — accumulating one finish photo per run is fine.
  3835. # The print-start baseline (#2704) is stale for the same reason:
  3836. # it describes the printer before the previous run. The capture
  3837. # below overwrites it, but clear it here too so an early failure
  3838. # can't leave the scan diffing against the wrong snapshot.
  3839. archive.timelapse_baseline = None
  3840. stale_timelapse_relpath = archive.timelapse_path
  3841. if stale_timelapse_relpath:
  3842. archive.timelapse_path = None
  3843. try:
  3844. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3845. if stale_path.is_file():
  3846. stale_path.unlink()
  3847. logger.info(
  3848. "Deleted stale timelapse %s on reprint of archive %s",
  3849. stale_timelapse_relpath,
  3850. expected_archive_id,
  3851. )
  3852. except OSError as e:
  3853. logger.warning(
  3854. "Failed to delete stale timelapse %s on reprint: %s",
  3855. stale_timelapse_relpath,
  3856. e,
  3857. )
  3858. # Persist a restart-stable id so a later restart resumes this
  3859. # archive by subtask_id instead of name-matching + duplicating
  3860. # it (#1485). The printer often hasn't echoed subtask_id back
  3861. # this soon after dispatch, so fall back to the id Bambuddy
  3862. # minted when it sent the print command. Scoped to this
  3863. # expected-print branch on purpose: an expected match means
  3864. # Bambuddy dispatched this exact print in this process, so the
  3865. # client's last-dispatch id genuinely belongs to it — using it
  3866. # for an externally-started print could mis-tag the archive.
  3867. effective_subtask_id = subtask_id
  3868. if not effective_subtask_id:
  3869. _client = printer_manager.get_client(printer_id)
  3870. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3871. if _dispatched:
  3872. effective_subtask_id = str(_dispatched).strip() or None
  3873. # Update on first-set OR on reprint (the queue dispatcher mints
  3874. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3875. # the rewrite for reprints leaves the archive holding the FIRST
  3876. # run's id; if MQTT then reconnects mid-print, the reconciler
  3877. # (#1542) compares the stale stored id against the printer's
  3878. # live id, sees a mismatch, and synthesises a bogus PRINT
  3879. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3880. # in #1807. Inequality check preserves the noop-on-stable-push
  3881. # behaviour the earlier `not archive.subtask_id` guard provided.
  3882. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3883. archive.subtask_id = effective_subtask_id
  3884. # #1403 follow-up: VP-queue archives are created with
  3885. # printer_id=None at queue-add time (we don't know which
  3886. # printer will run the job yet). When the print actually
  3887. # starts on a specific printer the expected-archive lookup
  3888. # used to skip this assignment, leaving printer_id=None
  3889. # forever — which then disables the "Scan for timelapse"
  3890. # button in ArchivesPage (gated on !archive.printer_id).
  3891. if archive.printer_id != printer_id:
  3892. archive.printer_id = printer_id
  3893. await db.commit()
  3894. # Track as active print
  3895. _active_prints[(printer_id, archive.filename)] = archive.id
  3896. if subtask_name:
  3897. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3898. # Start timelapse session if external camera is enabled (#1353).
  3899. # Queue / VP-dispatched prints land here in the expected-archive
  3900. # branch and used to skip start_session entirely — frames were
  3901. # never captured and the post-print stitch silently returned None.
  3902. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3903. # Inject ams_mapping into usage tracker session — the session was created
  3904. # before expected-print promotion, so it may have ams_mapping=None when
  3905. # the MQTT request topic subscription failed (common on P1S/A1).
  3906. _stored_map = _print_ams_mappings.get(expected_archive_id)
  3907. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  3908. if _stored_map or _stored_plate_id is not None:
  3909. try:
  3910. from backend.app.services.usage_tracker import _active_sessions
  3911. _ut_session = _active_sessions.get(printer_id)
  3912. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  3913. _ut_session.ams_mapping = _stored_map
  3914. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  3915. # plate_id injection covers direct-Print of plate N of a multi-plate
  3916. # 3MF — queue prints already capture it via the on_print_start queue
  3917. # lookup, but direct-Print never goes through the queue (#1697).
  3918. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  3919. _ut_session.plate_id = _stored_plate_id
  3920. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  3921. except Exception:
  3922. pass
  3923. # Set up energy tracking (#941: persist start on archive row)
  3924. await _record_energy_start(archive, printer_id, db, context="expected-print")
  3925. await ws_manager.send_archive_updated(
  3926. {
  3927. "id": archive.id,
  3928. "status": "printing",
  3929. }
  3930. )
  3931. # Send notification with archive data (reprint/scheduled)
  3932. if not notification_sent:
  3933. # Use archive's created_by_id; fall back to the creator registered via
  3934. # register_expected_print (handles library-file-based queue items where
  3935. # the freshly-created archive has no created_by_id yet).
  3936. # Pop ALL matching keys so no stale entries remain in the dict.
  3937. fallback_creator = None
  3938. for key in expected_keys:
  3939. popped = _expected_print_creators.pop(key, None)
  3940. if fallback_creator is None:
  3941. fallback_creator = popped
  3942. archive_data = {
  3943. "print_time_seconds": archive.print_time_seconds,
  3944. "created_by_id": archive.created_by_id or fallback_creator,
  3945. }
  3946. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3947. # Extract printable objects from the archived 3MF file
  3948. _load_objects_from_archive(archive, printer_id, logger)
  3949. # Store Spoolman tracking data for per-filament usage reporting
  3950. try:
  3951. await _store_spoolman_print_data(
  3952. printer_id,
  3953. archive.id,
  3954. archive.file_path,
  3955. db,
  3956. printer_manager,
  3957. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3958. plate_id=_get_start_plate_id(archive.id),
  3959. )
  3960. except Exception as e:
  3961. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3962. # Capture timelapse file baseline for snapshot-diff on completion
  3963. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  3964. # hit this branch — without the baseline the completion-time scan
  3965. # falls into its "take baseline now" fallback, which snapshots
  3966. # AFTER the new MP4 already exists and never matches a diff
  3967. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  3968. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3969. return # Skip creating a new archive
  3970. # Check if there's already a "printing" archive for this printer/file
  3971. # This prevents duplicates when backend restarts during an active print
  3972. from backend.app.models.archive import PrintArchive
  3973. existing_archive: PrintArchive | None = None
  3974. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  3975. # across a backend restart for the same print, so this is the most
  3976. # reliable way to reattach. We also accept a previously stale-cancelled
  3977. # archive here so users upgrading mid-print get revived when the row
  3978. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  3979. if subtask_id:
  3980. by_id = await db.execute(
  3981. select(PrintArchive)
  3982. .where(PrintArchive.printer_id == printer_id)
  3983. .where(PrintArchive.subtask_id == subtask_id)
  3984. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  3985. .order_by(PrintArchive.created_at.desc())
  3986. .limit(1)
  3987. )
  3988. candidate = by_id.scalar_one_or_none()
  3989. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3990. existing_archive = candidate
  3991. # Fallback match: name-based lookup. Kept as-is for prints whose
  3992. # subtask_id is missing ("0" / local / non-cloud prints).
  3993. if existing_archive is None:
  3994. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3995. existing = await db.execute(
  3996. select(PrintArchive)
  3997. .where(PrintArchive.printer_id == printer_id)
  3998. .where(PrintArchive.status == "printing")
  3999. .where(
  4000. or_(
  4001. PrintArchive.print_name == check_name,
  4002. PrintArchive.filename.in_(
  4003. [
  4004. f"{check_name}.3mf",
  4005. f"{check_name}.gcode.3mf",
  4006. ]
  4007. ),
  4008. )
  4009. )
  4010. .order_by(PrintArchive.created_at.desc())
  4011. .limit(1)
  4012. )
  4013. existing_archive = existing.scalar_one_or_none()
  4014. if existing_archive:
  4015. # subtask_id match → always resume, regardless of age. Same print,
  4016. # just a backend restart. Revive if it was previously stale-cancelled.
  4017. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4018. if subtask_match:
  4019. if existing_archive.status == "cancelled":
  4020. logger.warning(
  4021. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4022. existing_archive.id,
  4023. subtask_id,
  4024. )
  4025. existing_archive.status = "printing"
  4026. existing_archive.failure_reason = None
  4027. await db.commit()
  4028. else:
  4029. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4030. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4031. if existing_archive.energy_start_kwh is None:
  4032. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4033. if not notification_sent:
  4034. archive_data = {
  4035. "print_time_seconds": existing_archive.print_time_seconds,
  4036. "created_by_id": existing_archive.created_by_id,
  4037. }
  4038. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4039. _load_objects_from_archive(existing_archive, printer_id, logger)
  4040. return
  4041. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4042. # stale from the printer's *current* progress, not wall-clock age.
  4043. # A genuinely long print used to trip a blind 4h cutoff and have its
  4044. # live archive cancelled + duplicated on every backend restart
  4045. # (#1485). If the printer reports real progress, this name-matched
  4046. # 'printing' archive IS that ongoing print — resume it whatever its
  4047. # age. Only treat it as a stale leftover when the printer clearly
  4048. # shows a different, freshly-started print: near-0% progress on an
  4049. # archive far too old to still be at 0%. Unknown progress (printer
  4050. # not connected) never cancels — resuming is the safe default.
  4051. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4052. live_status = printer_manager.get_status(printer_id)
  4053. live_progress = getattr(live_status, "progress", None) if live_status else None
  4054. looks_stale = (
  4055. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4056. )
  4057. if looks_stale:
  4058. logger.warning(
  4059. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4060. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4061. )
  4062. existing_archive.status = "cancelled"
  4063. # Canonical key, not a sentence (issue #2974). "No status update
  4064. # received" is what both stale paths actually observed; which of
  4065. # the two it was is already carried by ``status`` -- cancelled
  4066. # here, the reconciled outcome at the reconnect site -- so one
  4067. # key loses no information and gives the Statistics breakdown a
  4068. # single bucket instead of two untranslatable prose strings.
  4069. existing_archive.failure_reason = "noStatusUpdate"
  4070. await db.commit()
  4071. # Fall through to create new archive (don't return)
  4072. else:
  4073. logger.info(
  4074. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4075. )
  4076. # Track this as the active print
  4077. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4078. # Attach subtask_id retroactively so future restarts can resume.
  4079. # Compare for inequality (not "is empty") to also pick up reprint
  4080. # dispatches that mint a fresh id — see #1807 for the bogus
  4081. # "Print Stopped" the strict-empty guard caused on reconnect.
  4082. if subtask_id and existing_archive.subtask_id != subtask_id:
  4083. existing_archive.subtask_id = subtask_id
  4084. await db.commit()
  4085. # Also set up energy tracking if not already tracked (#941: persisted column)
  4086. if existing_archive.energy_start_kwh is None:
  4087. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4088. # Send notification with archive data (existing archive)
  4089. if not notification_sent:
  4090. archive_data = {
  4091. "print_time_seconds": existing_archive.print_time_seconds,
  4092. "created_by_id": existing_archive.created_by_id,
  4093. }
  4094. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4095. # Extract printable objects from the archived 3MF file
  4096. _load_objects_from_archive(existing_archive, printer_id, logger)
  4097. return
  4098. # Build list of possible 3MF filenames to try
  4099. possible_names = []
  4100. # Bambu printers typically store files as "Name.gcode.3mf"
  4101. # The subtask_name is usually the best source for the filename
  4102. if subtask_name:
  4103. # Try common Bambu naming patterns
  4104. possible_names.append(f"{subtask_name}.gcode.3mf")
  4105. possible_names.append(f"{subtask_name}.3mf")
  4106. # Try original filename with .3mf extension
  4107. if filename:
  4108. # Extract just the filename part, not the full path
  4109. fname = filename.split("/")[-1] if "/" in filename else filename
  4110. if fname.endswith(".3mf"):
  4111. possible_names.append(fname)
  4112. elif fname.endswith(".gcode"):
  4113. base = fname.rsplit(".", 1)[0]
  4114. possible_names.append(f"{base}.gcode.3mf")
  4115. possible_names.append(f"{base}.3mf")
  4116. else:
  4117. possible_names.append(f"{fname}.gcode.3mf")
  4118. possible_names.append(f"{fname}.3mf")
  4119. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4120. space_variants = []
  4121. for name in possible_names:
  4122. if " " in name:
  4123. space_variants.append(name.replace(" ", "_"))
  4124. possible_names.extend(space_variants)
  4125. # Remove duplicates while preserving order
  4126. seen = set()
  4127. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4128. logger.info("Trying filenames: %s", possible_names)
  4129. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4130. # here means none of the expected-/existing-archive write branches ran
  4131. # (they all return earlier) — only SELECTs have executed on this path, so
  4132. # this commit persists nothing; it ends the read transaction so the
  4133. # connection returns to the pool during the download. That download tries
  4134. # up to five remote paths per candidate filename with retry/backoff and
  4135. # can run for minutes under FTP contention; holding the session across it
  4136. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4137. # work runs during the download — the new-archive writes below re-acquire
  4138. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4139. await db.commit()
  4140. # Try to find and download the 3MF file
  4141. temp_path = None
  4142. downloaded_filename = None
  4143. # Cache check: cover endpoint may have already pulled this 3MF during
  4144. # the print (frontend opens the card and shows the thumbnail) — reuse
  4145. # that file instead of re-downloading 36MB over the same FTP link that
  4146. # just served it (#972). The cache keys on a normalized filename so
  4147. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4148. for try_filename in possible_names:
  4149. if not try_filename.endswith(".3mf"):
  4150. continue
  4151. cached = get_cached_3mf(printer_id, try_filename)
  4152. if cached:
  4153. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4154. temp_path = cached
  4155. downloaded_filename = try_filename
  4156. break
  4157. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4158. # H2-series and P2S the answer is routinely no — the file stays on
  4159. # internal eMMC and port 990 only ever serves external storage — and
  4160. # then the whole sweep below (six filenames x five directories x four
  4161. # retries, then the directory walk) is ~110 connections that cannot
  4162. # succeed. Skip it and say why (#2780).
  4163. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4164. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4165. # running rather than because the file is somewhere unreachable. The
  4166. # distinction is the whole of #2957: one is permanent, the other clears
  4167. # in minutes with the file still sitting on the printer.
  4168. blocked_by_ftps_cooloff = False
  4169. # Set when a probe reached the printer and still came back without the
  4170. # file -- a timeout mid-transfer, a refused connection, anything that is
  4171. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4172. # caught by name below, so a file that genuinely is not on the card
  4173. # leaves this False and schedules nothing. Anything else means the
  4174. # transfer, not the file, is what failed, and that does not last (#3063).
  4175. ftp_transfer_failed = False
  4176. # The print's name, for a fallback archive whose `subtask_name` the
  4177. # plate guard below had to disown. Display only, and deliberately kept
  4178. # apart from `subtask_name`: that variable is what every file lookup
  4179. # here is built from, and once a name has been shown to fetch another
  4180. # plate's 3MF it must not key `_active_prints` either, or the cover
  4181. # endpoint hands the same contradicted file to
  4182. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4183. display_name_after_plate_reject: str | None = None
  4184. # Get FTP retry settings
  4185. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4186. # ...but "the printer put it on eMMC" is where it went, not whether we
  4187. # can read it. An H2D with a card in mirrors the job to /cache and
  4188. # serves it happily, and skipping on the URL alone cost that reporter
  4189. # every archive for two days (#2856). So ask the printer instead of
  4190. # guessing: the dispatch named the exact file, which is one connection
  4191. # walking five paths rather than the sweep's ~110. Only when the probe
  4192. # comes back empty does the verdict's reason stand.
  4193. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4194. if ftps_handshake_blocked(printer.ip_address):
  4195. # Deliberately NOT recorded as a cool-off give-up. This branch
  4196. # only runs on an unreachable verdict, and that verdict is the
  4197. # honest, permanent reason the archive is empty — the probe was
  4198. # a long shot on top of it. Blaming the cool-off here would
  4199. # schedule a retry for a file sitting on internal eMMC, which is
  4200. # the sweep #2780 removed (#2957).
  4201. logger.debug(
  4202. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4203. storage.probe_filename,
  4204. printer_id,
  4205. )
  4206. else:
  4207. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4208. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4209. try:
  4210. probe_hit = await download_file_try_paths_async(
  4211. printer.ip_address,
  4212. printer.access_code,
  4213. ftp_probe_paths(storage.probe_filename),
  4214. probe_path,
  4215. socket_timeout=ftp_timeout,
  4216. printer_model=printer.model,
  4217. )
  4218. except Exception as e:
  4219. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4220. probe_hit = False
  4221. if probe_hit:
  4222. downloaded_filename = storage.probe_filename
  4223. temp_path = probe_path
  4224. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4225. # Naming the path, not just the file: a printer that keeps
  4226. # uploads around for weeks can serve a same-named copy of an
  4227. # earlier slice, and without the directory in the log that
  4228. # mismatch is invisible rather than merely rare (#1820).
  4229. logger.info(
  4230. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4231. downloaded_filename,
  4232. probe_hit,
  4233. printer_id,
  4234. storage.reason,
  4235. )
  4236. if not storage.reachable and not downloaded_filename:
  4237. # Same opening words whether or not a probe ran, because that is
  4238. # the phrase support asks people to grep for — only the tail says
  4239. # which of the two happened.
  4240. logger.info(
  4241. "Skipping the 3MF lookup for printer %s: %s — %s",
  4242. printer_id,
  4243. storage.reason,
  4244. "no copy of it on external storage either"
  4245. if storage.probe_filename
  4246. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4247. )
  4248. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4249. if not try_filename.endswith(".3mf"):
  4250. continue
  4251. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4252. # printers, so try it first — deferring it to last cost #972's reporter
  4253. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4254. # landing on the path that actually had the file.
  4255. remote_paths = [
  4256. f"/{try_filename}",
  4257. f"/cache/{try_filename}",
  4258. f"/model/{try_filename}",
  4259. f"/data/{try_filename}",
  4260. f"/data/Metadata/{try_filename}",
  4261. ]
  4262. temp_path = app_settings.archive_dir / "temp" / try_filename
  4263. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4264. for remote_path in remote_paths:
  4265. if ftps_handshake_blocked(printer.ip_address):
  4266. # The printer's FTPS service is not completing a TLS
  4267. # handshake, so it has no path we could reach — walking the
  4268. # remaining candidates only re-runs the same failure
  4269. # (#2780). Fall through to the no-3MF archive now.
  4270. #
  4271. # Remember *why*, though. This is the one give-up that is
  4272. # temporary: the cool-off clears in minutes and the file was
  4273. # on the printer the whole time. The fallback archive is
  4274. # stamped with it so a retry can be scheduled, and so the
  4275. # Archives banner stops blaming storage (#2957).
  4276. blocked_by_ftps_cooloff = True
  4277. logger.warning(
  4278. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4279. printer_id,
  4280. )
  4281. break
  4282. logger.debug("Trying FTP download: %s", remote_path)
  4283. try:
  4284. if ftp_retry_enabled:
  4285. downloaded = await with_ftp_retry(
  4286. download_file_async,
  4287. printer.ip_address,
  4288. printer.access_code,
  4289. remote_path,
  4290. temp_path,
  4291. timeout=ftp_timeout,
  4292. socket_timeout=ftp_timeout,
  4293. printer_model=printer.model,
  4294. max_retries=ftp_retry_count,
  4295. retry_delay=ftp_retry_delay,
  4296. operation_name=f"Download 3MF from {remote_path}",
  4297. cooloff_ip=printer.ip_address,
  4298. non_retry_exceptions=(FileNotOnPrinterError,),
  4299. )
  4300. else:
  4301. downloaded = await download_file_async(
  4302. printer.ip_address,
  4303. printer.access_code,
  4304. remote_path,
  4305. temp_path,
  4306. timeout=ftp_timeout,
  4307. socket_timeout=ftp_timeout,
  4308. printer_model=printer.model,
  4309. )
  4310. if downloaded:
  4311. downloaded_filename = try_filename
  4312. logger.info("Downloaded: %s", remote_path)
  4313. # Populate shared cache so the cover endpoint (if it
  4314. # runs next) doesn't refetch the same 36MB over FTP.
  4315. cache_3mf_download(printer_id, try_filename, temp_path)
  4316. break
  4317. # with_ftp_retry returns None once it has spent its budget,
  4318. # and download_file_async returns False on a timeout, so an
  4319. # exhausted transfer arrives here rather than as an
  4320. # exception (#3063).
  4321. ftp_transfer_failed = True
  4322. except FileNotOnPrinterError:
  4323. # 550 — file isn't at this path. Advance to next candidate
  4324. # without burning the retry budget.
  4325. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4326. except Exception as e:
  4327. ftp_transfer_failed = True
  4328. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4329. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4330. break
  4331. # If still not found, try listing directories to find matching file
  4332. # Different printer models use different directory structures. Skipped
  4333. # when the printer's FTPS handshake is failing — the directory walk is
  4334. # five more connections that cannot get further than the download did.
  4335. if (
  4336. not downloaded_filename
  4337. and storage.reachable
  4338. and (filename or subtask_name)
  4339. and not ftps_handshake_blocked(printer.ip_address)
  4340. ):
  4341. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4342. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4343. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4344. for search_dir in search_dirs:
  4345. if downloaded_filename:
  4346. break
  4347. try:
  4348. dir_files = await list_files_async(
  4349. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4350. )
  4351. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4352. if threemf_files:
  4353. logger.info(
  4354. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4355. )
  4356. for f in dir_files:
  4357. if f.get("is_directory"):
  4358. continue
  4359. fname = f.get("name", "")
  4360. # Normalize both for comparison (spaces and underscores are equivalent)
  4361. fname_normalized = fname.lower().replace(" ", "_")
  4362. search_normalized = search_term.replace(" ", "_")
  4363. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4364. logger.info("Found matching file in %s: %s", search_dir, fname)
  4365. temp_path = app_settings.archive_dir / "temp" / fname
  4366. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4367. remote_full_path = posixpath.join(search_dir, fname)
  4368. if ftp_retry_enabled:
  4369. downloaded = await with_ftp_retry(
  4370. download_file_async,
  4371. printer.ip_address,
  4372. printer.access_code,
  4373. remote_full_path,
  4374. temp_path,
  4375. timeout=ftp_timeout,
  4376. socket_timeout=ftp_timeout,
  4377. printer_model=printer.model,
  4378. max_retries=ftp_retry_count,
  4379. retry_delay=ftp_retry_delay,
  4380. operation_name=f"Download 3MF from {remote_full_path}",
  4381. cooloff_ip=printer.ip_address,
  4382. )
  4383. else:
  4384. downloaded = await download_file_async(
  4385. printer.ip_address,
  4386. printer.access_code,
  4387. remote_full_path,
  4388. temp_path,
  4389. timeout=ftp_timeout,
  4390. socket_timeout=ftp_timeout,
  4391. printer_model=printer.model,
  4392. )
  4393. if downloaded:
  4394. downloaded_filename = fname
  4395. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4396. cache_3mf_download(printer_id, fname, temp_path)
  4397. break
  4398. # The listing named the file, so it is on the card;
  4399. # only the transfer failed (#3063).
  4400. ftp_transfer_failed = True
  4401. except Exception as e:
  4402. logger.debug("Failed to list %s: %s", search_dir, e)
  4403. # Validate the downloaded 3MF actually matches the plate that's running
  4404. # (#1204): subtask_name lags across consecutive plates of the same model,
  4405. # so the first FTP candidate (built from subtask_name) can land on the
  4406. # previous plate's still-resident upload. Cross-check the slice_info
  4407. # plate index against the plate parsed from gcode_file (always fresh —
  4408. # it's the field whose change triggered this callback).
  4409. if downloaded_filename and temp_path:
  4410. expected_plate = parse_plate_id(filename)
  4411. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4412. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4413. logger.warning(
  4414. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4415. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4416. downloaded_filename,
  4417. actual_plate,
  4418. expected_plate,
  4419. subtask_name,
  4420. )
  4421. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4422. retry_succeeded = False
  4423. if corrected_subtask and corrected_subtask != subtask_name:
  4424. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4425. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4426. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4427. for remote_path in (
  4428. f"/{try_filename}",
  4429. f"/cache/{try_filename}",
  4430. f"/model/{try_filename}",
  4431. f"/data/{try_filename}",
  4432. f"/data/Metadata/{try_filename}",
  4433. ):
  4434. try:
  4435. if ftp_retry_enabled:
  4436. downloaded = await with_ftp_retry(
  4437. download_file_async,
  4438. printer.ip_address,
  4439. printer.access_code,
  4440. remote_path,
  4441. retry_temp_path,
  4442. timeout=ftp_timeout,
  4443. socket_timeout=ftp_timeout,
  4444. printer_model=printer.model,
  4445. max_retries=ftp_retry_count,
  4446. retry_delay=ftp_retry_delay,
  4447. operation_name=f"Re-download 3MF from {remote_path}",
  4448. cooloff_ip=printer.ip_address,
  4449. non_retry_exceptions=(FileNotOnPrinterError,),
  4450. )
  4451. else:
  4452. downloaded = await download_file_async(
  4453. printer.ip_address,
  4454. printer.access_code,
  4455. remote_path,
  4456. retry_temp_path,
  4457. timeout=ftp_timeout,
  4458. socket_timeout=ftp_timeout,
  4459. printer_model=printer.model,
  4460. )
  4461. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4462. logger.info(
  4463. "[CALLBACK] Re-download succeeded with corrected name %s "
  4464. "(plate %s) — replacing wrong file",
  4465. try_filename,
  4466. expected_plate,
  4467. )
  4468. try:
  4469. temp_path.unlink(missing_ok=True)
  4470. except OSError:
  4471. pass
  4472. temp_path = retry_temp_path
  4473. downloaded_filename = try_filename
  4474. subtask_name = corrected_subtask
  4475. cache_3mf_download(printer_id, try_filename, temp_path)
  4476. retry_succeeded = True
  4477. break
  4478. elif downloaded:
  4479. # Wrong plate again — discard and keep trying
  4480. try:
  4481. retry_temp_path.unlink(missing_ok=True)
  4482. except OSError:
  4483. pass
  4484. except FileNotOnPrinterError:
  4485. continue
  4486. except Exception as e:
  4487. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4488. if retry_succeeded:
  4489. break
  4490. # If the retry didn't find a matching file, drop the wrong 3MF
  4491. # so the no-3MF fallback below creates an archive whose name
  4492. # at least reflects the right plate.
  4493. if not retry_succeeded:
  4494. logger.warning(
  4495. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4496. expected_plate,
  4497. )
  4498. try:
  4499. temp_path.unlink(missing_ok=True)
  4500. except OSError:
  4501. pass
  4502. temp_path = None
  4503. downloaded_filename = None
  4504. # Whatever the sweep's transport did earlier, it is not why
  4505. # this archive ends up empty: a 3MF downloaded fine, it was
  4506. # just the wrong plate. Retrying would re-fetch that same
  4507. # contradicted file under the same stale names and hand it
  4508. # to _recover_fallback_archive, which checks that a
  4509. # candidate is a readable 3MF but not which plate it is --
  4510. # so the row would be filled in with another plate's
  4511. # filament and cost, the exact swap #2957 removed (#3063).
  4512. ftp_transfer_failed = False
  4513. # Disown the name for *lookups*: it has just been shown to
  4514. # fetch another plate's 3MF, and it keys `_active_prints`
  4515. # below, where the cover endpoint's own download of that
  4516. # same name would find this archive and fill it in with the
  4517. # file we are discarding here.
  4518. #
  4519. # Keep it for the *title*, which is a separate question.
  4520. # ``swap_plate_suffix`` returns None both for a name that
  4521. # carries no "- Plate N" / "_plate_N" suffix and for no
  4522. # name at all, and those are not the same situation: a name
  4523. # without a suffix holds no stale plate number to be wrong
  4524. # about. Blanking both uses at once dropped the project
  4525. # name too, and the row fell through to the gcode_file path
  4526. # titled "plate_1" though the real name was in hand.
  4527. # #1204's own premise is consecutive plates *of the same
  4528. # model*, so the project part is right either way (#3126).
  4529. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4530. subtask_name = corrected_subtask or ""
  4531. if not downloaded_filename or not temp_path:
  4532. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4533. # Create a fallback archive without 3MF data so the print is still tracked
  4534. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4535. try:
  4536. from backend.app.models.archive import PrintArchive
  4537. # Why the card is empty. The two temporary causes outrank the
  4538. # storage verdict because they say the sweep never got a fair
  4539. # answer: a cool-off skipped it at the transport, and a failed
  4540. # transfer reached the printer but never finished. Either way
  4541. # the file is still on the card, so reporting where the printer
  4542. # files its jobs would describe a setting that is not the
  4543. # problem (#2957, #3063).
  4544. if blocked_by_ftps_cooloff:
  4545. no_3mf_reason = REASON_FTPS_COOLOFF
  4546. elif storage.reachable and ftp_transfer_failed:
  4547. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4548. else:
  4549. no_3mf_reason = storage.reason
  4550. # Derive print name from subtask_name or filename. The
  4551. # plate guard's disowned name comes second: it is a real name
  4552. # for a real print, and only the gcode_file path is left
  4553. # otherwise -- which titles the row "plate_1" (#3126).
  4554. print_name = subtask_name or display_name_after_plate_reject or filename
  4555. if print_name:
  4556. # Clean up the name (remove extensions, path parts)
  4557. print_name = print_name.split("/")[-1]
  4558. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4559. else:
  4560. print_name = "Unknown Print"
  4561. # Recover estimated print time from MQTT (best-effort for notifications)
  4562. fallback_print_time = None
  4563. mqtt_remaining = data.get("remaining_time")
  4564. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4565. fallback_print_time = int(mqtt_remaining)
  4566. if fallback_print_time is None:
  4567. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4568. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4569. fallback_print_time = int(mc_remaining * 60)
  4570. # Best-effort filament metadata from MQTT — see
  4571. # _extract_filament_data_from_mqtt. Without this the fallback
  4572. # archive's filament fields stayed NULL even though the AMS
  4573. # state at print start was sitting right there in `data`.
  4574. # The slicer's ams_mapping (when present) narrows the result
  4575. # to slots actually used by the print (#1533).
  4576. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4577. # Create minimal archive entry
  4578. fallback_archive = PrintArchive(
  4579. printer_id=printer_id,
  4580. filename=filename or f"{print_name}.3mf",
  4581. file_path="", # Empty - no 3MF file available
  4582. file_size=0,
  4583. print_name=print_name,
  4584. print_time_seconds=fallback_print_time,
  4585. status="printing",
  4586. started_at=datetime.now(timezone.utc),
  4587. subtask_id=subtask_id,
  4588. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4589. filament_type=mqtt_filament_meta.get("filament_type"),
  4590. filament_color=mqtt_filament_meta.get("filament_color"),
  4591. extra_data={
  4592. "no_3mf_available": True,
  4593. # Why the card is empty, when we know -- see above. The
  4594. # banner reads this to stop telling H2/P2 owners to
  4595. # switch on a setting that is already on and would not
  4596. # have helped (#2780).
  4597. "no_3mf_reason": no_3mf_reason,
  4598. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4599. "_print_data": data,
  4600. },
  4601. )
  4602. db.add(fallback_archive)
  4603. await db.commit()
  4604. await db.refresh(fallback_archive)
  4605. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4606. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4607. # Track as active print
  4608. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4609. if filename:
  4610. _active_prints[(printer_id, filename)] = fallback_archive.id
  4611. if subtask_name:
  4612. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4613. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4614. # Record starting energy if smart plug available (#941: persisted column)
  4615. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4616. # Send WebSocket notification
  4617. await ws_manager.send_archive_created(
  4618. {
  4619. "id": fallback_archive.id,
  4620. "printer_id": fallback_archive.printer_id,
  4621. "filename": fallback_archive.filename,
  4622. "print_name": fallback_archive.print_name,
  4623. "status": fallback_archive.status,
  4624. }
  4625. )
  4626. # MQTT relay - publish archive created
  4627. try:
  4628. await mqtt_relay.on_archive_created(
  4629. archive_id=fallback_archive.id,
  4630. print_name=fallback_archive.print_name,
  4631. printer_name=printer.name,
  4632. status=fallback_archive.status,
  4633. )
  4634. except Exception:
  4635. pass # Don't fail if MQTT fails
  4636. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4637. try:
  4638. await _store_spoolman_print_data(
  4639. printer_id,
  4640. fallback_archive.id,
  4641. fallback_archive.file_path,
  4642. db,
  4643. printer_manager,
  4644. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4645. plate_id=_get_start_plate_id(fallback_archive.id),
  4646. )
  4647. except Exception as e:
  4648. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4649. # Both temporary give-ups are worth coming back for, and for
  4650. # the same reason: the file is on the printer and the last look
  4651. # failed at the transport rather than finding nothing. One waits
  4652. # out the handshake block (#2957), the other waits for the
  4653. # printer to stop being busy (#3063). Deliberately not scheduled
  4654. # for a storage verdict: a file on internal eMMC will not appear
  4655. # at any FTPS path however long we wait, and retrying it is
  4656. # exactly the sweep #2780 removed.
  4657. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4658. # `possible_names`, not the raw MQTT strings: it is the exact
  4659. # list this flow just tried, already stripped of any path
  4660. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4661. # some firmware) and deduped.
  4662. _schedule_fallback_3mf_retry(
  4663. printer_id=printer_id,
  4664. archive_id=fallback_archive.id,
  4665. filenames=list(possible_names),
  4666. reason=no_3mf_reason,
  4667. )
  4668. # Send notification without archive data (file not found)
  4669. if not notification_sent:
  4670. await _send_print_start_notification(printer_id, data, logger=logger)
  4671. # The same baseline the other two on_print_start branches take
  4672. # (#2704), and last for the same reason they are: it lists the
  4673. # printer's timelapse directory, so a slow card must not delay
  4674. # the _active_prints registration, the energy reading, the
  4675. # archive-created event or the start notification above it.
  4676. #
  4677. # This branch never took one, so every no-3MF archive reached
  4678. # completion with no baseline in memory and none on the row, and
  4679. # the completion scan fell into its "snapshot now" fallback --
  4680. # which runs after the printer has written the video, so the new
  4681. # file landed inside the baseline and no diff ever matched
  4682. # (#2957 follow-up).
  4683. #
  4684. # Skipped when the FTPS cool-off is what produced this fallback:
  4685. # the listing needs the same connection that just failed, so it
  4686. # could only record that the card was unreadable. The scan
  4687. # handles that case by refusing to choose between candidates.
  4688. if not blocked_by_ftps_cooloff:
  4689. await _capture_timelapse_baseline_at_start(
  4690. printer, printer_id, logger, archive_id=fallback_archive.id
  4691. )
  4692. return
  4693. except Exception as e:
  4694. logger.error("Failed to create fallback archive: %s", e)
  4695. # Send notification without archive data (file not found)
  4696. if not notification_sent:
  4697. await _send_print_start_notification(printer_id, data, logger=logger)
  4698. return
  4699. try:
  4700. # Archive the file with status "printing"
  4701. service = ArchiveService(db)
  4702. archive = await service.archive_print(
  4703. printer_id=printer_id,
  4704. source_file=temp_path,
  4705. print_data={**data, "status": "printing"},
  4706. subtask_id=subtask_id,
  4707. )
  4708. if archive:
  4709. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4710. # Set on the row rather than passed to archive_print, which also
  4711. # serves the queue dispatcher — there the queue item decides.
  4712. # Guarded because this branch has no ``except``: an unhandled
  4713. # write error would take the _active_prints registration, the
  4714. # start notification, the energy reading and the timelapse
  4715. # baseline below it with it, and a missing prompt is by far the
  4716. # cheaper failure.
  4717. archive_id = archive.id
  4718. try:
  4719. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4720. archive.confirm_requested = True
  4721. await db.commit()
  4722. except Exception as e:
  4723. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  4724. # The rollback expires every loaded object, and on an async
  4725. # session reading one afterwards raises instead of
  4726. # reloading, so the two this branch goes on to use are
  4727. # fetched again. The archive itself was committed by
  4728. # archive_print; only the flag is lost.
  4729. try:
  4730. await db.rollback()
  4731. archive = await db.get(PrintArchive, archive_id)
  4732. printer = await db.get(Printer, printer_id)
  4733. except Exception as reload_error:
  4734. logger.warning(
  4735. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  4736. )
  4737. # Track this active print (use both original filename and downloaded filename)
  4738. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4739. if filename and filename != downloaded_filename:
  4740. _active_prints[(printer_id, filename)] = archive.id
  4741. if subtask_name:
  4742. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4743. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4744. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4745. # Record starting energy from smart plug if available (#941: persisted column)
  4746. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4747. await ws_manager.send_archive_created(
  4748. {
  4749. "id": archive.id,
  4750. "printer_id": archive.printer_id,
  4751. "filename": archive.filename,
  4752. "print_name": archive.print_name,
  4753. "status": archive.status,
  4754. }
  4755. )
  4756. # MQTT relay - publish archive created
  4757. try:
  4758. await mqtt_relay.on_archive_created(
  4759. archive_id=archive.id,
  4760. print_name=archive.print_name,
  4761. printer_name=printer.name,
  4762. status=archive.status,
  4763. )
  4764. except Exception:
  4765. pass # Don't fail if MQTT fails
  4766. # Send notification with archive data (new archive created)
  4767. if not notification_sent:
  4768. archive_data = {
  4769. "print_time_seconds": archive.print_time_seconds,
  4770. "created_by_id": archive.created_by_id,
  4771. }
  4772. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4773. # Extract printable objects for skip object functionality
  4774. try:
  4775. from backend.app.services.archive import extract_printable_objects_from_3mf
  4776. client = printer_manager.get_client(printer_id)
  4777. if client:
  4778. with open(temp_path, "rb") as f:
  4779. threemf_data = f.read()
  4780. # Extract with positions for UI overlay, scoped to the
  4781. # plate that is printing — an all-plates 3MF carries
  4782. # every plate's objects (#2522).
  4783. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4784. threemf_data,
  4785. plate_number=resolve_plate_id(client.state),
  4786. include_positions=True,
  4787. )
  4788. if printable_objects:
  4789. # Store objects in printer state
  4790. client.state.printable_objects = printable_objects
  4791. client.state.printable_objects_bbox_all = bbox_all
  4792. client.state.skipped_objects = [] # Reset skipped objects for new print
  4793. logger.info(
  4794. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4795. )
  4796. except Exception as e:
  4797. logger.debug("Failed to extract printable objects: %s", e)
  4798. # Store Spoolman tracking data for per-filament usage reporting
  4799. try:
  4800. await _store_spoolman_print_data(
  4801. printer_id,
  4802. archive.id,
  4803. archive.file_path,
  4804. db,
  4805. printer_manager,
  4806. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4807. plate_id=_get_start_plate_id(archive.id),
  4808. )
  4809. except Exception as e:
  4810. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4811. # Capture timelapse file baseline for snapshot-diff on completion
  4812. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4813. finally:
  4814. # Keep temp_path around until print completes so the cover endpoint
  4815. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4816. # the file. If the cache entry was evicted early (file vanished),
  4817. # clean up any stragglers here to avoid leaking disk on retries.
  4818. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4819. if temp_path and temp_path.exists() and cached_now != temp_path:
  4820. temp_path.unlink()
  4821. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4822. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4823. # tests can shrink them without waiting out real delays.
  4824. #
  4825. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4826. # looking. Across 247 support bundles the attempt that found the video was #1
  4827. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4828. # decaying one, which is the signature of a budget that expires while files are
  4829. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4830. # prints make big videos and the printer writes them after the print ends, so
  4831. # the poll now runs for minutes and costs one FTP LIST per round.
  4832. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4833. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4834. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4835. def _timelapse_scan_max_attempts() -> int:
  4836. """Round cap for the poll, derived from the wall-clock budget.
  4837. The deadline alone is not a sufficient bound: it assumes each round really
  4838. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4839. and an FTP list that fails immediately would otherwise spin against the
  4840. printer at full speed for the whole window. Whichever bound is reached
  4841. first ends the poll.
  4842. """
  4843. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4844. # A zero interval makes the wall-clock budget meaningless; fall back to
  4845. # the round count the production interval would have given.
  4846. return 32
  4847. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4848. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4849. """Video filenames already attached to some other archive of this printer.
  4850. Used to disambiguate when more than one file is new since the baseline —
  4851. which happens when a previous print's video landed after this print's
  4852. baseline was taken. Ordering the candidates would be the obvious fix and is
  4853. the wrong one: it can only be done on mtime or on the filename timestamp,
  4854. both of which come from the printer's own clock, and a LAN-only printer
  4855. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4856. ``attach_timelapse`` saves the video into the archive directory under the
  4857. printer's original filename, and the later MP4 conversion keeps the stem,
  4858. so the stem of ``timelapse_path`` recovers what was claimed.
  4859. """
  4860. from backend.app.models.archive import PrintArchive
  4861. rows = await db.execute(
  4862. select(PrintArchive.timelapse_path).where(
  4863. PrintArchive.printer_id == printer_id,
  4864. PrintArchive.id != exclude_archive_id,
  4865. PrintArchive.timelapse_path.is_not(None),
  4866. )
  4867. )
  4868. return {Path(p).stem for p in rows.scalars().all() if p}
  4869. def _timelapse_listing_is_trustworthy(printer) -> bool:
  4870. """Whether an *empty* timelapse listing for *printer* can be believed.
  4871. ``list_files_async`` answers ``[]`` when its connect fails rather than
  4872. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  4873. from one holding no videos. Everywhere that only wants to know "is there a
  4874. video yet" the difference does not matter — both mean "not yet, retry".
  4875. It matters where an empty listing is recorded as a *baseline*. Recording
  4876. "the card held nothing" for a card that was never read means every video on
  4877. it counts as new once the cool-off expires, and the completion scan then
  4878. attaches a stale video to this print and deletes it from the printer
  4879. (#2957 follow-up). Those two callers ask this first.
  4880. """
  4881. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  4882. ip_address = getattr(printer, "ip_address", None)
  4883. if not ip_address:
  4884. return True
  4885. return not ftps_handshake_blocked(ip_address)
  4886. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  4887. """List video files from printer's timelapse directory.
  4888. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  4889. Returns (video_files, found_path) where video_files is a list of file dicts
  4890. and found_path is the directory where they were found, or ([], None).
  4891. An empty return does not distinguish "no videos" from "could not read the
  4892. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  4893. baseline callers consult before believing one.
  4894. """
  4895. from backend.app.services.bambu_ftp import list_files_async
  4896. logger = logging.getLogger(__name__)
  4897. # No card in the slot means no /timelapse to walk — four connections that
  4898. # can only fail, on a path whose failures are swallowed and so would go on
  4899. # costing time silently forever (#2780).
  4900. #
  4901. # ``getattr`` rather than ``printer.id``: every dereference below happens
  4902. # inside the loop's own try/except, so a caller that passed something
  4903. # unexpected used to get an empty listing rather than an exception. Keep
  4904. # that, instead of making this gate the first thing that can raise here.
  4905. printer_id = getattr(printer, "id", None)
  4906. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  4907. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  4908. return [], None
  4909. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  4910. try:
  4911. found_files = await list_files_async(
  4912. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  4913. )
  4914. if found_files:
  4915. video_files = [
  4916. f
  4917. for f in found_files
  4918. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  4919. ]
  4920. if video_files:
  4921. return video_files, timelapse_path
  4922. except Exception as e:
  4923. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  4924. continue
  4925. return [], None
  4926. async def _capture_timelapse_baseline_at_start(
  4927. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  4928. ) -> None:
  4929. """Snapshot the printer's timelapse directory at print start so the
  4930. completion-time scan can pick the new file by set-difference.
  4931. Must be called from every on_print_start path that proceeds to a real
  4932. print — both the new-archive branch and the expected-archive branch (which
  4933. queue / VP-dispatched prints take). Without a baseline,
  4934. _scan_for_timelapse_with_retries falls into its "take baseline now"
  4935. fallback that runs AFTER the new MP4 has already landed on the SD card,
  4936. so the new file ends up in the "baseline" set and no diff ever matches.
  4937. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  4938. unreliable — the snapshot-diff approach sidesteps that entirely.
  4939. When ``archive_id`` is known the baseline is also written to the archive
  4940. row, so it survives a restart and the manual "Scan for Timelapse" button
  4941. can run the same diff instead of falling back to clock-based matching
  4942. (#2704). Only baselines taken at print start are persisted — one taken at
  4943. completion already contains the new video and would poison a later scan.
  4944. """
  4945. names: set[str] | None = None
  4946. try:
  4947. if not _timelapse_listing_is_trustworthy(printer):
  4948. # Recorded anyway, deliberately. An empty baseline taken off a card
  4949. # we could not read is not authoritative, but it is still the right
  4950. # *default*: Bambuddy deletes each video from the printer once it is
  4951. # attached, so the usual card holds exactly one video at completion
  4952. # and an empty baseline resolves it correctly. Persisting NULL
  4953. # instead would send completion to take its own snapshot, by which
  4954. # point this print's video is on the card and would be swallowed by
  4955. # it. The ambiguity is handled where it actually bites — see
  4956. # ``require_unambiguous`` in the scan (#2957 follow-up).
  4957. logger.warning(
  4958. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  4959. "handshake cool-off, so the card could not be read — treating it as empty",
  4960. printer_id,
  4961. )
  4962. baseline_files, _ = await _list_timelapse_videos(printer)
  4963. names = {f.get("name", "") for f in baseline_files}
  4964. _timelapse_baselines[printer_id] = names
  4965. logger.info(
  4966. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  4967. len(names),
  4968. printer_id,
  4969. )
  4970. except Exception as e:
  4971. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  4972. if archive_id is None:
  4973. return
  4974. try:
  4975. async with async_session() as db:
  4976. from backend.app.models.archive import PrintArchive
  4977. archive = await db.get(PrintArchive, archive_id)
  4978. if archive is not None:
  4979. # Written even when the listing failed, and then as NULL. A
  4980. # reprint reuses the archive row, so leaving the previous run's
  4981. # baseline in place would have the scan diff this print against
  4982. # the state of the printer before the *last* one — and a stale
  4983. # baseline reads as authoritative, where NULL correctly falls
  4984. # back to a fresh snapshot.
  4985. archive.timelapse_baseline = sorted(names) if names is not None else None
  4986. await db.commit()
  4987. except Exception as e:
  4988. # In-memory baseline still covers the normal completion path.
  4989. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  4990. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  4991. """Poll the printer for this print's timelapse and attach it.
  4992. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  4993. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  4994. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  4995. (#2704). Comparing the current listing against the set of filenames that
  4996. existed when the print started needs no clock at all, because the printer
  4997. writes the video only once the print has ended.
  4998. Baseline precedence: the caller's in-memory set, then the one persisted on
  4999. the archive at print start, then a snapshot taken now. The last of those is
  5000. a poor substitute — by completion the new video may already be on the card,
  5001. in which case it lands in the "baseline" and no diff can ever match — but it
  5002. is all that is available for a print that began before Bambuddy started.
  5003. On success the video is deleted from the printer, which keeps ``/timelapse``
  5004. down to the unclaimed files and makes the next diff unambiguous.
  5005. """
  5006. logger = logging.getLogger(__name__)
  5007. # Cleared when the baseline had to be taken off a card we could not read, so
  5008. # the attach step refuses to choose between several candidates (#2957).
  5009. baseline_trusted = True
  5010. # --- Phase 1: establish the baseline -------------------------------------
  5011. try:
  5012. async with async_session() as db:
  5013. from backend.app.models.printer import Printer
  5014. service = ArchiveService(db)
  5015. archive = await service.get_archive(archive_id)
  5016. if not archive:
  5017. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5018. return
  5019. if archive.timelapse_path:
  5020. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5021. return
  5022. if not archive.printer_id:
  5023. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5024. return
  5025. if baseline_names is not None:
  5026. logger.info(
  5027. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5028. len(baseline_names),
  5029. archive_id,
  5030. )
  5031. elif archive.timelapse_baseline is not None:
  5032. # Persisted at print start — survives a restart mid-print.
  5033. baseline_names = set(archive.timelapse_baseline)
  5034. logger.info(
  5035. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5036. len(baseline_names),
  5037. archive_id,
  5038. )
  5039. else:
  5040. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5041. printer = result.scalar_one_or_none()
  5042. if not printer:
  5043. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5044. return
  5045. if not _timelapse_listing_is_trustworthy(printer):
  5046. # The card is unreadable at the one moment a baseline has to
  5047. # be taken, so the empty listing below means "we never
  5048. # looked", not "these are all new". Carry on with it anyway
  5049. # — the usual card holds exactly one video, which resolves
  5050. # correctly — but stop the poll from *choosing* between
  5051. # several, which is how a stale video got attached to this
  5052. # print and then deleted off the printer (#2957 follow-up).
  5053. baseline_trusted = False
  5054. logger.warning(
  5055. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5056. "handshake cool-off. A single new video still resolves; several will not be "
  5057. "guessed between — use Scan for Timelapse to pick one by hand",
  5058. archive_id,
  5059. archive.printer_id,
  5060. )
  5061. baseline_files, _ = await _list_timelapse_videos(printer)
  5062. baseline_names = {f.get("name", "") for f in baseline_files}
  5063. logger.info(
  5064. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5065. len(baseline_names),
  5066. archive_id,
  5067. )
  5068. except Exception as e:
  5069. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5070. return
  5071. # --- Phase 2: poll for a file that was not there when the print began -----
  5072. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5073. max_attempts = _timelapse_scan_max_attempts()
  5074. seen_names: set[str] = set()
  5075. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5076. attempt = 0
  5077. while True:
  5078. await asyncio.sleep(delay)
  5079. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5080. attempt += 1
  5081. try:
  5082. from backend.app.models.printer import Printer
  5083. # Read phase: fetch archive + printer in a short session and release
  5084. # the pooled connection BEFORE the FTP list/download below. Holding it
  5085. # across the FTP round-trips left one connection idle-in-transaction per
  5086. # in-flight scan (issue #2572).
  5087. async with async_session() as db:
  5088. service = ArchiveService(db)
  5089. archive = await service.get_archive(archive_id)
  5090. if not archive:
  5091. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5092. return
  5093. if archive.timelapse_path:
  5094. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5095. return
  5096. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5097. printer = result.scalar_one_or_none()
  5098. if not printer:
  5099. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5100. return
  5101. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5102. # I/O phase (no DB connection held): FTP list + download.
  5103. video_files, found_path = await _list_timelapse_videos(printer)
  5104. # The poll can run for dozens of rounds, so only narrate a round
  5105. # that saw something change. Repeating the whole listing every 30 s
  5106. # would bury the one interesting line in the support bundle.
  5107. names_now = {f.get("name", "") for f in video_files}
  5108. changed = attempt == 1 or names_now != seen_names
  5109. seen_names = names_now
  5110. speak = logger.info if changed else logger.debug
  5111. if video_files:
  5112. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5113. if changed:
  5114. for f in video_files[:5]:
  5115. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5116. attached = await _attach_first_unclaimed_timelapse(
  5117. archive_id,
  5118. printer,
  5119. video_files,
  5120. baseline_names,
  5121. claimed,
  5122. attempt,
  5123. logger,
  5124. quiet=not changed,
  5125. require_unambiguous=not baseline_trusted,
  5126. )
  5127. if attached:
  5128. return
  5129. else:
  5130. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5131. except Exception as e:
  5132. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5133. if attempt >= max_attempts or time.monotonic() >= deadline:
  5134. break
  5135. # No name-match fallback: it compared the print name against the filename,
  5136. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5137. # bundles it fired 159 times and matched zero times, so all it added was a
  5138. # misleading log line before giving up.
  5139. logger.warning(
  5140. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5141. archive_id,
  5142. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5143. )
  5144. async def _attach_first_unclaimed_timelapse(
  5145. archive_id: int,
  5146. printer,
  5147. video_files: list[dict],
  5148. baseline_names: set[str],
  5149. claimed: set[str],
  5150. attempt: int,
  5151. logger: logging.Logger,
  5152. *,
  5153. quiet: bool = False,
  5154. require_unambiguous: bool = False,
  5155. ) -> bool:
  5156. """Download and attach the one video that belongs to this print.
  5157. A candidate is any file absent from the print-start baseline. More than one
  5158. can qualify when a previous print's video landed late, after this print's
  5159. baseline was taken — those are filtered out by name, because they are
  5160. already attached to another archive. Sorting the candidates instead would
  5161. mean sorting on mtime or on the filename timestamp, both of which come from
  5162. the printer's unsynced clock.
  5163. Returns True once a video is attached. The printer's copy is deleted only
  5164. after the attach succeeds on bytes whose length matched the listing.
  5165. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5166. already seen this exact listing — the poll runs for many rounds and only the
  5167. rounds where something changed are worth an INFO line.
  5168. """
  5169. from backend.app.services.bambu_ftp import (
  5170. delete_archived_timelapse,
  5171. download_file_bytes_async,
  5172. remote_file_settled,
  5173. )
  5174. speak = logger.debug if quiet else logger.info
  5175. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5176. if not new_files:
  5177. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5178. return False
  5179. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5180. if not candidates:
  5181. speak(
  5182. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5183. attempt,
  5184. len(new_files),
  5185. )
  5186. return False
  5187. if len(candidates) > 1:
  5188. if require_unambiguous:
  5189. # The baseline is not evidence -- it was taken off a card that could
  5190. # not be read -- so "new since the baseline" does not narrow these
  5191. # down at all. Taking the first would attach an arbitrary video to
  5192. # this print and then delete it from the printer.
  5193. logger.warning(
  5194. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5195. "leaving all of them on the printer for manual selection",
  5196. attempt,
  5197. len(candidates),
  5198. ", ".join(str(f.get("name")) for f in candidates),
  5199. )
  5200. return False
  5201. logger.warning(
  5202. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5203. "the rest stay on the printer for manual selection",
  5204. attempt,
  5205. len(candidates),
  5206. ", ".join(str(f.get("name")) for f in candidates),
  5207. )
  5208. target = candidates[0]
  5209. file_name = target.get("name")
  5210. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5211. logger.info(
  5212. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5213. attempt,
  5214. file_name,
  5215. archive_id,
  5216. )
  5217. # The listing always carries a size (`list_files` skips entries it can't
  5218. # parse), but read it explicitly: the delete below is destructive and must
  5219. # depend on a size we actually had, not on one we hoped was there.
  5220. expected_size = target.get("size")
  5221. timelapse_data = await download_file_bytes_async(
  5222. printer.ip_address,
  5223. printer.access_code,
  5224. remote_path,
  5225. printer_model=printer.model,
  5226. expected_size=expected_size,
  5227. )
  5228. if not timelapse_data:
  5229. # Short or failed transfer. The printer keeps its copy, so the next
  5230. # round can try again — which is exactly why the delete below is
  5231. # gated on a verified download.
  5232. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5233. return False
  5234. # The length check above proves we got what the listing said, not that the
  5235. # printer had finished writing. A video still being written can be listed
  5236. # short, served short, and pass — so confirm it has stopped growing before
  5237. # committing to it and deleting the original (#2704).
  5238. if not await remote_file_settled(
  5239. printer.ip_address,
  5240. printer.access_code,
  5241. remote_path,
  5242. len(timelapse_data),
  5243. printer_model=printer.model,
  5244. ):
  5245. return False
  5246. # Write phase: attach in a fresh short-lived session.
  5247. async with async_session() as db:
  5248. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  5249. if not success:
  5250. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5251. return False
  5252. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5253. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5254. await delete_archived_timelapse(
  5255. printer.ip_address,
  5256. printer.access_code,
  5257. remote_path,
  5258. verified=expected_size is not None,
  5259. printer_model=printer.model,
  5260. printer_name=printer.name,
  5261. )
  5262. return True
  5263. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5264. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5265. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5266. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5267. # How long the *background* upgrade keeps waiting after the notification has
  5268. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5269. # printer can't hold up the print-complete notification; this one exists so the
  5270. # archive still ends up with the better frame afterwards.
  5271. #
  5272. # Measured across 261 attaches in the support bundles, the video lands a median
  5273. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5274. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5275. # was 546s. Every other model was inside 26s. The long budget is therefore
  5276. # almost entirely for P1-series users; on everything else the short wait already
  5277. # wins and this task never runs.
  5278. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5279. async def _capture_finish_photo_from_timelapse(
  5280. archive_id: int,
  5281. archive_dir: Path,
  5282. timeout: float | None = None,
  5283. rotation: int = 0,
  5284. ) -> tuple[str | None, bool]:
  5285. """Wait for the per-print timelapse to land on the archive and extract its
  5286. last frame as the finish photo (#1397).
  5287. Bambu firmware stops timelapse recording after the toolhead parks but
  5288. before the bed-drop end-gcode runs, so the last frame frames the finished
  5289. print correctly. A live camera grab at gcode_state=FINISH captures the
  5290. bed already lowered.
  5291. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5292. ``archive.timelapse_path`` when the file lands. This function polls for
  5293. that field.
  5294. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5295. the wait ran out with no video on the archive yet — i.e. the video may
  5296. still be coming and a later attempt could succeed. It is False when the
  5297. video landed (whether or not extraction worked), because in that case
  5298. waiting longer changes nothing. The caller uses that to decide between
  5299. falling back permanently and scheduling a background upgrade.
  5300. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5301. still (#2708) so this source agrees with every other finish-photo source.
  5302. The archived video itself is the printer's own file and is left alone —
  5303. rotating it would mean re-encoding it.
  5304. """
  5305. import uuid
  5306. from backend.app.models.archive import PrintArchive
  5307. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5308. logger = logging.getLogger(__name__)
  5309. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5310. deadline = asyncio.get_event_loop().time() + budget
  5311. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5312. while True:
  5313. async with async_session() as db:
  5314. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5315. archive = result.scalar_one_or_none()
  5316. timelapse_relpath = archive.timelapse_path if archive else None
  5317. if timelapse_relpath:
  5318. video_path = app_settings.base_dir / timelapse_relpath
  5319. if video_path.exists() and video_path.stat().st_size > 0:
  5320. photos_dir = archive_dir / "photos"
  5321. photos_dir.mkdir(parents=True, exist_ok=True)
  5322. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5323. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5324. output_path = photos_dir / filename
  5325. if await extract_video_last_frame(video_path, output_path):
  5326. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5327. logger.info(
  5328. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5329. video_path.name,
  5330. archive_id,
  5331. )
  5332. return filename, False
  5333. logger.warning(
  5334. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5335. video_path.name,
  5336. archive_id,
  5337. )
  5338. return None, False
  5339. if asyncio.get_event_loop().time() >= deadline:
  5340. logger.info(
  5341. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5342. archive_id,
  5343. budget,
  5344. )
  5345. return None, True
  5346. await asyncio.sleep(poll_interval)
  5347. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5348. """Add the timelapse's last frame to an archive after the fact (#2704).
  5349. The print-complete notification waits only ~60s for the video, because
  5350. holding a notification for minutes is worse than sending it with a live
  5351. camera grab. On a P1-series printer the video often lands well after that,
  5352. so the archive used to be stuck with the live grab — which is taken at
  5353. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5354. the worse photo of the two.
  5355. This keeps waiting in the background and, when the video arrives, extracts
  5356. the frame and puts it *first* in the archive's photo list, so opening the
  5357. gallery shows it. The live grab is deliberately kept: the notification that
  5358. already went out links to that exact file, and deleting it would leave a
  5359. broken image in Discord or Telegram.
  5360. """
  5361. logger = logging.getLogger(__name__)
  5362. filename, _ = await _capture_finish_photo_from_timelapse(
  5363. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5364. )
  5365. if not filename:
  5366. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5367. return
  5368. try:
  5369. async with async_session() as db:
  5370. from backend.app.models.archive import PrintArchive
  5371. archive = await db.get(PrintArchive, archive_id)
  5372. if archive is None:
  5373. return
  5374. photos = list(archive.photos or [])
  5375. if filename in photos:
  5376. return
  5377. # Front of the list: PhotoGalleryModal opens at index 0.
  5378. archive.photos = [filename, *photos]
  5379. await db.commit()
  5380. except Exception as e:
  5381. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5382. return
  5383. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5384. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5385. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5386. """Put the filament-attribution context back after a restart mid-print.
  5387. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5388. both die with the process. The print keeps running, so at completion the
  5389. tracker would fall back to whatever the printer reports *now* — and AMS
  5390. filament backup makes "now" the substitute tray, charging the whole print
  5391. to the spool that only finished it.
  5392. The persisted row is only trusted when its print name still matches what
  5393. the printer says it is running: a row left behind by a completion we never
  5394. saw must not attach itself to the next print.
  5395. """
  5396. try:
  5397. from backend.app.api.routes.settings import get_setting
  5398. from backend.app.services.usage_tracker import (
  5399. clear_persisted_session,
  5400. get_persisted_print_name,
  5401. restore_session,
  5402. )
  5403. persisted_name = await get_persisted_print_name(db, printer_id)
  5404. current_name = (state.subtask_name or "").strip()
  5405. if persisted_name and current_name and persisted_name.strip() != current_name:
  5406. logger.info(
  5407. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5408. printer_id,
  5409. persisted_name,
  5410. current_name,
  5411. )
  5412. await clear_persisted_session(db, printer_id)
  5413. # Fall through to seeding: the print on the printer is real, it just
  5414. # isn't the one the row described.
  5415. persisted_log = None
  5416. else:
  5417. # Spoolman users get the tray-change log back but no in-memory
  5418. # session — see ``on_print_start`` on why that dict is load-bearing
  5419. # for the remain%-sync guard.
  5420. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5421. persisted_log = await restore_session(
  5422. db,
  5423. printer_id,
  5424. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5425. )
  5426. if persisted_log:
  5427. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5428. # Anything this process already observed goes after the persisted
  5429. # history — the log is ordered by layer, and a fresh process can
  5430. # only have seen changes from later in the print.
  5431. for entry in state.tray_change_log or []:
  5432. if tuple(entry) not in restored:
  5433. restored.append(tuple(entry))
  5434. state.tray_change_log = restored
  5435. tray_now = state.tray_now
  5436. if 0 <= tray_now <= 254:
  5437. if not state.tray_change_log:
  5438. # No persisted history — a print that started before this build,
  5439. # or before the row existed. Seed with the tray feeding right
  5440. # now so the remainder of the print is at least attributable to
  5441. # the right spool.
  5442. state.tray_change_log = [(tray_now, state.layer_num)]
  5443. logger.info(
  5444. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5445. printer_id,
  5446. tray_now,
  5447. state.layer_num,
  5448. )
  5449. # The tray handler updates ``last_loaded_tray`` on every push
  5450. # regardless of whether it logged a change, so re-align it to avoid
  5451. # a duplicate entry on the next push. Only ever with a real tray:
  5452. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5453. # 255" fallback, and writing 255 into it would defeat that.
  5454. state.last_loaded_tray = tray_now
  5455. except Exception:
  5456. # Never let attribution recovery cost the caller its timelapse
  5457. # baseline — that capture has to happen before the printer uploads
  5458. # the in-flight MP4 and there is no second chance at it.
  5459. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5460. async def on_print_running_observed(printer_id: int, data: dict):
  5461. """Restart-recovery for a print that started before Bambuddy came up.
  5462. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5463. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5464. creation). This hook restores the persisted archive into ``_active_prints``
  5465. and captures the timelapse baseline that normally hangs off print start.
  5466. Fires once per session, in lieu of on_print_start when restart-recovery
  5467. kicks in. The printer doesn't upload the timelapse until after PRINT
  5468. COMPLETE, so a baseline captured any time during the print is still
  5469. pre-upload.
  5470. """
  5471. logger = logging.getLogger(__name__)
  5472. async with async_session() as db:
  5473. from backend.app.models.printer import Printer
  5474. state = printer_manager.get_status(printer_id)
  5475. if state is not None:
  5476. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5477. if authorization is True:
  5478. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5479. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5480. await _restore_printable_objects(printer_id, state, db, logger)
  5481. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5482. printer = result.scalar_one_or_none()
  5483. if not printer:
  5484. logger.warning(
  5485. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5486. printer_id,
  5487. )
  5488. return
  5489. # Avoid double-capture: ownership reconciliation above must still run when
  5490. # a baseline already exists, but the camera work itself is one-shot.
  5491. if printer_id in _timelapse_baselines:
  5492. logger.debug(
  5493. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5494. printer_id,
  5495. )
  5496. return
  5497. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5498. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5499. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5500. against the printer's current MQTT state.
  5501. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5502. COMPLETE events, typically a print finishing during an MQTT disconnect
  5503. window followed by a smart-plug power cycle):
  5504. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5505. provably not running anymore — only branch that should fire under
  5506. normal disconnect-then-reconnect timing.
  5507. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5508. firmware mints a fresh ``subtask_id`` for each print, including the
  5509. ghost replay it runs after a power cycle from a leftover SD file —
  5510. so a mismatch unambiguously means the in-DB archive is no longer
  5511. the print on the printer.
  5512. 3. Printer is running but ``subtask_name`` is empty. The printer
  5513. doesn't know what it's running; the archive's reference to it is
  5514. already broken.
  5515. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5516. with matching subtask_id+subtask_name is left alone. The cost of a false
  5517. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5518. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5519. clears on synthesis, so the real completion creates a fresh row instead
  5520. of overwriting the synthesised one (#1679). The cost of a false negative
  5521. is the ghost-print loop in #1542.
  5522. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5523. MQTT has connected but the first ``push_status`` response hasn't been
  5524. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5525. The reconcile caller in ``on_printer_status_change`` is already gated
  5526. on a real ``state.state``, so in normal operation this branch is
  5527. unreachable; it's kept as belt-and-braces for future callers and for
  5528. the narrow window where a partial state update could arrive
  5529. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5530. ``not stale`` on degenerate input is strictly conservative: a real
  5531. stale archive will still be caught by the next push_status arriving
  5532. with terminal state.
  5533. """
  5534. current_state = (state.state or "").upper()
  5535. if current_state in ("", "UNKNOWN"):
  5536. # No real push_status yet — PrinterState defaults are not evidence.
  5537. return False, ""
  5538. if current_state in ("IDLE", "FINISH", "FAILED"):
  5539. return True, f"printer state {current_state}"
  5540. # Below here the printer is in a running / pre-running state (RUNNING /
  5541. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5542. current_subtask_id = (state.subtask_id or "").strip()
  5543. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5544. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5545. current_subtask_name = (state.subtask_name or "").strip()
  5546. if not current_subtask_name:
  5547. return True, "printer subtask_name empty"
  5548. return False, ""
  5549. async def prime_kprofile_table(printer_id: int) -> int:
  5550. """Read the printer's calibration table once per connection.
  5551. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5552. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5553. report ``cali_idx`` and nothing else -- that number can only come from
  5554. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5555. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5556. backup, or the printer answering a query BambuStudio made on the report
  5557. topic we share. A Bambuddy that nobody visited showed a card with no K
  5558. values at all.
  5559. Only the diameters actually fitted are asked for, which is one request on a
  5560. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5561. what the backup does, and it is both wasteful and the thing that used to
  5562. blank the table.
  5563. Returns the number of nozzles whose table was read.
  5564. """
  5565. client = printer_manager.get_client(printer_id)
  5566. state = printer_manager.get_status(printer_id)
  5567. if client is None or state is None or not state.connected:
  5568. return 0
  5569. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5570. # ask once, and both entries are empty until the first push_status lands.
  5571. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5572. if not diameters:
  5573. logging.getLogger(__name__).debug(
  5574. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5575. printer_id,
  5576. )
  5577. return 0
  5578. primed = 0
  5579. for diameter in diameters:
  5580. try:
  5581. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5582. except Exception as exc: # noqa: BLE001
  5583. # A printer that won't answer costs the card its K values, nothing
  5584. # more — never the connection this runs on the back of.
  5585. logging.getLogger(__name__).warning(
  5586. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5587. )
  5588. continue
  5589. primed += 1
  5590. logging.getLogger(__name__).info(
  5591. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5592. )
  5593. return primed
  5594. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5595. """Synthesise ``on_print_complete`` for archives whose print can't be
  5596. running on the printer anymore.
  5597. Called once per MQTT (re)connection (from on_printer_status_change when
  5598. the connected edge flips False → True) and at Bambuddy startup (from
  5599. the FastAPI lifespan). Without this, a print that completes during a
  5600. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5601. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5602. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5603. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5604. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5605. closes the loop by faking the missed PRINT COMPLETE — the existing
  5606. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5607. and notifications.
  5608. Synthesised ``status="aborted"`` is the conservative label: we have no
  5609. proof the print finished successfully (and no progress evidence to
  5610. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5611. fires later, overwrites the status with the correct value.
  5612. Returns the number of archives reconciled.
  5613. """
  5614. state = printer_manager.get_status(printer_id)
  5615. if not state:
  5616. return 0
  5617. # Don't reconcile while disconnected — we'd be making a decision against
  5618. # stale cached state. The connected → reconcile edge handles this.
  5619. if not state.connected:
  5620. return 0
  5621. from backend.app.models.archive import PrintArchive
  5622. reconciled = 0
  5623. async with async_session() as db:
  5624. result = await db.execute(
  5625. select(PrintArchive).where(
  5626. PrintArchive.printer_id == printer_id,
  5627. PrintArchive.status == "printing",
  5628. )
  5629. )
  5630. active = list(result.scalars().all())
  5631. if not active:
  5632. return 0
  5633. logger = logging.getLogger(__name__)
  5634. for archive in active:
  5635. is_stale, reason = _is_active_archive_stale(archive, state)
  5636. if not is_stale:
  5637. continue
  5638. logger.info(
  5639. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5640. printer_id,
  5641. archive.id,
  5642. archive.filename,
  5643. reason,
  5644. )
  5645. # Synthesised payload: minimal fields the on_print_complete chain
  5646. # needs. `_reconciled` marker lets downstream code distinguish this
  5647. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5648. # metrics / debug logging). raw_data is the live printer state so
  5649. # the usage tracker can compare end-of-print remain% against the
  5650. # captured start values.
  5651. try:
  5652. await on_print_complete(
  5653. printer_id,
  5654. {
  5655. "status": "aborted",
  5656. "filename": archive.filename,
  5657. "subtask_name": archive.print_name or "",
  5658. "subtask_id": archive.subtask_id or "",
  5659. "raw_data": state.raw_data or {},
  5660. "_reconciled": True,
  5661. },
  5662. )
  5663. reconciled += 1
  5664. except Exception as e:
  5665. # Catch-all: a reconciliation failure must not block the
  5666. # printer's normal status flow. The archive stays in
  5667. # ``status="printing"`` and the next reconnect retries.
  5668. logger.warning(
  5669. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5670. archive.id,
  5671. e,
  5672. )
  5673. return reconciled
  5674. # #2547: clearance left between the nozzle and the top of the print when the
  5675. # plate is commanded back into camera framing. The nozzle is parked away from
  5676. # the part by then, so this is belt-and-braces against a max_z_height that
  5677. # under-reports (e.g. a slicer that excludes a final Z hop).
  5678. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5679. # How far below the restored position to drop the plate again afterwards, so
  5680. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5681. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5682. # on machines with less headroom.
  5683. _PLATE_PARK_DROP_MM = 100.0
  5684. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5685. # this axis, so it is a proven-safe speed for the full travel.
  5686. _PLATE_RESTORE_FEEDRATE = 600
  5687. # Time allowed for the plate to reach the restored position before the camera
  5688. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5689. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5690. # How long `_background_finish_photo` waits for this producer. Must cover the
  5691. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5692. # notification path's own photo wait so a slow producer degrades to a
  5693. # photo-less notification rather than a missed one.
  5694. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5695. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  5696. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5697. This number becomes the target of a real Z move, so every step here refuses
  5698. rather than guesses. A height belonging to some *other* print is the one
  5699. failure that could drive the nozzle into the model: 20 mm carried onto a
  5700. 200 mm print would command the plate up through the part.
  5701. Two independent things therefore have to agree before a height is returned:
  5702. 1. **Identity.** The archive is matched by the finished print's own
  5703. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  5704. resolve to "Cube v2". Matching on "most recent archive for this printer"
  5705. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  5706. binding concurrently with us, and a print Bambuddy failed to archive
  5707. would silently resolve to its predecessor.
  5708. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5709. match the layer count the printer itself reported over MQTT for the print
  5710. that just ended. These come from genuinely different sources, so a
  5711. mismatch means the row is not this print, whatever its name says.
  5712. ``completed`` is accepted alongside ``printing`` only because
  5713. ``on_print_complete`` may already have flipped the status by the time we
  5714. run; the identity check above is what actually selects the row.
  5715. """
  5716. subtask_name = (data.get("subtask_name") or "").strip()
  5717. if not subtask_name:
  5718. # Nothing to identify the print by — refuse rather than fall back to
  5719. # "whatever ran last on this printer".
  5720. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5721. return None
  5722. try:
  5723. from backend.app.models.archive import PrintArchive
  5724. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5725. async with async_session() as db:
  5726. result = await db.execute(
  5727. select(PrintArchive)
  5728. .where(
  5729. PrintArchive.printer_id == printer_id,
  5730. PrintArchive.status.in_(("printing", "completed")),
  5731. PrintArchive.deleted_at.is_(None),
  5732. or_(
  5733. PrintArchive.print_name == subtask_name,
  5734. PrintArchive.filename == subtask_name,
  5735. PrintArchive.filename == f"{subtask_name}.3mf",
  5736. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  5737. ),
  5738. )
  5739. .order_by(PrintArchive.id.desc())
  5740. .limit(1)
  5741. )
  5742. archive = result.scalar_one_or_none()
  5743. if archive is None or not archive.file_path:
  5744. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  5745. return None
  5746. client = printer_manager.get_client(printer_id)
  5747. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  5748. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  5749. logger.warning(
  5750. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  5751. "— refusing to move the plate on a height that may not be this print's",
  5752. printer_id,
  5753. archive.id,
  5754. archive.total_layers,
  5755. reported_layers,
  5756. )
  5757. return None
  5758. path = Path(archive.file_path)
  5759. if not path.is_absolute():
  5760. path = Path(app_settings.data_dir) / path
  5761. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  5762. except Exception as e:
  5763. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  5764. return None
  5765. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  5766. """Raise the plate back into camera framing before the finish photo (#2547).
  5767. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  5768. the time ``gcode_state`` reaches FINISH the finished print sits far below
  5769. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  5770. This commands an absolute ``G1 Z`` back to just above the last printed
  5771. layer.
  5772. Absolute, not relative, is the whole safety argument. ``max_z_height +
  5773. clearance`` is a height the toolhead was physically at seconds earlier, so
  5774. it is inside the travel limits by construction and leaves the nozzle above
  5775. the part. It is also unambiguous across model families: Z is the
  5776. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  5777. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  5778. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  5779. (#2579).
  5780. Returns True if the move was sent and waited out, False if it was skipped.
  5781. """
  5782. client = printer_manager.get_client(printer_id)
  5783. if client is None:
  5784. return False
  5785. # Re-read state immediately before commanding motion. If the queue has
  5786. # already started the next print, the printer is no longer ours to move.
  5787. state = getattr(client, "state", None)
  5788. if state is None or state.state != "FINISH":
  5789. logger.info(
  5790. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  5791. printer_id,
  5792. getattr(state, "state", "unknown"),
  5793. )
  5794. return False
  5795. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  5796. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  5797. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  5798. return False
  5799. logger.info(
  5800. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  5801. printer_id,
  5802. target_z,
  5803. max_z_height,
  5804. _PLATE_RESTORE_CLEARANCE_MM,
  5805. _PLATE_RESTORE_SETTLE_SECONDS,
  5806. )
  5807. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  5808. return True
  5809. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  5810. """Drop the plate again after the finish photo (#2547).
  5811. Without this the user walks up to a finished print sitting just under the
  5812. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  5813. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  5814. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  5815. print homes anyway.
  5816. """
  5817. client = printer_manager.get_client(printer_id)
  5818. state = getattr(client, "state", None) if client else None
  5819. if client is None or state is None or state.state != "FINISH":
  5820. return
  5821. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  5822. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  5823. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  5824. """True if a queue item is about to take this printer (#2547).
  5825. The scheduler dispatches the next job the moment a print completes, and a
  5826. plate move interleaved with a print start is not a race worth having. The
  5827. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  5828. this window; this closes the head of it.
  5829. """
  5830. try:
  5831. from backend.app.models.print_queue import PrintQueueItem
  5832. async with async_session() as db:
  5833. result = await db.execute(
  5834. select(PrintQueueItem.id)
  5835. .where(
  5836. PrintQueueItem.printer_id == printer_id,
  5837. PrintQueueItem.status.in_(("pending", "printing")),
  5838. )
  5839. .limit(1)
  5840. )
  5841. return result.scalar_one_or_none() is not None
  5842. except Exception as e:
  5843. # Fail closed: if we can't tell, don't move the plate.
  5844. logging.getLogger(__name__).debug(
  5845. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  5846. )
  5847. return True
  5848. async def on_finish_photo_moment(printer_id: int, data: dict):
  5849. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  5850. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  5851. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  5852. fallback for prints that skip stage 22 (cancel, external-spool-only,
  5853. HMS halt, firmware variants). Grabs one frame via the same
  5854. external-camera / RTSP path the post-completion fallback uses, stores
  5855. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  5856. ``_background_finish_photo`` consume the cached bytes when it runs.
  5857. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  5858. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  5859. set to Smooth (#1721). No force-on now means the user's explicit
  5860. timelapse=off in the slicer send dialog is respected.
  5861. """
  5862. logger = logging.getLogger(__name__)
  5863. trigger = data.get("trigger", "unknown")
  5864. timelapse_was_active = bool(data.get("timelapse_was_active"))
  5865. logger.info(
  5866. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  5867. printer_id,
  5868. trigger,
  5869. timelapse_was_active,
  5870. )
  5871. # If a timelapse is actively recording, skip the pre-capture — the
  5872. # post-completion path will extract the last frame from the recorded
  5873. # video, which still provides the best framing (toolhead parked,
  5874. # before bed drop) without the per-layer parking side effects.
  5875. if timelapse_was_active:
  5876. logger.info(
  5877. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  5878. printer_id,
  5879. )
  5880. return
  5881. # #1790: register the producer-done event BEFORE the first await so the
  5882. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  5883. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  5884. # The `finally` below guarantees `set()` runs on every exit, including
  5885. # early returns and exceptions, so the consumer's bounded wait can't hang.
  5886. producer_done = asyncio.Event()
  5887. _stage22_finish_in_flight[printer_id] = producer_done
  5888. # #2547: set once the plate has actually been raised, and read by the
  5889. # `finally` below. Declared out here so a failure anywhere after the move —
  5890. # a camera timeout, a DB error — still lowers the plate again.
  5891. restore_max_z: float | None = None
  5892. try:
  5893. async with async_session() as db:
  5894. from backend.app.api.routes.settings import get_setting
  5895. from backend.app.models.printer import Printer
  5896. capture_setting = await get_setting(db, "capture_finish_photo")
  5897. if capture_setting is not None and capture_setting.lower() != "true":
  5898. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  5899. return
  5900. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  5901. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  5902. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5903. printer = result.scalar_one_or_none()
  5904. if printer is None:
  5905. logger.warning(
  5906. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  5907. printer_id,
  5908. )
  5909. return
  5910. frame_bytes: bytes | None = None
  5911. # #2708: the banked frame arrives already rotated — it comes from
  5912. # `_capture_snapshot_for_notification`, which rotates before returning.
  5913. # Every other source below is a raw grab. Tracking which lets us store
  5914. # exactly one rotation in `_stage22_finish_frames` either way.
  5915. frame_already_rotated = False
  5916. # On the FINISH-state path the End G-code has already run, and two very
  5917. # different situations arrive here needing opposite answers.
  5918. #
  5919. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  5920. # snippet may have ejected the plate — the scene in front of the camera
  5921. # is no longer the finished print, and no amount of moving the plate
  5922. # brings it back. Use the banked in-print frame instead.
  5923. #
  5924. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  5925. # than the camera frames well, and the toolhead is parked out of the
  5926. # way. That is the *best* moment available on firmware that never emits
  5927. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  5928. # back. Preferring the bank here unconditionally, as this code used to,
  5929. # is what shipped a mid-print photo with the toolhead over the part.
  5930. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  5931. banked = _inprint_frame_bank.get(printer_id)
  5932. if banked:
  5933. frame_bytes = banked
  5934. frame_already_rotated = True
  5935. logger.info(
  5936. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  5937. "frame (%d bytes) instead of a post-swap live grab",
  5938. len(banked),
  5939. )
  5940. else:
  5941. logger.warning(
  5942. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  5943. "in-print bank is empty — falling back to a live grab, which may show a "
  5944. "swapped or empty plate",
  5945. printer_id,
  5946. )
  5947. # `restore_max_z` is set only once the plate is actually up, because the
  5948. # `finally` reads it to decide whether it owes a move back down.
  5949. #
  5950. # Never on a print whose End G-code Bambuddy injected, even when the bank
  5951. # came up empty above: that machine may have just ejected its plate, and
  5952. # driving Z into whatever a swap mechanism is doing is not a risk worth
  5953. # taking for a photo of a bed we already know may be bare.
  5954. if (
  5955. frame_bytes is None
  5956. and trigger == "finish_state"
  5957. and restore_plate_enabled
  5958. and not print_dispatch_context.end_gcode_injected(printer_id)
  5959. ):
  5960. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  5961. if wants_restore is None:
  5962. logger.info(
  5963. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  5964. printer_id,
  5965. )
  5966. elif await _plate_restore_is_blocked_by_queue(printer_id):
  5967. logger.info(
  5968. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  5969. printer_id,
  5970. )
  5971. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  5972. restore_max_z = wants_restore
  5973. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  5974. from backend.app.api.routes.camera import live_frame_for_capture
  5975. from backend.app.services.external_camera import capture_frame
  5976. # #2707: this used to collide with the live view and fail, which is
  5977. # how finish-photo notifications went out with no image attached.
  5978. # Leaving frame_bytes None keeps the rest of the fallback chain.
  5979. defer, buffered = live_frame_for_capture(printer_id)
  5980. if defer:
  5981. frame_bytes = buffered
  5982. else:
  5983. frame_bytes = await capture_frame(
  5984. printer.external_camera_url,
  5985. printer.external_camera_type or "mjpeg",
  5986. snapshot_url=printer.external_camera_snapshot_url,
  5987. )
  5988. if frame_bytes:
  5989. logger.info(
  5990. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  5991. len(frame_bytes),
  5992. )
  5993. elif frame_bytes is None:
  5994. from backend.app.api.routes.camera import get_buffered_frame
  5995. buffered = get_buffered_frame(printer_id)
  5996. if buffered:
  5997. frame_bytes = buffered
  5998. logger.info(
  5999. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6000. len(frame_bytes),
  6001. )
  6002. else:
  6003. from backend.app.services.camera import capture_camera_frame_bytes
  6004. frame_bytes = await capture_camera_frame_bytes(
  6005. ip_address=printer.ip_address,
  6006. access_code=printer.access_code,
  6007. model=printer.model,
  6008. timeout=15,
  6009. )
  6010. if frame_bytes:
  6011. logger.info(
  6012. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6013. len(frame_bytes),
  6014. )
  6015. if frame_bytes:
  6016. if not frame_already_rotated:
  6017. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6018. _stage22_finish_frames[printer_id] = frame_bytes
  6019. else:
  6020. logger.warning(
  6021. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6022. printer_id,
  6023. )
  6024. except Exception as e:
  6025. logger.warning(
  6026. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6027. printer_id,
  6028. e,
  6029. )
  6030. finally:
  6031. # #2547: we raised the plate, so we own lowering it — including when the
  6032. # capture above failed or threw partway through.
  6033. if restore_max_z is not None:
  6034. try:
  6035. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6036. except Exception as e:
  6037. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6038. # #1790: always unblock the consumer's bounded wait — whether we stored
  6039. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6040. # dict entry by the consumer doesn't affect signalling.
  6041. producer_done.set()
  6042. def _subtask_name_from_filename(filename: str) -> str:
  6043. """Recover the subtask name a print command would have carried for *filename*.
  6044. The dispatcher derives the printer-facing subtask name from the archive's
  6045. file name, so stripping the extensions back off gives the value MQTT echoes
  6046. on completion. Only the two extensions Bambuddy actually stores are removed,
  6047. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6048. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6049. """
  6050. name = PurePosixPath(filename).name
  6051. for suffix in (".3mf", ".gcode"):
  6052. if name.lower().endswith(suffix):
  6053. name = name[: -len(suffix)]
  6054. return name
  6055. # How the printer marks a subtask name it had to cut short. Observed on real
  6056. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6057. # (a name with multibyte characters came back at 98), so match the marker
  6058. # rather than a length.
  6059. _SUBTASK_TRUNCATION_MARKER = "..."
  6060. def _normalise_subtask_name(name: str) -> str:
  6061. """Canonical form for comparing a dispatched name against MQTT's echo.
  6062. The printer does not echo the name back verbatim: it substitutes
  6063. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6064. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6065. The 3MF lookup in this module has always known that -- it builds
  6066. space-to-underscore variants of every candidate filename, and its
  6067. directory search normalises both sides before comparing. This exists so
  6068. the completion check reads the same rule from the same place instead of
  6069. growing its own, which is exactly how it came to disagree (#2829).
  6070. """
  6071. return name.strip().replace(" ", "_").casefold()
  6072. def _subtask_names_match(expected: str, observed: str) -> bool:
  6073. """Whether two subtask names describe the same print.
  6074. Beyond the space/underscore substitution, the printer truncates long names
  6075. and marks the cut with ``...``. A truncated echo has to count as a match or
  6076. every print with a long name strands its queue item the same way.
  6077. """
  6078. expected_n = _normalise_subtask_name(expected)
  6079. observed_n = _normalise_subtask_name(observed)
  6080. if expected_n == observed_n:
  6081. return True
  6082. # Either side can be the truncated one: the printer truncates what it
  6083. # echoes, and an archive whose own filename was recorded from a previous
  6084. # truncated echo carries the marker too.
  6085. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6086. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  6087. return True
  6088. return False
  6089. async def _queue_item_dispatched_name(db, item) -> str:
  6090. """The subtask name *item* was dispatched under, or "" when unknowable.
  6091. A row with no archive, or an archive with no file name, is unverifiable
  6092. rather than wrong; every caller answers that with its permissive branch.
  6093. """
  6094. if item.archive_id is None:
  6095. return ""
  6096. from backend.app.models.archive import PrintArchive
  6097. archive = await db.get(PrintArchive, item.archive_id)
  6098. if archive is None or not archive.filename:
  6099. return ""
  6100. return _subtask_name_from_filename(archive.filename)
  6101. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6102. """Whether this completion event is plausibly about *item*'s print.
  6103. The caller finds its queue row by printer and ``status='printing'`` alone,
  6104. which is all a completion event gives it -- there is no run identifier in
  6105. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6106. completion delivered for this printer closes whichever row happens to be
  6107. printing, however unrelated. Comparing the subtask name against the archive
  6108. the row was dispatched with costs one primary-key load and rules that out.
  6109. Deliberately permissive: it answers False only on a positive disagreement
  6110. between two names we actually have. A row with no archive, an archive with
  6111. no file name, or an event with no subtask name is unverifiable rather than
  6112. wrong, and refusing those would strand the item in ``printing`` and wedge
  6113. the printer's queue -- a worse failure than the one being prevented.
  6114. """
  6115. observed = (data.get("subtask_name") or "").strip()
  6116. if not observed or item.archive_id is None:
  6117. return True
  6118. from backend.app.models.archive import PrintArchive
  6119. archive = await db.get(PrintArchive, item.archive_id)
  6120. if archive is None or not archive.filename:
  6121. return True
  6122. expected = _subtask_name_from_filename(archive.filename)
  6123. if not expected or _subtask_names_match(expected, observed):
  6124. return True
  6125. logging.getLogger(__name__).warning(
  6126. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6127. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6128. "printing rather than closing a run this event is not about.",
  6129. item.id,
  6130. expected,
  6131. archive.id,
  6132. archive.filename,
  6133. observed,
  6134. )
  6135. return False
  6136. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6137. """Spend the 3MF download cache on a still-empty fallback archive.
  6138. ``on_print_complete`` drops the cache as its first act, which deletes the
  6139. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6140. print ran and the archive never got one, this is the last moment those bytes
  6141. exist (#2957).
  6142. """
  6143. logger = logging.getLogger(__name__)
  6144. names = [
  6145. n
  6146. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6147. if n
  6148. ]
  6149. for name in names:
  6150. try:
  6151. cached = get_cached_3mf(printer_id, name)
  6152. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6153. return
  6154. except Exception as e:
  6155. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6156. async def on_print_complete(printer_id: int, data: dict):
  6157. """Handle print completion - update the archive status."""
  6158. import time
  6159. logger = logging.getLogger(__name__)
  6160. start_time = time.time()
  6161. def log_timing(section: str):
  6162. elapsed = time.time() - start_time
  6163. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6164. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6165. # A kill-switch stop sends its provider notification immediately. Keep the
  6166. # task so the later notification path can await it and avoid a duplicate;
  6167. # if that immediate attempt failed, the regular completion path retries.
  6168. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6169. # Last chance before the bytes go: if this print's archive is still an empty
  6170. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6171. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6172. # below deletes the file (#2957).
  6173. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6174. # A pending cool-off retry has nothing left to recover for — the cache is
  6175. # about to be dropped and the print is over.
  6176. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6177. if retry_task and not retry_task.done():
  6178. retry_task.cancel()
  6179. # Drop the 3MF download cache for this printer (#972). The print is over,
  6180. # nothing else legitimately needs the bytes; keeping them would only risk
  6181. # handing a stale file to the next print if it reuses the same name.
  6182. clear_3mf_cache(printer_id)
  6183. try:
  6184. ws_data = {
  6185. "status": data.get("status"),
  6186. "filename": data.get("filename"),
  6187. "subtask_name": data.get("subtask_name"),
  6188. "timelapse_was_active": data.get("timelapse_was_active"),
  6189. }
  6190. await ws_manager.send_print_complete(printer_id, ws_data)
  6191. log_timing("WebSocket send_print_complete")
  6192. except Exception as e:
  6193. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6194. # Capture user info before clearing (needed for print log entry)
  6195. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6196. # Clear current print user tracking (Issue #206)
  6197. printer_manager.clear_current_print_user(printer_id)
  6198. # If the user explicitly stopped this print from the queue UI the printer will
  6199. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6200. # correct "print stopped" notification/email is sent instead of a failure alert.
  6201. _raw_status = data.get("status", "completed")
  6202. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6203. logger.info(
  6204. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6205. _raw_status,
  6206. printer_id,
  6207. )
  6208. data = {**data, "status": "cancelled"}
  6209. _user_stopped_printers.discard(printer_id)
  6210. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6211. # may have left material on the bed: a user can cancel ten hours into a
  6212. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6213. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6214. # `_user_stopped_printers` is only populated when the user stops via the
  6215. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6216. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6217. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6218. # Auto Off power cycles and Bambuddy restarts.
  6219. _final_status = data.get("status", "completed")
  6220. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6221. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6222. # MQTT relay - publish print complete
  6223. try:
  6224. printer_info = printer_manager.get_printer(printer_id)
  6225. if printer_info:
  6226. await mqtt_relay.on_print_complete(
  6227. printer_id,
  6228. printer_info.name,
  6229. printer_info.serial_number,
  6230. data.get("filename", ""),
  6231. data.get("subtask_name", ""),
  6232. data.get("status", "completed"),
  6233. )
  6234. except Exception:
  6235. pass # Don't fail print complete callback if MQTT fails
  6236. filename = data.get("filename", "")
  6237. subtask_name = data.get("subtask_name", "")
  6238. if not filename and not subtask_name:
  6239. logger.warning("Print complete without filename or subtask_name")
  6240. return
  6241. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6242. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6243. possible_keys = []
  6244. # Try subtask_name variations first (most reliable for matching)
  6245. if subtask_name:
  6246. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6247. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6248. possible_keys.append((printer_id, subtask_name))
  6249. # Try filename variations
  6250. if filename:
  6251. # Extract just the filename if it's a path
  6252. fname = filename.split("/")[-1] if "/" in filename else filename
  6253. if fname.endswith(".3mf"):
  6254. possible_keys.append((printer_id, fname))
  6255. elif fname.endswith(".gcode"):
  6256. base_name = fname.rsplit(".", 1)[0]
  6257. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6258. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6259. possible_keys.append((printer_id, fname))
  6260. else:
  6261. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6262. possible_keys.append((printer_id, f"{fname}.3mf"))
  6263. possible_keys.append((printer_id, fname))
  6264. # Also try full path versions
  6265. if filename.endswith(".3mf"):
  6266. possible_keys.append((printer_id, filename))
  6267. elif filename.endswith(".gcode"):
  6268. base_name = filename.rsplit(".", 1)[0]
  6269. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6270. possible_keys.append((printer_id, filename))
  6271. else:
  6272. possible_keys.append((printer_id, f"{filename}.3mf"))
  6273. possible_keys.append((printer_id, filename))
  6274. # Find the archive for this print
  6275. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6276. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6277. archive_id = None
  6278. for key in possible_keys:
  6279. archive_id = _active_prints.pop(key, None)
  6280. if archive_id:
  6281. logger.info("Found archive %s with key %s", archive_id, key)
  6282. # Also clean up any other keys pointing to this archive
  6283. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6284. for k in keys_to_remove:
  6285. _active_prints.pop(k, None)
  6286. break
  6287. if not archive_id:
  6288. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6289. async with async_session() as db:
  6290. from backend.app.models.archive import PrintArchive
  6291. # Try matching by subtask_name (stored as print_name) first
  6292. if subtask_name:
  6293. result = await db.execute(
  6294. select(PrintArchive)
  6295. .where(PrintArchive.printer_id == printer_id)
  6296. .where(PrintArchive.status == "printing")
  6297. .where(
  6298. or_(
  6299. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6300. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6301. )
  6302. )
  6303. .order_by(PrintArchive.created_at.desc())
  6304. .limit(1)
  6305. )
  6306. archive = result.scalar_one_or_none()
  6307. if archive:
  6308. archive_id = archive.id
  6309. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6310. # Also try by filename
  6311. if not archive_id and filename:
  6312. result = await db.execute(
  6313. select(PrintArchive)
  6314. .where(PrintArchive.printer_id == printer_id)
  6315. .where(PrintArchive.filename == filename)
  6316. .where(PrintArchive.status == "printing")
  6317. .order_by(PrintArchive.created_at.desc())
  6318. .limit(1)
  6319. )
  6320. archive = result.scalar_one_or_none()
  6321. if archive:
  6322. archive_id = archive.id
  6323. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6324. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6325. # auto-start files found in root on power cycle, causing ghost prints.
  6326. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6327. try:
  6328. if subtask_name:
  6329. archive_filename: str | None = None
  6330. async with async_session() as db:
  6331. from backend.app.models.archive import PrintArchive
  6332. from backend.app.models.printer import Printer
  6333. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6334. printer = result.scalar_one_or_none()
  6335. if archive_id:
  6336. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6337. archive_filename = archive_row.scalar_one_or_none()
  6338. if printer:
  6339. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6340. from backend.app.utils.filename import derive_remote_filename
  6341. # Primary candidate: the exact path the dispatcher uploaded to
  6342. # (derived from archive.filename via the same rule as upload).
  6343. # Without it, a library row that ended up with a doubled
  6344. # .gcode.3mf (#1542) leaves the real file behind because the
  6345. # subtask_name + ext fallbacks below don't match what's on the
  6346. # SD card. Fallbacks remain for archive-less prints (subtask
  6347. # never resolved to an archive) and for older naming variants.
  6348. candidate_paths: list[str] = []
  6349. if archive_filename:
  6350. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6351. for ext in (".3mf", ".gcode"):
  6352. fallback = f"/{subtask_name}{ext}"
  6353. if fallback not in candidate_paths:
  6354. candidate_paths.append(fallback)
  6355. # Three outcomes track across all candidates so the final log
  6356. # line reflects what actually happened. The A1 in #1721 always
  6357. # ends here with ``any_not_found=True`` and the others False
  6358. # — its firmware auto-cleans the SD card before our cleanup
  6359. # runs, every candidate FTP-DELE returns 550, and the old
  6360. # code burned 3 retries × 2 s × 3 candidates per print
  6361. # logging a misleading "may linger" WARNING on a successful
  6362. # print.
  6363. any_deleted = False
  6364. any_real_failure = False
  6365. any_not_found = False
  6366. for remote_path in candidate_paths:
  6367. # Retry only the FAILED case — 550 NOT_FOUND will never
  6368. # recover by waiting, so a "file isn't here" answer
  6369. # advances immediately to the next candidate without
  6370. # consuming the retry budget.
  6371. for attempt in range(1, 4):
  6372. try:
  6373. delete_result = await delete_file_async(
  6374. printer.ip_address,
  6375. printer.access_code,
  6376. remote_path,
  6377. printer_model=printer.model,
  6378. )
  6379. except Exception as e:
  6380. delete_result = DeleteResult.FAILED
  6381. logger.warning(
  6382. "SD card cleanup attempt %d/3 raised for %s: %s",
  6383. attempt,
  6384. remote_path,
  6385. e,
  6386. )
  6387. if delete_result == DeleteResult.DELETED:
  6388. any_deleted = True
  6389. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6390. break
  6391. if delete_result == DeleteResult.NOT_FOUND:
  6392. any_not_found = True
  6393. break # 550 will not recover; try next candidate
  6394. # FAILED: real error — retry with backoff, then give up
  6395. if attempt < 3:
  6396. await asyncio.sleep(2)
  6397. else:
  6398. any_real_failure = True
  6399. logger.warning(
  6400. "SD card cleanup failed after 3 attempts for %s "
  6401. "(network/auth/transient error — file may linger on SD card)",
  6402. remote_path,
  6403. )
  6404. if not any_deleted and not any_real_failure and any_not_found:
  6405. # Every candidate said "not here." Either the printer
  6406. # firmware swept the SD card itself (common on A1) or the
  6407. # dispatcher's upload path doesn't match our candidate
  6408. # rule. Either way: nothing to clean up, no warning.
  6409. logger.debug(
  6410. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6411. "(printer likely self-cleaned)",
  6412. printer.name,
  6413. )
  6414. except Exception as e:
  6415. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6416. log_timing("SD card cleanup")
  6417. # Update queue item status early — must run before the archive_id early-return
  6418. # so queue items don't get stuck in "printing" when archive lookup fails.
  6419. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6420. queue_item_id = None
  6421. billing_run_id: str | None = None
  6422. billing_user_id: int | None = None
  6423. billing_cost_center_id: int | None = None
  6424. billing_plate_id: int | None = None
  6425. queue_status = None
  6426. queue_auto_off = False
  6427. try:
  6428. from backend.app.core.database import run_with_retry
  6429. from backend.app.models.print_queue import PrintQueueItem
  6430. async def _update_queue_status(db):
  6431. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6432. nonlocal queue_item_id, queue_status, queue_auto_off
  6433. result = await db.execute(
  6434. select(PrintQueueItem)
  6435. .where(PrintQueueItem.printer_id == printer_id)
  6436. .where(PrintQueueItem.status == "printing")
  6437. )
  6438. printing_items = list(result.scalars().all())
  6439. if len(printing_items) > 1:
  6440. logger.warning(
  6441. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6442. printer_id,
  6443. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6444. )
  6445. item = printing_items[0] if printing_items else None
  6446. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6447. return
  6448. if item:
  6449. queue_status = data.get("status", "completed")
  6450. # MQTT sends "aborted" for cancelled prints; normalise to
  6451. # "cancelled" so it matches the queue schema Literal.
  6452. if queue_status == "aborted":
  6453. queue_status = "cancelled"
  6454. item.status = queue_status
  6455. item.completed_at = datetime.now(timezone.utc)
  6456. if queue_status == "failed" and not item.error_message:
  6457. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6458. # Bump usage counters on the source library file so admins can
  6459. # sort by "last printed" and (eventually) auto-purge stale
  6460. # files — #1008.
  6461. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6462. await db.commit()
  6463. queue_item_id = item.id
  6464. billing_run_id = item.billing_run_id
  6465. billing_user_id = item.created_by_id
  6466. billing_cost_center_id = item.cost_center_id
  6467. billing_plate_id = item.plate_id
  6468. queue_auto_off = item.auto_off_after
  6469. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6470. await run_with_retry(_update_queue_status, label="queue status update")
  6471. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6472. # their own sessions and have their own error handling — no retry needed.
  6473. if queue_item_id is not None:
  6474. # Batch orders (#342): this run may have been the last one an order
  6475. # owed. Re-evaluate here rather than lazily on read, so a finished
  6476. # order reports itself complete without someone opening the page.
  6477. try:
  6478. from backend.app.services.print_batch import refresh_batch_status_for_item
  6479. async with async_session() as db:
  6480. await refresh_batch_status_for_item(db, queue_item_id)
  6481. await db.commit()
  6482. except Exception as e:
  6483. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6484. # MQTT relay - publish queue job completed
  6485. try:
  6486. printer_info = printer_manager.get_printer(printer_id)
  6487. await mqtt_relay.on_queue_job_completed(
  6488. job_id=queue_item_id,
  6489. filename=filename or subtask_name,
  6490. printer_id=printer_id,
  6491. printer_name=printer_info.name if printer_info else "Unknown",
  6492. status=queue_status,
  6493. )
  6494. except Exception:
  6495. pass # Don't fail if MQTT fails
  6496. # Check if queue is now empty and send notification
  6497. try:
  6498. from sqlalchemy import func as sa_func
  6499. async with async_session() as db:
  6500. count_result = await db.execute(
  6501. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6502. )
  6503. pending_count = count_result.scalar() or 0
  6504. if pending_count == 0:
  6505. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6506. completed_result = await db.execute(
  6507. select(sa_func.count(PrintQueueItem.id)).where(
  6508. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6509. PrintQueueItem.completed_at >= today_start,
  6510. )
  6511. )
  6512. completed_count = completed_result.scalar() or 1
  6513. await notification_service.on_queue_completed(
  6514. completed_count=completed_count,
  6515. db=db,
  6516. )
  6517. except Exception:
  6518. pass # Don't fail if notification fails
  6519. # Handle auto_off_after - power off printer if the queue item opted
  6520. # in. Delegates to the smart-plug manager so the off honours each
  6521. # plug's configured strategy (time delay or temperature threshold),
  6522. # is cancelled if the printer starts printing again, and never cuts
  6523. # power on a loaded print (#1890). Previously an inline block here
  6524. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6525. # timeout regardless of print state — cutting a touchscreen reprint.
  6526. if queue_auto_off:
  6527. try:
  6528. async with async_session() as db:
  6529. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6530. except Exception as e:
  6531. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6532. except Exception as e:
  6533. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6534. log_timing("Queue item update")
  6535. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6536. # Must run before archive_id early-return so it fires for all prints (including
  6537. # prints started from BambuStudio/touchscreen that have no archive).
  6538. if data.get("status") == "completed":
  6539. try:
  6540. from backend.app.api.routes.settings import get_setting
  6541. async with async_session() as db:
  6542. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6543. threshold = float(threshold_str) if threshold_str else 35.0
  6544. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6545. async with async_session() as db:
  6546. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6547. if providers:
  6548. _bed_cool_waiters[printer_id] = {
  6549. "threshold": threshold,
  6550. "filename": filename or subtask_name or "",
  6551. "registered_at": time.time(),
  6552. }
  6553. logger.info(
  6554. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6555. printer_id,
  6556. threshold,
  6557. )
  6558. else:
  6559. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6560. except Exception as e:
  6561. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6562. # Capture the slicer estimate before usage tracking runs. The tracker may
  6563. # update archive.cost with this run's measured cost; billing partial runs
  6564. # against that already-partial value would discount the charge twice.
  6565. billing_planned_grams: float | None = None
  6566. billing_base_cost: float | None = None
  6567. if archive_id:
  6568. try:
  6569. async with async_session() as db:
  6570. from backend.app.models.archive import PrintArchive
  6571. billing_archive = await db.get(PrintArchive, archive_id)
  6572. if billing_archive:
  6573. billing_path = (
  6574. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6575. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6576. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6577. billing_archive,
  6578. billing_path,
  6579. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6580. )
  6581. except Exception as e:
  6582. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6583. # --- Track filament consumption (must run before archive_id early-return so usage
  6584. # is recorded even when auto-archive is disabled) ---
  6585. usage_results: list[dict] = []
  6586. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6587. stored_ams_mapping = data.get("ams_mapping")
  6588. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6589. if not stored_ams_mapping and archive_id:
  6590. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6591. # Always drain the plate_id register on completion — the session already
  6592. # consumed it at print-start injection; leaving it would leak into the next
  6593. # print on the same archive_id (rare but possible with reprints) (#1697).
  6594. # Capture the popped value so the completion notification can scope the
  6595. # archive-level (summed-across-plates per #1593) filament + time totals
  6596. # down to the single plate that was actually printed (#1785).
  6597. notify_plate_id: int | None = None
  6598. if archive_id:
  6599. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6600. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6601. try:
  6602. async with async_session() as db:
  6603. from backend.app.api.routes.settings import get_setting
  6604. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6605. if not _spoolman_on or _spoolman_on.lower() != "true":
  6606. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6607. async with async_session() as db:
  6608. usage_results = await usage_on_print_complete(
  6609. printer_id,
  6610. data,
  6611. printer_manager,
  6612. db,
  6613. archive_id=archive_id,
  6614. ams_mapping=stored_ams_mapping,
  6615. )
  6616. if usage_results:
  6617. await ws_manager.broadcast(
  6618. {
  6619. "type": "spool_usage_logged",
  6620. "printer_id": printer_id,
  6621. "usage": usage_results,
  6622. }
  6623. )
  6624. log_timing("Usage tracker")
  6625. except Exception as e:
  6626. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6627. # Drop the print-start context unconditionally — the Spoolman branch above
  6628. # skips the internal tracker entirely, so nothing else would clear what
  6629. # print start captured, and a row surviving its print would be restored
  6630. # onto the next one after a restart.
  6631. try:
  6632. from backend.app.services.usage_tracker import discard_session
  6633. async with async_session() as db:
  6634. await discard_session(db, printer_id)
  6635. except Exception as e:
  6636. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6637. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6638. if archive_id:
  6639. if data.get("status") == "completed":
  6640. try:
  6641. await _report_spoolman_usage(printer_id, archive_id)
  6642. log_timing("Spoolman usage report")
  6643. except Exception as e:
  6644. logger.warning("Spoolman usage reporting failed: %s", e)
  6645. else:
  6646. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6647. try:
  6648. async with async_session() as db:
  6649. await _cleanup_spoolman_tracking(
  6650. printer_id,
  6651. archive_id,
  6652. db,
  6653. last_layer_num=data.get("last_layer_num"),
  6654. last_progress=data.get("last_progress"),
  6655. )
  6656. except Exception as e:
  6657. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6658. log_timing("Filament usage tracking")
  6659. if not archive_id:
  6660. # The printer's own calibration run has no archive by design, so this
  6661. # arrives here every time one finishes. Returning before the no-archive
  6662. # notification is not just noise control: that path attributes an
  6663. # unmatched completion to any queue item this printer finished in the
  6664. # last five minutes, which for a calibration that runs alongside a real
  6665. # print means emailing its owner that their print is done, twice and
  6666. # early. Everything above this point has already run — the plate-clear
  6667. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6668. # notification is skipped.
  6669. if is_internal_printer_job(filename, subtask_name):
  6670. logger.info(
  6671. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6672. filename,
  6673. subtask_name,
  6674. )
  6675. return
  6676. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6677. # Still send print-complete/failed/stopped notifications even without an archive.
  6678. # Try to enrich with queue/library-file data so user-specific emails work too.
  6679. async def _notify_no_archive():
  6680. try:
  6681. async with async_session() as db:
  6682. from backend.app.models.library import LibraryFile
  6683. from backend.app.models.print_queue import PrintQueueItem
  6684. from backend.app.models.printer import Printer
  6685. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6686. printer_obj = result.scalar_one_or_none()
  6687. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  6688. # Try to find the most-recent queue item for this printer so we can
  6689. # recover created_by_id and estimated print time.
  6690. # NOTE: By the time this task runs the queue item status has already
  6691. # been updated to a terminal state (completed/failed/cancelled), so
  6692. # we look for recently-completed items (within the last 5 minutes).
  6693. no_archive_data: dict | None = None
  6694. try:
  6695. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  6696. q_result = await db.execute(
  6697. select(PrintQueueItem)
  6698. .where(PrintQueueItem.printer_id == printer_id)
  6699. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  6700. .where(PrintQueueItem.completed_at >= cutoff)
  6701. .order_by(PrintQueueItem.completed_at.desc())
  6702. .limit(1)
  6703. )
  6704. queue_item = q_result.scalar_one_or_none()
  6705. if queue_item:
  6706. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6707. # Pull estimated time from library file when available
  6708. if queue_item.library_file_id:
  6709. lib_result = await db.execute(
  6710. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6711. )
  6712. lib_file = lib_result.scalar_one_or_none()
  6713. if lib_file and lib_file.print_time_seconds:
  6714. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6715. except Exception as lookup_err:
  6716. logger.debug(
  6717. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6718. )
  6719. # Enrich with usage tracker results (captured in enclosing scope)
  6720. if usage_results:
  6721. if no_archive_data is None:
  6722. no_archive_data = {}
  6723. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6724. if total_from_usage > 0:
  6725. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6726. no_archive_data["usage_results"] = usage_results
  6727. # Try MQTT remaining_time for print duration when no queue/library data
  6728. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  6729. mqtt_remaining = data.get("remaining_time")
  6730. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  6731. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  6732. ps = data.get("status", "completed")
  6733. logger.info(
  6734. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  6735. )
  6736. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6737. await notification_service.on_print_complete(
  6738. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  6739. )
  6740. else:
  6741. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6742. # Send user-specific email if we have a created_by_id
  6743. if no_archive_data and no_archive_data.get("created_by_id"):
  6744. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6745. await _dispatch_user_print_email(
  6746. ps,
  6747. no_archive_data["created_by_id"],
  6748. p_name,
  6749. raw_filename,
  6750. db,
  6751. )
  6752. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  6753. except Exception as e:
  6754. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  6755. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  6756. return
  6757. log_timing("Archive lookup")
  6758. # Update archive status
  6759. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  6760. try:
  6761. async with async_session() as db:
  6762. service = ArchiveService(db)
  6763. status = data.get("status", "completed")
  6764. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  6765. if hms_errors:
  6766. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  6767. failure_reason = derive_failure_reason(status, hms_errors)
  6768. if data.get("_reconciled"):
  6769. # A reconciled completion closes out a stale archive at
  6770. # reconnect — it is not a user action, so don't mislabel it
  6771. # "userCancelled". It shares the stale-cleanup path's key
  6772. # (issue #2974) and records that the real end time is unknown,
  6773. # which is also why its logged duration is 0 (#2592).
  6774. failure_reason = "noStatusUpdate"
  6775. if failure_reason:
  6776. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  6777. elif status == "failed" and hms_errors:
  6778. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  6779. await service.update_archive_status(
  6780. archive_id,
  6781. status=status,
  6782. completed_at=(
  6783. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  6784. ),
  6785. failure_reason=failure_reason,
  6786. )
  6787. logger.info(
  6788. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  6789. )
  6790. await ws_manager.send_archive_updated(
  6791. {
  6792. "id": archive_id,
  6793. "status": status,
  6794. }
  6795. )
  6796. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  6797. # MQTT relay - publish archive updated
  6798. try:
  6799. await mqtt_relay.on_archive_updated(
  6800. archive_id=archive_id,
  6801. print_name=filename or subtask_name,
  6802. status=status,
  6803. )
  6804. except Exception:
  6805. pass # Don't fail if MQTT fails
  6806. except Exception as e:
  6807. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  6808. # Continue with other operations even if archive update fails
  6809. log_timing("Archive status update")
  6810. # Apply finance wallet charge or release reservations once. For all partial
  6811. # terminal states (failed, aborted at the printer display, or cancelled via
  6812. # Bambuddy) use this run's measured spool delta, falling back to the last
  6813. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  6814. # estimate and therefore cannot represent an interrupted run.
  6815. try:
  6816. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  6817. async with async_session() as db:
  6818. from backend.app.models.archive import PrintArchive
  6819. from backend.app.services.finance_billing import apply_print_charge_for_archive
  6820. archive = await db.get(PrintArchive, archive_id)
  6821. if archive and billing_run_id is None:
  6822. billing_run_id = getattr(archive, "billing_run_id", None)
  6823. if archive and archive.created_by_id is None and _print_user_info:
  6824. archive.created_by_id = _print_user_info.get("user_id")
  6825. await db.flush()
  6826. run_status = data.get("status", "completed")
  6827. last_progress = data.get("last_progress")
  6828. if last_progress is None:
  6829. last_progress = data.get("progress")
  6830. actual_run_grams = _compute_run_filament_grams(
  6831. run_status,
  6832. billing_planned_grams,
  6833. last_progress,
  6834. usage_results,
  6835. )
  6836. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  6837. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  6838. charged = await apply_print_charge_for_archive(
  6839. db,
  6840. archive_id,
  6841. charged_user_id=billing_user_id,
  6842. cost_center_id=(
  6843. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  6844. ),
  6845. print_queue_id=queue_item_id,
  6846. print_run_id=billing_run_id,
  6847. base_cost_override=billing_base_cost,
  6848. filament_usage=filament_usage,
  6849. )
  6850. await db.commit()
  6851. if charged:
  6852. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  6853. except Exception as e:
  6854. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  6855. printer_info = printer_manager.get_printer(printer_id)
  6856. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  6857. billing_filename = filename or subtask_name or "Unknown"
  6858. billing_error = str(e)
  6859. try:
  6860. await ws_manager.broadcast(
  6861. {
  6862. "type": "billing_charge_failed",
  6863. "printer_id": printer_id,
  6864. "printer_name": billing_printer_name,
  6865. "filename": billing_filename,
  6866. "archive_id": archive_id,
  6867. }
  6868. )
  6869. except Exception as notification_error:
  6870. logger.error(
  6871. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  6872. archive_id,
  6873. notification_error,
  6874. )
  6875. async def _notify_billing_charge_failed() -> None:
  6876. try:
  6877. async with async_session() as notification_db:
  6878. await notification_service.on_billing_charge_failed(
  6879. printer_id,
  6880. billing_printer_name,
  6881. billing_filename,
  6882. archive_id,
  6883. billing_error,
  6884. notification_db,
  6885. )
  6886. except Exception as provider_error:
  6887. logger.error(
  6888. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  6889. archive_id,
  6890. provider_error,
  6891. exc_info=True,
  6892. )
  6893. spawn_background_task(
  6894. _notify_billing_charge_failed(),
  6895. name=f"billing-charge-failed-{archive_id}",
  6896. )
  6897. log_timing("Finance charge update")
  6898. # Write independent print log entry (separate table, never touches archives)
  6899. try:
  6900. async with async_session() as db:
  6901. from backend.app.models.archive import PrintArchive
  6902. from backend.app.services.print_log import write_log_entry
  6903. archive = await db.get(PrintArchive, archive_id)
  6904. if archive:
  6905. # Back-fill created_by_id on reprint (#730): reprint reuses the
  6906. # source archive row rather than creating a new one, so an
  6907. # archive that was auto-created from a printer-initiated
  6908. # print (created_by_id=NULL) would otherwise stay unattributed
  6909. # forever. When we have a print-session user AND the archive
  6910. # has no attribution yet, credit the current user. Never
  6911. # overwrite an existing attribution — the original uploader
  6912. # keeps ownership.
  6913. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  6914. if archive.created_by_id is None and _print_user_id is not None:
  6915. archive.created_by_id = _print_user_id
  6916. p_info = printer_manager.get_printer(printer_id)
  6917. # Per-run actuals — written to PrintLogEntry so stats reflect
  6918. # what THIS print actually used, not the source archive's
  6919. # first-run values (#1378). Helper handles the partial-print
  6920. # math (failed / cancelled / stopped get scaled to progress
  6921. # or to tracked spool deltas).
  6922. _run_status = data.get("status", "completed")
  6923. # #2614: scope the per-run estimate to the printed plate. For a
  6924. # multi-plate 3MF dispatched one plate at a time, the archive's
  6925. # filament/cost are the whole-file totals; the PrintLogEntry must
  6926. # reflect only this plate. No effect on single-plate archives (the
  6927. # plate estimate equals the whole-file value) or on the tracker
  6928. # path (measured spool deltas win in _compute_run_filament_grams).
  6929. _est_full_path = (
  6930. app_settings.base_dir / archive.file_path if archive.file_path else None
  6931. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6932. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  6933. _run_grams = _compute_run_filament_grams(
  6934. _run_status,
  6935. _est_grams,
  6936. data.get("last_progress", data.get("progress")),
  6937. usage_results,
  6938. )
  6939. # Per-run cost — prefer usage_results sum. For partial prints
  6940. # we deliberately skip the topup-to-estimate logic in
  6941. # usage_tracker (which assumes the print completed); the raw
  6942. # tracked-spool sum is closer to what THIS run actually cost.
  6943. _run_cost: float | None = None
  6944. if usage_results:
  6945. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  6946. if _run_cost is None and _run_status == "completed":
  6947. _run_cost = _est_cost
  6948. await write_log_entry(
  6949. db,
  6950. archive_id=archive.id,
  6951. # Captured by _update_queue_status above; None for
  6952. # printer-initiated prints with no queue row. Batch
  6953. # cost/energy roll-up joins on it (#342).
  6954. queue_item_id=queue_item_id,
  6955. status=_run_status,
  6956. print_name=archive.print_name,
  6957. printer_name=p_info.name if p_info else None,
  6958. printer_id=printer_id,
  6959. started_at=archive.started_at,
  6960. completed_at=archive.completed_at,
  6961. filament_type=archive.filament_type,
  6962. filament_color=archive.filament_color,
  6963. filament_used_grams=_run_grams,
  6964. cost=_run_cost,
  6965. failure_reason=archive.failure_reason,
  6966. thumbnail_path=archive.thumbnail_path,
  6967. created_by_id=archive.created_by_id,
  6968. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  6969. # Reconciled completions have an unknown real end time —
  6970. # log 0 duration instead of the whole disconnect gap (#2592).
  6971. reconciled=bool(data.get("_reconciled")),
  6972. )
  6973. await db.commit()
  6974. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  6975. except Exception as e:
  6976. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  6977. log_timing("Print log entry")
  6978. # Run slow operations as background tasks to avoid blocking the event loop
  6979. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  6980. async def _background_energy_calculation():
  6981. """Calculate and save energy usage in background.
  6982. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  6983. backend restart no longer loses per-print energy data).
  6984. """
  6985. try:
  6986. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  6987. async with async_session() as db:
  6988. from backend.app.models.archive import PrintArchive
  6989. archive = await db.get(PrintArchive, archive_id)
  6990. if archive is None:
  6991. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  6992. return
  6993. starting_kwh = archive.energy_start_kwh
  6994. if starting_kwh is None:
  6995. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  6996. return
  6997. candidates = await energy_plug_candidates(db, printer_id)
  6998. if not candidates:
  6999. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7000. return
  7001. # Same ordering as the start reading, so the delta below is
  7002. # against the counter that produced `starting_kwh` (#2859).
  7003. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7004. if selected is None:
  7005. logger.warning(
  7006. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7007. printer_id,
  7008. ", ".join(plug.name for plug in candidates),
  7009. )
  7010. return
  7011. plug, energy = selected
  7012. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7013. energy_used = round(energy["total"] - starting_kwh, 4)
  7014. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7015. if energy_used < 0:
  7016. logger.warning(
  7017. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7018. archive_id,
  7019. starting_kwh,
  7020. energy["total"],
  7021. )
  7022. return
  7023. from backend.app.api.routes.settings import get_setting
  7024. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  7025. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  7026. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  7027. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7028. # reprint doesn't visually clobber the source archive's energy data
  7029. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7030. from sqlalchemy import func
  7031. from backend.app.models.print_log import PrintLogEntry
  7032. existing_runs = await db.scalar(
  7033. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7034. )
  7035. if (existing_runs or 0) <= 1:
  7036. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7037. # we just wrote for THIS print. Either way it's the first run.
  7038. archive.energy_kwh = energy_used
  7039. archive.energy_cost = energy_cost_value
  7040. # Backfill the latest PrintLogEntry for this archive with energy
  7041. # (write_log_entry above ran before this background task completed,
  7042. # so energy fields are still NULL on that row).
  7043. latest_run = await db.execute(
  7044. select(PrintLogEntry)
  7045. .where(PrintLogEntry.archive_id == archive_id)
  7046. .order_by(PrintLogEntry.id.desc())
  7047. .limit(1)
  7048. )
  7049. run_row = latest_run.scalar_one_or_none()
  7050. if run_row is not None:
  7051. run_row.energy_kwh = energy_used
  7052. run_row.energy_cost = energy_cost_value
  7053. await db.commit()
  7054. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7055. except Exception as e:
  7056. logger.warning("[ENERGY-BG] Failed: %s", e)
  7057. async def _background_finish_photo() -> str | None:
  7058. """Capture finish photo in background. Returns photo filename if captured."""
  7059. # #2547: set once this function has raised the plate itself (the
  7060. # timelapse path, where the moment producer returned without doing it).
  7061. # Declared out here so the `finally` can lower it again no matter where
  7062. # the capture below fails.
  7063. plate_restored_z: float | None = None
  7064. try:
  7065. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7066. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7067. # Read phase: settings + printer + archive in a short session, released
  7068. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7069. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7070. # tens of seconds; holding this session across it pinned one pooled
  7071. # connection idle-in-transaction per finishing print (issue #2572).
  7072. async with async_session() as db:
  7073. from backend.app.api.routes.settings import get_setting
  7074. from backend.app.models.archive import PrintArchive
  7075. from backend.app.models.printer import Printer
  7076. capture_enabled = await get_setting(db, "capture_finish_photo")
  7077. if capture_enabled is not None and capture_enabled.lower() != "true":
  7078. return None
  7079. if not archive_id:
  7080. return None
  7081. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7082. archive = (
  7083. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7084. ).scalar_one_or_none()
  7085. if not printer or not archive:
  7086. return None
  7087. import uuid
  7088. from datetime import datetime
  7089. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7090. if not archive.file_path:
  7091. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7092. archive_dir = resolve_archive_dir(archive)
  7093. photo_filename = None
  7094. # Prefer the timelapse last-frame source when a timelapse was
  7095. # recording — it captures the moment after the toolhead parks
  7096. # but before the bed drops, which the live-camera grab below
  7097. # would miss (#1397). Skipped for external cameras (those have
  7098. # their own framing and don't see a Bambu timelapse). Only
  7099. # runs when the USER explicitly enabled timelapse for this
  7100. # print — #1721 removed Bambuddy's force-on at dispatch
  7101. # because it caused per-layer nozzle parking on Smooth-mode
  7102. # slicer profiles.
  7103. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7104. printer.external_camera_enabled and printer.external_camera_url
  7105. )
  7106. timelapse_still_pending = False
  7107. if prefer_timelapse_source:
  7108. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7109. archive_id=archive_id,
  7110. archive_dir=archive_dir,
  7111. rotation=getattr(printer, "camera_rotation", 0),
  7112. )
  7113. # #1721: replacement framing path — on_finish_photo_moment
  7114. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7115. # parked, bed not yet dropped) and cached the JPEG bytes in
  7116. # _stage22_finish_frames. Consume them now so the saved photo
  7117. # has the better framing instead of the post-bed-drop angle
  7118. # the live-camera fallback below would give.
  7119. if not photo_filename:
  7120. # #1790: on the FINISH-state fallback path the producer
  7121. # task is dispatched back-to-back with this consumer, so
  7122. # a bare pop would race past with an empty result and
  7123. # the RTSP fallback below would collide with the
  7124. # producer's still-in-flight grab (single-client RTSP
  7125. # on Bambu printers). Wait for the producer to finish
  7126. # or give up before touching the cache.
  7127. #
  7128. # #2547: 20s was enough when the producer only ever grabbed a
  7129. # frame. It now also raises the plate first, which costs the
  7130. # settle window before the grab even starts — so the budget has
  7131. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7132. # under the notification's own photo wait below.
  7133. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7134. if in_flight is not None:
  7135. try:
  7136. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7137. except asyncio.TimeoutError:
  7138. logger.warning(
  7139. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7140. printer_id,
  7141. )
  7142. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7143. if cached_frame:
  7144. # Already rotated by the producer (#2708) — rotating again
  7145. # here would undo the fix on the banked-frame path, whose
  7146. # bytes reach the cache having been rotated once already.
  7147. photos_dir = archive_dir / "photos"
  7148. photos_dir.mkdir(parents=True, exist_ok=True)
  7149. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7150. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7151. photo_path = photos_dir / photo_filename
  7152. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7153. logger.info(
  7154. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7155. photo_filename,
  7156. len(cached_frame),
  7157. )
  7158. # #2547: the timelapse path reaches the live grab below whenever the
  7159. # video hasn't landed in time — the documented usual outcome on
  7160. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7161. # returned early for those prints without raising the plate, so
  7162. # without this the photo that actually ships in the notification is
  7163. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7164. # asked us to fix. The archive still gets the better video frame
  7165. # later; this is about the image the user is sent.
  7166. #
  7167. # Gated on `timelapse_was_active` precisely because that is the
  7168. # condition under which the producer skipped. On every other path it
  7169. # has already raised and lowered the plate, and repeating that here
  7170. # would be a second pointless round trip.
  7171. if (
  7172. not photo_filename
  7173. and data.get("timelapse_was_active")
  7174. and not print_dispatch_context.end_gcode_injected(printer_id)
  7175. ):
  7176. try:
  7177. async with async_session() as db:
  7178. from backend.app.api.routes.settings import get_setting
  7179. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7180. if restore_setting is None or restore_setting.lower() == "true":
  7181. max_z = await _max_z_for_current_print(printer_id, data, logger)
  7182. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7183. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7184. plate_restored_z = max_z
  7185. except Exception as e:
  7186. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7187. # Fallback chain: external camera → buffered live frame →
  7188. # fresh RTSP capture. Only runs if the timelapse path above
  7189. # didn't already produce a photo.
  7190. if not photo_filename:
  7191. if printer.external_camera_enabled and printer.external_camera_url:
  7192. logger.info("[PHOTO-BG] Using external camera")
  7193. from backend.app.api.routes.camera import live_frame_for_capture
  7194. from backend.app.services.external_camera import capture_frame
  7195. # #2707: the second half of the finish-photo failure — the
  7196. # pre-capture and this fallback both collided with the live
  7197. # view. None here continues down the fallback chain.
  7198. defer, buffered = live_frame_for_capture(printer_id)
  7199. if defer:
  7200. frame_data = buffered
  7201. else:
  7202. frame_data = await capture_frame(
  7203. printer.external_camera_url,
  7204. printer.external_camera_type or "mjpeg",
  7205. snapshot_url=printer.external_camera_snapshot_url,
  7206. )
  7207. if frame_data:
  7208. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7209. photos_dir = archive_dir / "photos"
  7210. photos_dir.mkdir(parents=True, exist_ok=True)
  7211. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7212. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7213. photo_path = photos_dir / photo_filename
  7214. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7215. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7216. else:
  7217. # Check if camera stream is active - use buffered frame to avoid freeze
  7218. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7219. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7220. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  7221. buffered_frame = get_buffered_frame(printer_id)
  7222. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7223. # Use frame from active stream
  7224. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7225. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7226. photos_dir = archive_dir / "photos"
  7227. photos_dir.mkdir(parents=True, exist_ok=True)
  7228. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7229. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7230. photo_path = photos_dir / photo_filename
  7231. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7232. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7233. else:
  7234. # No active stream - capture new frame
  7235. from backend.app.services.camera import capture_finish_photo
  7236. photo_filename = await capture_finish_photo(
  7237. printer_id=printer_id,
  7238. ip_address=printer.ip_address,
  7239. access_code=printer.access_code,
  7240. model=printer.model,
  7241. archive_dir=archive_dir,
  7242. rotation=getattr(printer, "camera_rotation", 0),
  7243. )
  7244. # Write phase: attach the photo in a fresh short-lived session.
  7245. if photo_filename:
  7246. async with async_session() as db:
  7247. from backend.app.models.archive import PrintArchive
  7248. arch = await db.get(PrintArchive, archive_id)
  7249. if arch is not None:
  7250. photos = arch.photos or []
  7251. photos.append(photo_filename)
  7252. arch.photos = photos
  7253. await db.commit()
  7254. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7255. # The short wait above is bounded so a slow printer can't hold up
  7256. # the print-complete notification, which is what the caller is
  7257. # blocking on. When it ran out with the video still on its way,
  7258. # keep waiting off to the side and add the better frame to the
  7259. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7260. # users, whose videos routinely take minutes to transfer, never get
  7261. # the pre-bed-drop framing this path exists to provide.
  7262. #
  7263. # Spawned here rather than at the point the wait gave up: both this
  7264. # function and the upgrade do a read-modify-write on `photos`, and
  7265. # the live-camera fallback above can take tens of seconds. Starting
  7266. # the upgrade before that write means the two can interleave and one
  7267. # silently drops the other's entry, leaving a JPEG on disk that the
  7268. # gallery never lists.
  7269. if timelapse_still_pending:
  7270. spawn_background_task(
  7271. _upgrade_finish_photo_from_timelapse(
  7272. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7273. ),
  7274. name=f"finish-photo-upgrade-{archive_id}",
  7275. )
  7276. return photo_filename
  7277. except Exception as e:
  7278. logger.warning("[PHOTO-BG] Failed: %s", e)
  7279. return None
  7280. finally:
  7281. # #2547: we raised the plate, so we owe the move back down — even if
  7282. # the capture in between threw. Otherwise the user finds the print
  7283. # pinned under the nozzle.
  7284. if plate_restored_z is not None:
  7285. try:
  7286. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7287. except Exception as e:
  7288. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7289. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7290. # Photo capture task - result will be used by notifications
  7291. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7292. log_timing("Background tasks scheduled (energy, photo)")
  7293. # Also run smart plug, notifications, and maintenance as background tasks
  7294. print_status = data.get("status", "completed")
  7295. async def _background_smart_plug():
  7296. """Handle smart plug automation in background."""
  7297. try:
  7298. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7299. async with async_session() as db:
  7300. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7301. logger.info("[AUTO-OFF-BG] Completed")
  7302. except Exception as e:
  7303. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7304. async def _background_notifications(finish_photo_filename: str | None = None):
  7305. """Send print complete notifications in background."""
  7306. try:
  7307. logger.info(
  7308. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7309. )
  7310. async with async_session() as db:
  7311. from backend.app.models.archive import PrintArchive
  7312. from backend.app.models.printer import Printer
  7313. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7314. printer = result.scalar_one_or_none()
  7315. printer_name = printer.name if printer else f"Printer {printer_id}"
  7316. archive_data = None
  7317. if archive_id:
  7318. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7319. archive = archive_result.scalar_one_or_none()
  7320. if archive:
  7321. # Actual elapsed time from started_at/completed_at when both are
  7322. # populated (every terminal status sets completed_at after #1198).
  7323. # Falls back to None so the notification path can decide whether to
  7324. # render the slicer estimate as a last resort.
  7325. actual_time_seconds = None
  7326. if archive.started_at and archive.completed_at:
  7327. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7328. if elapsed > 0:
  7329. actual_time_seconds = int(elapsed)
  7330. archive_data = {
  7331. "print_time_seconds": archive.print_time_seconds,
  7332. "actual_time_seconds": actual_time_seconds,
  7333. "actual_filament_grams": archive.filament_used_grams,
  7334. "failure_reason": archive.failure_reason,
  7335. "created_by_id": archive.created_by_id,
  7336. }
  7337. # Scale filament usage for partial prints
  7338. if print_status != "completed" and archive.filament_used_grams:
  7339. progress = data.get("progress") or 0
  7340. scale = _partial_progress_scale(progress)
  7341. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7342. archive_data["progress"] = progress
  7343. # Pass per-slot data from archive.extra_data
  7344. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7345. slots = archive.extra_data["filament_slots"]
  7346. if print_status != "completed":
  7347. scale = _partial_progress_scale(data.get("progress"))
  7348. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7349. archive_data["filament_slots"] = slots
  7350. # Scope project-summed totals down to the plate that was
  7351. # actually printed — see _scope_notification_archive_data_to_plate
  7352. # for the why (#1785).
  7353. archive_data = _scope_notification_archive_data_to_plate(
  7354. archive_data,
  7355. archive.file_path,
  7356. notify_plate_id,
  7357. print_status,
  7358. data.get("progress"),
  7359. app_settings.base_dir,
  7360. )
  7361. # Enrich filament_grams from usage_results when archive has no 3MF data
  7362. if not archive_data.get("actual_filament_grams") and usage_results:
  7363. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7364. if total_from_usage > 0:
  7365. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7366. # Pass usage tracker results for AMS slot info in notifications
  7367. if usage_results:
  7368. archive_data["usage_results"] = usage_results
  7369. # Add finish photo URL and image bytes if available
  7370. if finish_photo_filename:
  7371. photo_url, photo_bytes = await _finish_photo_for_notification(
  7372. db, archive, archive_id, finish_photo_filename
  7373. )
  7374. if photo_url:
  7375. archive_data["finish_photo_url"] = photo_url
  7376. if photo_bytes:
  7377. archive_data["image_data"] = photo_bytes
  7378. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7379. await notification_service.on_print_complete(
  7380. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7381. )
  7382. else:
  7383. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7384. # Post-print outcome confirmation (#1898). Runs in this
  7385. # background task so the finish photo fetched above rides
  7386. # along with the prompt.
  7387. if print_status == "completed" and archive_id:
  7388. await _dispatch_outcome_confirmation_safely(
  7389. db, printer_id, printer_name, data, archive_id, archive_data
  7390. )
  7391. # Send user-specific email notification
  7392. if archive_data:
  7393. created_by_id = archive_data.get("created_by_id")
  7394. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7395. await _dispatch_user_print_email(
  7396. print_status,
  7397. created_by_id,
  7398. printer_name,
  7399. raw_filename,
  7400. db,
  7401. image_data=archive_data.get("image_data"),
  7402. finish_photo_url=archive_data.get("finish_photo_url"),
  7403. )
  7404. logger.info("[NOTIFY-BG] Completed")
  7405. except Exception as e:
  7406. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7407. async def _background_maintenance_check():
  7408. """Check for maintenance due in background."""
  7409. if print_status != "completed":
  7410. return
  7411. try:
  7412. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7413. async with async_session() as db:
  7414. from backend.app.models.printer import Printer
  7415. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7416. printer = result.scalar_one_or_none()
  7417. printer_name = printer.name if printer else f"Printer {printer_id}"
  7418. await ensure_default_types(db)
  7419. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7420. items_needing_attention = [
  7421. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7422. for item in overview.maintenance_items
  7423. if item.enabled and (item.is_due or item.is_warning)
  7424. ]
  7425. if items_needing_attention:
  7426. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7427. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7428. # MQTT relay - publish maintenance alerts
  7429. for item in items_needing_attention:
  7430. try:
  7431. await mqtt_relay.on_maintenance_alert(
  7432. printer_id=printer_id,
  7433. printer_name=printer_name,
  7434. maintenance_type=item["name"],
  7435. current_value=0, # Not easily available here
  7436. threshold=0, # Not easily available here
  7437. )
  7438. except Exception:
  7439. pass # Don't fail if MQTT fails
  7440. else:
  7441. logger.info("[MAINT-BG] Completed (no items need attention)")
  7442. except Exception as e:
  7443. logger.warning("[MAINT-BG] Failed: %s", e)
  7444. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7445. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7446. # Notification task waits for photo capture to complete first (with timeout).
  7447. # When a timelapse was recording, photo sourcing polls the per-print
  7448. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7449. # carries the correct bed-up photo instead of falling through to the
  7450. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7451. #
  7452. # #2547: both budgets now have to cover a plate restore as well.
  7453. #
  7454. # Without timelapse, the wait is on the moment producer, which raises the
  7455. # plate before its grab — so this has to outlast that producer's own budget.
  7456. #
  7457. # With timelapse, the capture polls up to
  7458. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7459. # falls back to a live grab, which is the case that raises the plate. At the
  7460. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7461. # restore would have moved the plate for a photo nobody waited for.
  7462. photo_wait_timeout = (
  7463. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7464. if data.get("timelapse_was_active")
  7465. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7466. )
  7467. async def _photo_then_notify():
  7468. """Wait for photo capture, then send notification with photo URL."""
  7469. finish_photo = None
  7470. try:
  7471. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7472. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7473. except TimeoutError:
  7474. logger.warning(
  7475. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7476. photo_wait_timeout,
  7477. )
  7478. except Exception as e:
  7479. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7480. try:
  7481. await _background_notifications(finish_photo)
  7482. except Exception as e:
  7483. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7484. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7485. # Stitch external camera layer timelapse if session was active
  7486. print_status = data.get("status", "completed")
  7487. async def _background_layer_timelapse():
  7488. """Stitch layer timelapse and attach to archive."""
  7489. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7490. try:
  7491. if print_status == "completed":
  7492. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7493. timelapse_path = await tl_complete(printer_id)
  7494. if timelapse_path and archive_id:
  7495. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7496. async with async_session() as db:
  7497. service = ArchiveService(db)
  7498. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7499. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  7500. # Clean up the temp file
  7501. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7502. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7503. elif timelapse_path:
  7504. # Timelapse created but no archive - just clean up
  7505. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7506. else:
  7507. # Print failed or cancelled - cancel timelapse session
  7508. cancel_session(printer_id)
  7509. logger.info(
  7510. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7511. )
  7512. except Exception as e:
  7513. logger.warning("[LAYER-TL] Failed: %s", e)
  7514. # Try to cancel session on error
  7515. try:
  7516. cancel_session(printer_id)
  7517. except Exception:
  7518. pass # Best-effort timelapse session cancellation on error
  7519. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7520. log_timing("All background tasks scheduled")
  7521. # Auto-scan for timelapse if recording was active during the print
  7522. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7523. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7524. # Schedule timelapse scan as background task with retries
  7525. # The printer needs time to encode the video after print completion
  7526. baseline = _timelapse_baselines.pop(printer_id, None)
  7527. spawn_background_task(
  7528. _scan_for_timelapse_with_retries(archive_id, baseline),
  7529. name=f"scan-timelapse-{archive_id}",
  7530. )
  7531. log_timing("Timelapse scan scheduled")
  7532. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7533. # AMS sensor history recording
  7534. _ams_history_task: asyncio.Task | None = None
  7535. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7536. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7537. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7538. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7539. _ams_alarm_cooldown: dict[str, datetime] = {}
  7540. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7541. # (printer_id, ams_id) already reported as sending the drop index and no
  7542. # percentage. Logged once each so a supported printer that turns out to do this
  7543. # shows up in a support bundle rather than as a user wondering where the
  7544. # humidity reading went -- see the note at the read site below (#3140).
  7545. _ams_index_only_logged: set[tuple[int, int]] = set()
  7546. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7547. """Temperature at which the AMS alarm fires, falling back to the display band.
  7548. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7549. when a notification was sent as well, which is why a room above it made the
  7550. alarm fire once an hour for as long as the weather lasted -- and the only way
  7551. to stop that was to raise the display band and lose the colour that says the
  7552. unit is warm (#2905).
  7553. Unset resolves to the fair threshold, so an install that never sets one is
  7554. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7555. so that arrives here as a string and is handled by the same branch as any
  7556. other unparseable value -- there is no separate sentinel to keep in sync.
  7557. A non-positive value is refused rather than honoured: zero would alarm
  7558. permanently, and it is far more likely to be a cleared field than a
  7559. deliberate choice.
  7560. """
  7561. if raw_alarm_value is None:
  7562. return fair_threshold
  7563. try:
  7564. value = float(raw_alarm_value)
  7565. except (TypeError, ValueError):
  7566. return fair_threshold
  7567. if not math.isfinite(value) or value <= 0:
  7568. return fair_threshold
  7569. return value
  7570. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7571. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7572. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7573. # partway through a cool-down would otherwise resume alarming about heat the
  7574. # user asked for — the same internal-timestamp-row pattern as
  7575. # support.py's debug_logging_enabled_at.
  7576. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7577. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7578. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7579. # matters when it never does.
  7580. AMS_DRYING_GRACE_MINUTES = 120
  7581. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7582. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7583. Anything older than the grace cap would expire on its next visit anyway, so
  7584. discarding it here costs nothing and stops rows for deleted printers from
  7585. accumulating.
  7586. Stamps ahead of now get two defences, because a box whose clock jumps
  7587. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7588. ones are discarded outright, and the rest are clamped to now. Without the
  7589. clamp the cap would measure from a moment that has not happened yet and hold
  7590. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7591. after a clock jump is a far better failure than an alarm silently disabled
  7592. for hours.
  7593. """
  7594. from backend.app.models.settings import Settings
  7595. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7596. setting = result.scalar_one_or_none()
  7597. if not setting or not setting.value:
  7598. return {}
  7599. try:
  7600. raw = json.loads(setting.value)
  7601. except (ValueError, TypeError):
  7602. return {} # Corrupted row → no latch, alarms behave as they did before
  7603. if not isinstance(raw, dict):
  7604. return {}
  7605. now = datetime.now(timezone.utc)
  7606. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7607. latch: dict[str, datetime] = {}
  7608. for key, value in raw.items():
  7609. try:
  7610. stamp = datetime.fromisoformat(str(value))
  7611. except (ValueError, TypeError):
  7612. continue
  7613. if stamp.tzinfo is None:
  7614. stamp = stamp.replace(tzinfo=timezone.utc)
  7615. if not (now - window <= stamp <= now + window):
  7616. continue
  7617. # Nothing may sit in the future: suppression is measured as now minus
  7618. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7619. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7620. latch[str(key)] = min(stamp, now)
  7621. return latch
  7622. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7623. """Persist the latch, writing only when it actually changed.
  7624. Adds the session change but does not commit — the caller's own commit
  7625. carries it, so the latch lands in the same transaction as the sensor rows
  7626. that produced it.
  7627. """
  7628. from backend.app.models.settings import Settings
  7629. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7630. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7631. setting = result.scalar_one_or_none()
  7632. if setting is None:
  7633. # Don't create the row on installs that never dry anything.
  7634. if payload != "{}":
  7635. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7636. elif setting.value != payload:
  7637. setting.value = payload
  7638. def _ams_has_filament(ams_data: dict) -> bool:
  7639. """True if this AMS unit has at least one tray slot holding filament.
  7640. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7641. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7642. still report sensor readings, but those readings are ambient and not
  7643. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7644. humidity/temperature alarms on this check so empty units don't generate
  7645. hourly noise. Sensor history still records regardless so the UI charts
  7646. stay continuous.
  7647. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7648. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7649. """
  7650. bits = ams_data.get("tray_exist_bits")
  7651. if isinstance(bits, str) and bits.strip():
  7652. try:
  7653. return int(bits, 16) > 0
  7654. except ValueError:
  7655. pass
  7656. trays = ams_data.get("tray")
  7657. if isinstance(trays, list):
  7658. return any(
  7659. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  7660. )
  7661. return False
  7662. async def record_ams_history():
  7663. """Background task to record AMS humidity and temperature data."""
  7664. logger = logging.getLogger(__name__)
  7665. # Wait a short time for MQTT connections to establish on startup
  7666. await asyncio.sleep(10)
  7667. while True:
  7668. try:
  7669. from backend.app.models.ams_history import AMSSensorHistory
  7670. from backend.app.models.printer import Printer
  7671. from backend.app.models.settings import Settings
  7672. async with async_session() as db:
  7673. # Get all active printers
  7674. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7675. printers = result.scalars().all()
  7676. # Get alarm thresholds from settings
  7677. humidity_threshold = 60.0 # Default: fair threshold
  7678. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  7679. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  7680. setting = result.scalar_one_or_none()
  7681. if setting:
  7682. try:
  7683. humidity_threshold = float(setting.value)
  7684. except (ValueError, TypeError):
  7685. pass # Keep default threshold if stored value is invalid
  7686. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  7687. setting = result.scalar_one_or_none()
  7688. if setting:
  7689. try:
  7690. temp_fair_threshold = float(setting.value)
  7691. except (ValueError, TypeError):
  7692. pass # Keep default threshold if stored value is invalid
  7693. # The alarm gets its own threshold, seeded from the resolved fair
  7694. # value so an install that has never set one behaves exactly as
  7695. # it did before (#2905). ams_temp_fair decides when the card turns
  7696. # amber; 35 C is a reasonable place to change a colour and not a
  7697. # reasonable place to page someone. A room above it makes the
  7698. # alarm fire once an hour for as long as the weather lasts, and
  7699. # the only way to stop it was to raise the display band and lose
  7700. # the colour that says the unit is warm.
  7701. #
  7702. # An unset value is stored as the literal "None", which the except
  7703. # below swallows the same way it swallows garbage -- so the
  7704. # fallback costs nothing and needs no sentinel of its own.
  7705. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  7706. setting = result.scalar_one_or_none()
  7707. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  7708. temp_fair_threshold, setting.value if setting else None
  7709. )
  7710. # Per-filament humidity threshold overrides (#1605) — resolved
  7711. # per-AMS below from the loaded tray types. Reuses the same
  7712. # resolver as the auto-drying scheduler so behavior stays in
  7713. # lockstep across both consumers.
  7714. from backend.app.services.print_scheduler import PrintScheduler
  7715. per_type_humidity_thresholds: dict[str, int] = {}
  7716. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  7717. setting = result.scalar_one_or_none()
  7718. if setting and setting.value:
  7719. try:
  7720. raw = json.loads(setting.value)
  7721. if isinstance(raw, dict):
  7722. for k, v in raw.items():
  7723. try:
  7724. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  7725. v
  7726. )
  7727. except (TypeError, ValueError):
  7728. continue
  7729. except (ValueError, TypeError):
  7730. pass # Invalid JSON → no overrides, fall through to global threshold
  7731. # Per-AMS drying latch (#1802), loaded once per pass and written
  7732. # back below only if a unit changed it.
  7733. drying_latch = await _load_ams_drying_latch(db)
  7734. drying_latch_before = dict(drying_latch)
  7735. recorded_count = 0
  7736. for printer in printers:
  7737. # Get current state from printer manager
  7738. state = printer_manager.get_status(printer.id)
  7739. if not state or not state.connected or not state.raw_data:
  7740. continue # Skip disconnected printers - don't use stale data
  7741. raw_data = state.raw_data
  7742. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  7743. continue
  7744. # Record data for each AMS unit
  7745. for ams_data in raw_data["ams"]:
  7746. ams_id = int(ams_data.get("id", 0))
  7747. # Percentage only. The 1-5 index is inverted, so
  7748. # charting it as a percentage drew the wettest units as
  7749. # the driest (#3140); a unit that reports no percentage
  7750. # leaves a gap in the chart instead. See
  7751. # utils/ams_humidity.
  7752. humidity = ams_humidity_percent(ams_data)
  7753. # No supported printer is known to send the index
  7754. # alone -- the report came from unsupported firmware,
  7755. # and no install has been seen using the old fallback.
  7756. # "Known" is doing work there, so say so once per unit:
  7757. # the alternative is a silent blank card.
  7758. if humidity is None and ams_data.get("humidity") is not None:
  7759. unit_key = (printer.id, ams_id)
  7760. if unit_key not in _ams_index_only_logged:
  7761. _ams_index_only_logged.add(unit_key)
  7762. logger.info(
  7763. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  7764. "percentage. The index is inverted and is not shown as a percentage "
  7765. "(#3140), so this unit has no humidity reading, chart or alarm. "
  7766. "Please report this with the printer and AMS firmware versions.",
  7767. printer.name,
  7768. ams_id,
  7769. )
  7770. # Get temperature
  7771. temperature = None
  7772. temp_str = ams_data.get("temp")
  7773. if temp_str is not None:
  7774. try:
  7775. temperature = float(temp_str)
  7776. except (ValueError, TypeError):
  7777. pass # Skip unparseable temperature value
  7778. # Skip if no data
  7779. if humidity is None and temperature is None:
  7780. continue
  7781. # Record the data point
  7782. history = AMSSensorHistory(
  7783. printer_id=printer.id,
  7784. ams_id=ams_id,
  7785. humidity=humidity,
  7786. # Both columns hold the same reading now that the
  7787. # index can no longer reach ``humidity``. Writing it
  7788. # through the same value also stops a genuine 0%
  7789. # from being stored as NULL, which the old truthiness
  7790. # test did.
  7791. humidity_raw=humidity,
  7792. temperature=temperature,
  7793. )
  7794. db.add(history)
  7795. recorded_count += 1
  7796. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  7797. is_ams_ht = ams_id >= 128
  7798. if is_ams_ht:
  7799. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  7800. else:
  7801. ams_label = f"AMS-{chr(65 + ams_id)}"
  7802. # Skip alarm dispatch for empty AMS units — humidity /
  7803. # temperature readings are ambient with no filament to
  7804. # protect, and the hourly notification just becomes
  7805. # noise. Sensor history was already recorded above so
  7806. # the UI charts stay continuous (#1619). Per-AMS check
  7807. # so a multi-AMS setup with one loaded + one empty
  7808. # still alarms on the loaded unit.
  7809. if not _ams_has_filament(ams_data):
  7810. continue
  7811. # Resolve per-filament humidity threshold for this AMS
  7812. # unit (#1605). Falls back to the global ams_humidity_fair
  7813. # when no per-type overrides are configured.
  7814. trays = ams_data.get("tray", []) or []
  7815. effective_humidity_threshold = float(
  7816. PrintScheduler.resolve_humidity_threshold(
  7817. trays, per_type_humidity_thresholds, int(humidity_threshold)
  7818. )
  7819. )
  7820. # Check humidity alarm (only if above threshold)
  7821. if humidity is not None and humidity > effective_humidity_threshold:
  7822. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  7823. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7824. now = datetime.now(timezone.utc)
  7825. if (
  7826. last_alarm is None
  7827. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7828. ):
  7829. _ams_alarm_cooldown[cooldown_key] = now
  7830. logger.info(
  7831. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  7832. )
  7833. try:
  7834. # Call different notification method based on AMS type
  7835. if is_ams_ht:
  7836. await notification_service.on_ams_ht_humidity_high(
  7837. printer.id,
  7838. printer.name,
  7839. ams_label,
  7840. humidity,
  7841. effective_humidity_threshold,
  7842. db,
  7843. )
  7844. else:
  7845. await notification_service.on_ams_humidity_high(
  7846. printer.id,
  7847. printer.name,
  7848. ams_label,
  7849. humidity,
  7850. effective_humidity_threshold,
  7851. db,
  7852. )
  7853. except Exception as e:
  7854. logger.warning("Failed to send humidity alarm: %s", e)
  7855. # A drying cycle heats the unit far past ams_temp_fair on
  7856. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  7857. # AMS-HT, against a 35 C default — so the alarm fired
  7858. # once an hour for the whole cycle and kept firing while
  7859. # the unit cooled back down (#1802). Latch on the
  7860. # firmware's own drying state and hold until the reading
  7861. # returns to normal. Humidity is deliberately left alone:
  7862. # it falls during drying, which is the whole point.
  7863. latch_key = f"{printer.id}:{ams_id}"
  7864. # The latch releases at `threshold`, so it takes the alarm
  7865. # number too. Handing it the display band would strand the
  7866. # latch on any unit that settles back above it -- a room
  7867. # where the AMS rests at 37.7 C never returns under a 35 C
  7868. # band, so the latch could only expire on the grace cap
  7869. # rather than releasing when the unit had actually cooled.
  7870. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  7871. drying_active=is_drying_active(ams_data),
  7872. temperature=temperature,
  7873. threshold=temp_alarm_threshold,
  7874. latched_at=drying_latch.get(latch_key),
  7875. now=datetime.now(timezone.utc),
  7876. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  7877. )
  7878. if new_latch is None:
  7879. drying_latch.pop(latch_key, None)
  7880. else:
  7881. drying_latch[latch_key] = new_latch
  7882. # Check temperature alarm (only if above threshold)
  7883. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  7884. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  7885. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7886. now = datetime.now(timezone.utc)
  7887. if (
  7888. last_alarm is None
  7889. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7890. ):
  7891. _ams_alarm_cooldown[cooldown_key] = now
  7892. logger.info(
  7893. f"Sending temperature alarm for {printer.name} {ams_label}: "
  7894. f"{temperature}°C > {temp_alarm_threshold}°C"
  7895. )
  7896. try:
  7897. # Call different notification method based on AMS type
  7898. if is_ams_ht:
  7899. # The reported threshold has to be the one
  7900. # that fired, or the message says "> 35 °C"
  7901. # while firing at 45.
  7902. await notification_service.on_ams_ht_temperature_high(
  7903. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7904. )
  7905. else:
  7906. await notification_service.on_ams_temperature_high(
  7907. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7908. )
  7909. except Exception as e:
  7910. logger.warning("Failed to send temperature alarm: %s", e)
  7911. if drying_latch != drying_latch_before:
  7912. await _save_ams_drying_latch(db, drying_latch)
  7913. await db.commit()
  7914. if recorded_count > 0:
  7915. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  7916. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  7917. global _ams_cleanup_counter
  7918. _ams_cleanup_counter += 1
  7919. if _ams_cleanup_counter >= 288:
  7920. _ams_cleanup_counter = 0
  7921. # Get retention days from settings
  7922. from backend.app.models.settings import Settings
  7923. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  7924. setting = result.scalar_one_or_none()
  7925. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  7926. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7927. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  7928. await db.commit()
  7929. if result.rowcount > 0:
  7930. logger.info(
  7931. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  7932. )
  7933. # Wait until next recording interval
  7934. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  7935. except asyncio.CancelledError:
  7936. break
  7937. except Exception as e:
  7938. logger.warning("AMS history recording failed: %s", e)
  7939. await asyncio.sleep(60) # Wait a bit before retrying
  7940. def start_ams_history_recording():
  7941. """Start the AMS history recording background task."""
  7942. global _ams_history_task
  7943. if _ams_history_task is None:
  7944. _ams_history_task = asyncio.create_task(record_ams_history())
  7945. logging.getLogger(__name__).info("AMS history recording started")
  7946. def stop_ams_history_recording():
  7947. """Stop the AMS history recording background task."""
  7948. global _ams_history_task
  7949. if _ams_history_task:
  7950. _ams_history_task.cancel()
  7951. _ams_history_task = None
  7952. logging.getLogger(__name__).info("AMS history recording stopped")
  7953. # Printer sensor history recording (nozzle / bed / chamber)
  7954. _printer_sensor_history_task: asyncio.Task | None = None
  7955. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  7956. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  7957. _printer_sensor_cleanup_counter = 0
  7958. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  7959. # MQTT parser writes, so we don't need to handle per-model field aliases here
  7960. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  7961. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  7962. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  7963. _SENSOR_TARGET_KEYS = {
  7964. "nozzle": "nozzle_target",
  7965. "nozzle_2": "nozzle_2_target",
  7966. "bed": "bed_target",
  7967. "chamber": "chamber_target",
  7968. }
  7969. async def record_printer_sensor_history():
  7970. """Background task to record nozzle / bed / chamber readings.
  7971. Pulls from `state.temperatures` (already normalised across all printer
  7972. models by the MQTT parser) rather than re-parsing raw_data, so we get
  7973. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  7974. """
  7975. logger = logging.getLogger(__name__)
  7976. await asyncio.sleep(10)
  7977. while True:
  7978. try:
  7979. from backend.app.models.printer import Printer
  7980. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  7981. from backend.app.models.settings import Settings
  7982. async with async_session() as db:
  7983. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7984. printers = result.scalars().all()
  7985. recorded_count = 0
  7986. for printer in printers:
  7987. state = printer_manager.get_status(printer.id)
  7988. if not state or not state.connected:
  7989. continue
  7990. temps = getattr(state, "temperatures", None) or {}
  7991. if not isinstance(temps, dict):
  7992. continue
  7993. for kind in _SENSOR_KINDS:
  7994. if kind not in temps:
  7995. continue
  7996. try:
  7997. value = float(temps[kind])
  7998. except (ValueError, TypeError):
  7999. continue
  8000. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8001. target_val: float | None = None
  8002. if target_raw is not None:
  8003. try:
  8004. target_val = float(target_raw)
  8005. except (ValueError, TypeError):
  8006. target_val = None
  8007. db.add(
  8008. PrinterSensorHistory(
  8009. printer_id=printer.id,
  8010. sensor_kind=kind,
  8011. value=value,
  8012. target=target_val,
  8013. )
  8014. )
  8015. recorded_count += 1
  8016. await db.commit()
  8017. if recorded_count > 0:
  8018. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8019. # Periodic cleanup — once every ~24h at this interval.
  8020. global _printer_sensor_cleanup_counter
  8021. _printer_sensor_cleanup_counter += 1
  8022. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8023. if _printer_sensor_cleanup_counter >= cleanup_every:
  8024. _printer_sensor_cleanup_counter = 0
  8025. result = await db.execute(
  8026. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8027. )
  8028. setting = result.scalar_one_or_none()
  8029. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8030. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8031. cleanup = await db.execute(
  8032. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8033. )
  8034. await db.commit()
  8035. if cleanup.rowcount > 0:
  8036. logger.info(
  8037. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8038. cleanup.rowcount,
  8039. retention_days,
  8040. )
  8041. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8042. except asyncio.CancelledError:
  8043. break
  8044. except Exception as e:
  8045. logger.warning("Printer sensor history recording failed: %s", e)
  8046. await asyncio.sleep(60)
  8047. def start_printer_sensor_history_recording():
  8048. global _printer_sensor_history_task
  8049. if _printer_sensor_history_task is None:
  8050. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8051. logging.getLogger(__name__).info("Printer sensor history recording started")
  8052. def stop_printer_sensor_history_recording():
  8053. global _printer_sensor_history_task
  8054. if _printer_sensor_history_task:
  8055. _printer_sensor_history_task.cancel()
  8056. _printer_sensor_history_task = None
  8057. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8058. # Printer runtime tracking
  8059. _runtime_tracking_task: asyncio.Task | None = None
  8060. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8061. async def track_printer_runtime():
  8062. """Background task to track printer active runtime (RUNNING state only).
  8063. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8064. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8065. which track mechanical wear. Pause time has no motion and no wear, so
  8066. counting it inflates maintenance warnings (#1521).
  8067. """
  8068. logger = logging.getLogger(__name__)
  8069. # Wait for MQTT connections to establish on startup
  8070. await asyncio.sleep(15)
  8071. while True:
  8072. try:
  8073. from backend.app.models.printer import Printer
  8074. # Fetch printer IDs in a short-lived read-only session
  8075. async with async_session() as db:
  8076. result = await db.execute(
  8077. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8078. Printer.is_active.is_(True)
  8079. )
  8080. )
  8081. printer_rows = result.all()
  8082. now = datetime.now(timezone.utc)
  8083. updated_count = 0
  8084. # Update each printer in its own short session to minimise write-lock
  8085. # hold time and avoid blocking critical commits like queue status
  8086. # updates (#897).
  8087. for pid, pname, runtime_secs, last_update in printer_rows:
  8088. state = printer_manager.get_status(pid)
  8089. if not state:
  8090. logger.debug("[%s] Runtime tracking: no state available", pname)
  8091. continue
  8092. if not state.connected:
  8093. logger.debug("[%s] Runtime tracking: not connected", pname)
  8094. continue
  8095. needs_commit = False
  8096. new_runtime = runtime_secs
  8097. new_last_update = last_update
  8098. if state.state == "RUNNING":
  8099. if last_update:
  8100. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8101. elapsed = (now - lu).total_seconds()
  8102. if elapsed > 0:
  8103. new_runtime = runtime_secs + int(elapsed)
  8104. updated_count += 1
  8105. needs_commit = True
  8106. logger.debug(
  8107. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8108. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8109. )
  8110. else:
  8111. needs_commit = True
  8112. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8113. new_last_update = now
  8114. else:
  8115. if last_update is not None:
  8116. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8117. new_last_update = None
  8118. needs_commit = True
  8119. if needs_commit:
  8120. try:
  8121. async with async_session() as db:
  8122. result = await db.execute(select(Printer).where(Printer.id == pid))
  8123. printer = result.scalar_one_or_none()
  8124. if printer:
  8125. printer.runtime_seconds = new_runtime
  8126. printer.last_runtime_update = new_last_update
  8127. await db.commit()
  8128. except Exception as e:
  8129. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8130. if updated_count > 0:
  8131. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8132. except asyncio.CancelledError:
  8133. logger.info("Runtime tracking cancelled")
  8134. break
  8135. except Exception as e:
  8136. logger.warning("Runtime tracking failed: %s", e)
  8137. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8138. def start_runtime_tracking():
  8139. """Start the printer runtime tracking background task."""
  8140. global _runtime_tracking_task
  8141. if _runtime_tracking_task is None:
  8142. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8143. logging.getLogger(__name__).info("Printer runtime tracking started")
  8144. def stop_runtime_tracking():
  8145. """Stop the printer runtime tracking background task."""
  8146. global _runtime_tracking_task
  8147. if _runtime_tracking_task:
  8148. _runtime_tracking_task.cancel()
  8149. _runtime_tracking_task = None
  8150. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8151. # SpoolBuddy device watchdog
  8152. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8153. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8154. async def _spoolbuddy_watchdog_loop():
  8155. """Periodic check for SpoolBuddy devices that have gone offline."""
  8156. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8157. while True:
  8158. try:
  8159. await spoolbuddy_watchdog()
  8160. except asyncio.CancelledError:
  8161. break
  8162. except Exception as e:
  8163. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8164. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8165. def start_spoolbuddy_watchdog():
  8166. global _spoolbuddy_watchdog_task
  8167. if _spoolbuddy_watchdog_task is None:
  8168. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8169. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8170. def stop_spoolbuddy_watchdog():
  8171. global _spoolbuddy_watchdog_task
  8172. if _spoolbuddy_watchdog_task:
  8173. _spoolbuddy_watchdog_task.cancel()
  8174. _spoolbuddy_watchdog_task = None
  8175. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8176. # Dead-MQTT-session recovery
  8177. #
  8178. # check_staleness() covers the "connected but silent" half-broken session. It
  8179. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8180. # is the only thing left watching at that point. When paho stops making
  8181. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8182. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8183. # offline with the UI open the whole time, recovered only when something
  8184. # happened to nudge it.
  8185. #
  8186. # This loop is that backstop. It only touches printers that had a working
  8187. # session and lost it, and only when the MQTT port still answers — a printer
  8188. # that is simply switched off is left to paho, since rebuilding a client
  8189. # against an unreachable host achieves nothing and would fill the log every
  8190. # night.
  8191. _connection_watchdog_task: asyncio.Task | None = None
  8192. CONNECTION_WATCHDOG_INTERVAL = 60
  8193. # How long a printer must have been silent before we stop trusting paho.
  8194. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8195. # so a session that is recovering on its own is never interrupted.
  8196. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8197. # Per-printer floor between rebuild attempts.
  8198. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8199. _connection_watchdog_last_attempt: dict[int, float] = {}
  8200. async def _recover_dead_printer_sessions() -> int:
  8201. """Rebuild MQTT clients that have been offline too long to still be trying.
  8202. Returns the number of printers a rebuild was attempted for (for tests and
  8203. for the caller's logging). Never raises: one unreachable printer must not
  8204. stop the sweep for the rest of the farm.
  8205. """
  8206. logger = logging.getLogger(__name__)
  8207. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8208. now = time.monotonic()
  8209. recovered = 0
  8210. for printer_id, client in list(printer_manager._clients.items()):
  8211. try:
  8212. if client.state.connected:
  8213. _connection_watchdog_last_attempt.pop(printer_id, None)
  8214. continue
  8215. # Time since the last inbound message is the age of the last known
  8216. # good session — no extra bookkeeping needed, and it is the same
  8217. # clock is_stale() reads. 0 means this client has never had one:
  8218. # that is the initial-connect path, where paho retrying is the
  8219. # correct and only behaviour, so leave it be.
  8220. last_msg = client._last_message_time
  8221. if not last_msg:
  8222. continue
  8223. offline_for = time.time() - last_msg
  8224. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8225. continue
  8226. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8227. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8228. continue
  8229. if not await check_port(client.ip_address, PORT_MQTT):
  8230. # Switched off, unplugged, or off the network. Paho's retry is
  8231. # the right handler; say so at debug level and move on.
  8232. logger.debug(
  8233. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8234. "— leaving the reconnect to paho",
  8235. printer_id,
  8236. offline_for,
  8237. )
  8238. _connection_watchdog_last_attempt[printer_id] = now
  8239. continue
  8240. _connection_watchdog_last_attempt[printer_id] = now
  8241. recovered += 1
  8242. logger.warning(
  8243. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8244. "rebuilding the client with a fresh session (last connect error: %s)",
  8245. printer_id,
  8246. offline_for,
  8247. PORT_MQTT,
  8248. client.last_connect_error or "none recorded",
  8249. )
  8250. # Async context, so this takes the hard-reset path: fresh client_id,
  8251. # paho's QoS 1 queue dropped. That matters — a project_file left
  8252. # unacked on the dead session would otherwise replay into the new
  8253. # one and trip 0500_4003 on the printer (#1136).
  8254. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8255. except Exception as e:
  8256. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8257. return recovered
  8258. async def _connection_watchdog_loop():
  8259. logger = logging.getLogger(__name__)
  8260. # Let the initial connects settle before judging anyone offline.
  8261. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8262. while True:
  8263. try:
  8264. await _recover_dead_printer_sessions()
  8265. except asyncio.CancelledError:
  8266. break
  8267. except Exception as e:
  8268. logger.warning("Connection watchdog sweep failed: %s", e)
  8269. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8270. def start_connection_watchdog():
  8271. global _connection_watchdog_task
  8272. if _connection_watchdog_task is None:
  8273. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8274. logging.getLogger(__name__).info("Printer connection watchdog started")
  8275. def stop_connection_watchdog():
  8276. global _connection_watchdog_task
  8277. if _connection_watchdog_task:
  8278. _connection_watchdog_task.cancel()
  8279. _connection_watchdog_task = None
  8280. _connection_watchdog_last_attempt.clear()
  8281. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8282. # Camera stream orphan cleanup
  8283. _camera_cleanup_task: asyncio.Task | None = None
  8284. CAMERA_CLEANUP_INTERVAL = 60
  8285. async def _camera_cleanup_loop():
  8286. """Periodically clean up orphaned ffmpeg processes."""
  8287. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8288. while True:
  8289. try:
  8290. await cleanup_orphaned_streams()
  8291. except asyncio.CancelledError:
  8292. break
  8293. except Exception as e:
  8294. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8295. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8296. def start_camera_cleanup():
  8297. global _camera_cleanup_task
  8298. if _camera_cleanup_task is None:
  8299. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8300. logging.getLogger(__name__).info("Camera stream cleanup started")
  8301. def stop_camera_cleanup():
  8302. global _camera_cleanup_task
  8303. if _camera_cleanup_task:
  8304. _camera_cleanup_task.cancel()
  8305. _camera_cleanup_task = None
  8306. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8307. # ---------------------------------------------------------------------------
  8308. # Expected-print TTL eviction
  8309. # ---------------------------------------------------------------------------
  8310. def _evict_stale_expected_prints() -> None:
  8311. """Remove entries from _expected_prints / _expected_print_creators that are
  8312. older than _EXPECTED_PRINT_TTL_SECONDS.
  8313. This prevents unbounded growth when a print is registered (via
  8314. register_expected_print) but on_print_start never fires — e.g. because the
  8315. printer disconnects, the app restarts, or the print is started directly from
  8316. the printer panel without going through the queue.
  8317. """
  8318. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8319. # (e.g. NTP sync, DST changes).
  8320. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8321. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8322. if not stale_keys:
  8323. return
  8324. evicted_archive_ids: set[int] = set()
  8325. for key in stale_keys:
  8326. archive_id = _expected_prints.pop(key, None)
  8327. if archive_id is not None:
  8328. evicted_archive_ids.add(archive_id)
  8329. _expected_print_creators.pop(key, None)
  8330. _expected_print_registered_at.pop(key, None)
  8331. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8332. # that have no remaining live keys in _expected_prints (all variants
  8333. # were just evicted).
  8334. live_archive_ids = set(_expected_prints.values())
  8335. for archive_id in evicted_archive_ids:
  8336. if archive_id not in live_archive_ids:
  8337. _print_ams_mappings.pop(archive_id, None)
  8338. _print_cost_center_ids.pop(archive_id, None)
  8339. _print_plate_ids.pop(archive_id, None)
  8340. logging.getLogger(__name__).info(
  8341. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8342. )
  8343. async def _expected_prints_cleanup_loop() -> None:
  8344. """Background task: periodically evict stale expected-print entries."""
  8345. while True:
  8346. try:
  8347. _evict_stale_expected_prints()
  8348. except asyncio.CancelledError:
  8349. raise
  8350. except Exception as e:
  8351. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8352. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8353. def start_expected_prints_cleanup() -> None:
  8354. global _expected_prints_cleanup_task
  8355. if _expected_prints_cleanup_task is None:
  8356. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8357. logging.getLogger(__name__).info("Expected prints cleanup started")
  8358. def stop_expected_prints_cleanup() -> None:
  8359. global _expected_prints_cleanup_task
  8360. if _expected_prints_cleanup_task:
  8361. _expected_prints_cleanup_task.cancel()
  8362. _expected_prints_cleanup_task = None
  8363. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8364. # ---------------------------------------------------------------------------
  8365. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8366. # ---------------------------------------------------------------------------
  8367. _auth_cleanup_task: asyncio.Task | None = None
  8368. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8369. async def _run_auth_cleanup() -> None:
  8370. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8371. from backend.app.core.database import async_session
  8372. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8373. from backend.app.models.user_totp import UserTOTP
  8374. now = datetime.now(timezone.utc)
  8375. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8376. try:
  8377. async with async_session() as db:
  8378. stale_cutoff = now - timedelta(hours=1)
  8379. result = await db.execute(
  8380. select(UserTOTP).where(
  8381. UserTOTP.is_enabled.is_(False),
  8382. UserTOTP.created_at < stale_cutoff,
  8383. )
  8384. )
  8385. stale_records = result.scalars().all()
  8386. if stale_records:
  8387. for rec in stale_records:
  8388. await db.delete(rec)
  8389. await db.commit()
  8390. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8391. except Exception as e:
  8392. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8393. # Remove expired revoked-JTI entries (they are no longer needed once the
  8394. # original token's exp has passed — the token would be rejected by JWT
  8395. # signature verification regardless).
  8396. try:
  8397. async with async_session() as db:
  8398. await db.execute(
  8399. delete(AuthEphemeralToken).where(
  8400. AuthEphemeralToken.token_type == "revoked_jti",
  8401. AuthEphemeralToken.expires_at < now,
  8402. )
  8403. )
  8404. await db.commit()
  8405. except Exception as e:
  8406. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8407. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8408. # Events outside this window can never affect rate-limit decisions — they only
  8409. # consume DB space. Use the same window constant as the rate limiter so the
  8410. # two are always in sync.
  8411. try:
  8412. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8413. async with async_session() as db:
  8414. await db.execute(
  8415. delete(AuthRateLimitEvent).where(
  8416. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8417. )
  8418. )
  8419. await db.commit()
  8420. except Exception as e:
  8421. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8422. async def _auth_cleanup_loop() -> None:
  8423. """Periodic background task: run auth cleanup every hour."""
  8424. while True:
  8425. try:
  8426. await _run_auth_cleanup()
  8427. except asyncio.CancelledError:
  8428. break
  8429. except Exception as e:
  8430. logging.warning("Auth cleanup loop error: %s", e)
  8431. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8432. def start_auth_cleanup() -> None:
  8433. global _auth_cleanup_task
  8434. if _auth_cleanup_task is None:
  8435. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8436. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8437. def stop_auth_cleanup() -> None:
  8438. global _auth_cleanup_task
  8439. if _auth_cleanup_task:
  8440. _auth_cleanup_task.cancel()
  8441. _auth_cleanup_task = None
  8442. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8443. @asynccontextmanager
  8444. async def lifespan(app: FastAPI):
  8445. # Startup
  8446. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8447. # anything else can spawn tasks that might trip it.
  8448. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8449. install_proactor_reset_filter()
  8450. # Before init_db, so the warning is near the top of the log rather than
  8451. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8452. warn_if_running_on_uvloop()
  8453. await init_db()
  8454. # Browser download tokens expire after five minutes. Remove abandoned
  8455. # prepared ZIPs at startup as well as before each new preparation so a
  8456. # quiet appliance cannot retain an unusable bundle indefinitely.
  8457. try:
  8458. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8459. await prune_stale_printer_file_bundles()
  8460. except Exception as exc:
  8461. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8462. # After migrations, so the is_env_managed column exists. Never raises --
  8463. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8464. # startup (see apply_env_oidc_provider).
  8465. from backend.app.core.oidc_env import apply_env_oidc_provider
  8466. async with async_session() as oidc_db:
  8467. await apply_env_oidc_provider(oidc_db)
  8468. # Close out batches that finished before `completed` was a reachable status
  8469. # (#342). Without this the Batches tab opens on every batch created since
  8470. # the feature shipped, all still marked active. Never blocks startup.
  8471. try:
  8472. from backend.app.services.print_batch import backfill_batch_statuses
  8473. async with async_session() as batch_db:
  8474. await backfill_batch_statuses(batch_db)
  8475. except Exception as exc:
  8476. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8477. # Register an app-scoped httpx client for Bambu Cloud services so
  8478. # per-request BambuCloudService instances reuse the same connection pool
  8479. # (important for routes like /cloud/filament-info that chain many
  8480. # get_setting_detail calls). The shared client stores no region/token
  8481. # state, so the per-request ownership pattern that fixed the region-bleed
  8482. # bug is preserved.
  8483. import httpx as _httpx
  8484. from backend.app.services.bambu_cloud import set_shared_http_client
  8485. from backend.app.services.model_providers.makerworld.service import (
  8486. set_shared_http_client as set_shared_makerworld_http_client,
  8487. )
  8488. from backend.app.services.orca_cloud import (
  8489. set_shared_http_client as set_shared_orca_http_client,
  8490. )
  8491. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8492. set_shared_http_client(_shared_cloud_http_client)
  8493. # Reuse the same connection pool for MakerWorld — different host, same
  8494. # keep-alive pool saves a TLS handshake per request.
  8495. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8496. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8497. # each spun up (and never closed) its own client, leaking sockets.
  8498. set_shared_orca_http_client(_shared_cloud_http_client)
  8499. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8500. # This can happen when a print was cancelled mid-print on versions before this fix.
  8501. try:
  8502. async with async_session() as db:
  8503. from backend.app.models.print_queue import PrintQueueItem
  8504. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8505. aborted_items = result.scalars().all()
  8506. if aborted_items:
  8507. for item in aborted_items:
  8508. item.status = "cancelled"
  8509. await db.commit()
  8510. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8511. except Exception as e:
  8512. logging.warning("Failed to fix aborted queue items: %s", e)
  8513. # Restore debug logging state from previous session
  8514. await init_debug_logging()
  8515. # Set up printer manager callbacks
  8516. loop = asyncio.get_event_loop()
  8517. printer_manager.set_event_loop(loop)
  8518. printer_manager.set_status_change_callback(on_printer_status_change)
  8519. printer_manager.set_print_start_callback(on_print_start)
  8520. printer_manager.set_print_complete_callback(on_print_complete)
  8521. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8522. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8523. printer_manager.set_ams_change_callback(on_ams_change)
  8524. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8525. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8526. await printer_manager.load_awaiting_plate_clear_from_db()
  8527. # Layer change callback for external camera timelapse
  8528. async def on_layer_change(printer_id: int, layer_num: int):
  8529. """Capture timelapse frame on layer change + first layer notification."""
  8530. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8531. await tl_layer_change(printer_id, layer_num)
  8532. # #1867: bank a recent in-print frame so the finish-photo path has a
  8533. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8534. # #2547 added `on_print_progress` as a second driver — this one alone
  8535. # stops firing once the final layer begins.
  8536. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8537. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8538. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8539. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8540. # nozzle clean), so a bare layer_num check can fire minutes before the
  8541. # first real extrusion. We require gcode_state == RUNNING and
  8542. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8543. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8544. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8545. # edge fires later; _first_layer_notified stays clear until we actually send
  8546. # so a deferred re-evaluation can win. See issue #1837.
  8547. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8548. client = printer_manager.get_client(printer_id)
  8549. state = client.state if client else None
  8550. if not state or state.state != "RUNNING":
  8551. return
  8552. if state.mc_print_sub_stage not in (None, 0):
  8553. return
  8554. _first_layer_notified[printer_id] = True
  8555. try:
  8556. async with async_session() as db:
  8557. from backend.app.models.printer import Printer
  8558. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8559. printer = result.scalar_one_or_none()
  8560. if not printer:
  8561. return
  8562. printer_name = printer.name
  8563. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8564. total_layers = state.total_layers if state else 0
  8565. image_data = await _capture_snapshot_for_notification(
  8566. printer_id, printer, logging.getLogger(__name__)
  8567. )
  8568. await notification_service.on_first_layer_complete(
  8569. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8570. )
  8571. except Exception as e:
  8572. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8573. printer_manager.set_layer_change_callback(on_layer_change)
  8574. async def on_print_progress(printer_id: int, percent: int):
  8575. """#2547: keep the in-print frame bank fresh through the final layer.
  8576. `on_layer_change` stops the moment the last layer starts, which on the
  8577. H2C capture that closed #2547 left the bank stale for the three minutes
  8578. that layer took. Progress is the only field that keeps advancing there,
  8579. and it freezes before the End G-code runs — so banking on it stays
  8580. inside the print and never sees a swapped plate.
  8581. """
  8582. client = printer_manager.get_client(printer_id)
  8583. state = client.state if client else None
  8584. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8585. printer_manager.set_print_progress_callback(on_print_progress)
  8586. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8587. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8588. waiter = _bed_cool_waiters.get(printer_id)
  8589. if not waiter:
  8590. return
  8591. threshold = waiter["threshold"]
  8592. if bed_temp > threshold:
  8593. return
  8594. # Bed is at or below threshold — fire notification and remove waiter
  8595. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8596. if not waiter_info:
  8597. return # Another callback already handled it
  8598. bed_cool_logger = logging.getLogger(__name__)
  8599. bed_cool_logger.info(
  8600. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8601. bed_temp,
  8602. printer_id,
  8603. threshold,
  8604. )
  8605. try:
  8606. printer_info = printer_manager.get_printer(printer_id)
  8607. p_name = printer_info.name if printer_info else "Unknown"
  8608. async with async_session() as db:
  8609. await notification_service.on_bed_cooled(
  8610. printer_id=printer_id,
  8611. printer_name=p_name,
  8612. bed_temp=bed_temp,
  8613. threshold=threshold,
  8614. filename=waiter_info["filename"],
  8615. db=db,
  8616. )
  8617. except Exception as e:
  8618. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8619. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8620. async def on_drying_complete(printer_id: int, ams_id: int):
  8621. """Smart-plug auto-off-after-drying trigger (#1349).
  8622. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8623. manager walks all plugs linked to this printer and turns off only
  8624. the ones with ``auto_off_after_drying`` enabled, after their
  8625. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8626. dual-AMS dry that ends within the same MQTT push) call this once
  8627. per unit — the manager's ``_cancel_pending_off`` collapses
  8628. repeated scheduling on the same plug to one timer, so duplicate
  8629. fires are safe.
  8630. """
  8631. try:
  8632. async with async_session() as db:
  8633. await smart_plug_manager.on_drying_complete(printer_id, db)
  8634. except Exception as e:
  8635. logging.getLogger(__name__).warning(
  8636. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8637. printer_id,
  8638. ams_id,
  8639. e,
  8640. )
  8641. printer_manager.set_drying_complete_callback(on_drying_complete)
  8642. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  8643. """Surface the read-back result of a spool assignment to the UI (#2582).
  8644. The MQTT client confirms (or fails to confirm) that the tray telemetry
  8645. echoed back the filament id we pushed. We relay that as a websocket
  8646. event so the frontend can toast "loaded" / "assignment didn't take"
  8647. instead of the historic silent fire-and-forget, which made the
  8648. AMS→Studio hand-off feel random to users.
  8649. """
  8650. try:
  8651. from backend.app.services.spool_assignment_notifications import (
  8652. _slot_label_from_global_tray,
  8653. )
  8654. if ams_id == 255:
  8655. global_id = 254 + tray_id
  8656. elif ams_id >= 128:
  8657. global_id = ams_id
  8658. else:
  8659. global_id = ams_id * 4 + tray_id
  8660. slot_label = _slot_label_from_global_tray(global_id)
  8661. printer_info = printer_manager.get_printer(printer_id)
  8662. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8663. await ws_manager.broadcast(
  8664. {
  8665. "type": "spool_assignment_verified",
  8666. "printer_id": printer_id,
  8667. "printer_name": printer_name,
  8668. "ams_id": ams_id,
  8669. "tray_id": tray_id,
  8670. "slot": slot_label,
  8671. "verified": verified,
  8672. # Present on success: False means the filament setting landed
  8673. # but the K-profile (cali_idx) did not — the reporter's exact
  8674. # "loaded but no flow profile" symptom.
  8675. "kprofile_applied": detail.get("kprofile_applied", True),
  8676. # Present on failure: whether any tray telemetry was seen in
  8677. # the window (distinguishes "printer silent" from "printer
  8678. # stored something else").
  8679. "saw_tray": detail.get("saw_tray", False),
  8680. }
  8681. )
  8682. except Exception as e:
  8683. logging.getLogger(__name__).warning(
  8684. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  8685. printer_id,
  8686. ams_id,
  8687. tray_id,
  8688. e,
  8689. )
  8690. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  8691. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  8692. """Persist a mid-print tray change for completion-time attribution.
  8693. AMS filament backup switches trays without telling the slicer, so the
  8694. tray-change log is the only record of which spool fed which layers.
  8695. Keeping it only in memory meant a restart mid-print charged everything
  8696. to the tray that finished the job.
  8697. """
  8698. try:
  8699. from backend.app.services.usage_tracker import record_tray_change
  8700. async with async_session() as db:
  8701. await record_tray_change(db, printer_id, tray_global, layer_num)
  8702. except Exception as e:
  8703. logging.getLogger(__name__).warning(
  8704. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  8705. printer_id,
  8706. tray_global,
  8707. layer_num,
  8708. e,
  8709. )
  8710. printer_manager.set_tray_change_callback(on_tray_change)
  8711. # Initialize MQTT relay from settings
  8712. async with async_session() as db:
  8713. from backend.app.api.routes.settings import get_setting
  8714. mqtt_settings = {
  8715. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  8716. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  8717. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  8718. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  8719. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  8720. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  8721. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  8722. }
  8723. await mqtt_relay.configure(mqtt_settings)
  8724. # Restore MQTT smart plug subscriptions
  8725. if mqtt_settings.get("mqtt_enabled"):
  8726. from backend.app.models.smart_plug import SmartPlug
  8727. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  8728. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  8729. mqtt_plugs = result.scalars().all()
  8730. restored = 0
  8731. for plug in mqtt_plugs:
  8732. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  8733. restored += 1
  8734. if restored:
  8735. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  8736. # Connect to all active printers
  8737. async with async_session() as db:
  8738. await init_printer_connections(db)
  8739. # Auto-connect to Spoolman if enabled
  8740. async with async_session() as db:
  8741. from backend.app.api.routes.settings import get_setting
  8742. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  8743. spoolman_url = await get_setting(db, "spoolman_url")
  8744. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  8745. try:
  8746. client = await init_spoolman_client(spoolman_url)
  8747. if await client.health_check():
  8748. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  8749. # Ensure the 'tag' extra field exists for RFID/UUID storage
  8750. field_ok = await client.ensure_tag_extra_field()
  8751. if not field_ok:
  8752. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  8753. # Register the BambuStudio slicer-preset fields used by the
  8754. # spool-edit / assign flow. Spoolman rejects PATCHes with
  8755. # unknown extra keys, so these must exist before any update
  8756. # that touches them.
  8757. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  8758. if not await client.ensure_extra_field(field_name):
  8759. logging.warning(
  8760. "Spoolman extra field %r registration failed — "
  8761. "spool slicer-preset edits will return 502",
  8762. field_name,
  8763. )
  8764. else:
  8765. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  8766. except Exception as e:
  8767. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  8768. # Start the print scheduler
  8769. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  8770. # Start the smart plug scheduler for time-based on/off
  8771. smart_plug_manager.start_scheduler()
  8772. # Start the Home Assistant sensor poller (#1148)
  8773. ha_sensor_manager.start()
  8774. location_ha_sensor_manager.start()
  8775. # Resume any pending auto-offs that were interrupted by restart
  8776. await smart_plug_manager.resume_pending_auto_offs()
  8777. # Start the notification digest scheduler
  8778. notification_service.start_digest_scheduler()
  8779. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  8780. # provider in reactions/both mode; the notification routes resync them.
  8781. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  8782. # until the next provider save, not the whole startup.
  8783. try:
  8784. await telegram_reaction_poller.start()
  8785. except Exception as e:
  8786. logging.warning("Telegram reaction poller did not start: %s", e)
  8787. # Start the GitHub backup scheduler
  8788. await github_backup_service.start_scheduler()
  8789. # Start the local backup scheduler
  8790. await local_backup_service.start_scheduler()
  8791. await obico_detection_service.start()
  8792. # Start the library trash sweeper (#1008)
  8793. await library_trash_service.start_scheduler()
  8794. # Start the archive auto-purge sweeper (#1008 follow-up)
  8795. await archive_purge_service.start_scheduler()
  8796. # Start AMS history recording
  8797. start_ams_history_recording()
  8798. # Start printer sensor (nozzle / bed / chamber) history recording
  8799. start_printer_sensor_history_recording()
  8800. # Start printer runtime tracking
  8801. start_runtime_tracking()
  8802. # Start SpoolBuddy device watchdog
  8803. start_spoolbuddy_watchdog()
  8804. # Start camera stream orphan cleanup
  8805. start_camera_cleanup()
  8806. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  8807. start_connection_watchdog()
  8808. # One-shot sweep for timelapse session directories orphaned by a crash
  8809. # or restart that happened mid-print (in-memory session tracking can't
  8810. # survive that, and nothing else reaps the leftover frames/output file)
  8811. try:
  8812. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  8813. removed = cleanup_orphaned_timelapse_sessions()
  8814. if removed:
  8815. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  8816. except Exception as e:
  8817. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  8818. # Start expected-print TTL eviction (prevents memory leak when prints are
  8819. # registered but on_print_start never fires)
  8820. start_expected_prints_cleanup()
  8821. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  8822. start_auth_cleanup()
  8823. from backend.app.services.printer_media import start_printer_download_cleanup
  8824. start_printer_download_cleanup()
  8825. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  8826. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  8827. from backend.app.services.loop_watchdog import start_loop_watchdog
  8828. start_loop_watchdog()
  8829. # Initialize virtual printer manager and sync from DB
  8830. from backend.app.services.virtual_printer import virtual_printer_manager
  8831. virtual_printer_manager.set_session_factory(async_session)
  8832. virtual_printer_manager.set_printer_manager(printer_manager)
  8833. try:
  8834. await virtual_printer_manager.sync_from_db()
  8835. logging.info("Virtual printer manager synced from database")
  8836. except Exception as e:
  8837. logging.warning("Failed to sync virtual printers: %s", e)
  8838. yield
  8839. # Shutdown
  8840. print_scheduler.stop()
  8841. smart_plug_manager.stop_scheduler()
  8842. ha_sensor_manager.stop()
  8843. location_ha_sensor_manager.stop()
  8844. notification_service.stop_digest_scheduler()
  8845. await telegram_reaction_poller.aclose()
  8846. github_backup_service.stop_scheduler()
  8847. local_backup_service.stop_scheduler()
  8848. library_trash_service.stop_scheduler()
  8849. archive_purge_service.stop_scheduler()
  8850. obico_detection_service.stop()
  8851. stop_ams_history_recording()
  8852. stop_printer_sensor_history_recording()
  8853. stop_runtime_tracking()
  8854. stop_spoolbuddy_watchdog()
  8855. stop_camera_cleanup()
  8856. stop_connection_watchdog()
  8857. from backend.app.services.loop_watchdog import stop_loop_watchdog
  8858. stop_loop_watchdog()
  8859. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  8860. # cleanly rather than waiting on a queue that nothing will ever fill.
  8861. try:
  8862. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  8863. await shutdown_all_broadcasters()
  8864. except Exception as e:
  8865. logging.warning("Failed to shut down camera broadcasters: %s", e)
  8866. stop_expected_prints_cleanup()
  8867. stop_auth_cleanup()
  8868. from backend.app.services.printer_media import stop_printer_download_cleanup
  8869. await stop_printer_download_cleanup()
  8870. printer_manager.disconnect_all()
  8871. slot_unlink_grace.reset()
  8872. await close_spoolman_client()
  8873. # Stop all virtual printer services
  8874. await virtual_printer_manager.stop_all()
  8875. await mqtt_smart_plug_service.disconnect(timeout=2)
  8876. await mqtt_relay.disconnect(timeout=2)
  8877. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  8878. set_shared_http_client(None)
  8879. set_shared_makerworld_http_client(None)
  8880. set_shared_orca_http_client(None)
  8881. await _shared_cloud_http_client.aclose()
  8882. # Checkpoint WAL (SQLite only) and close all database connections
  8883. from backend.app.core.db_dialect import is_sqlite
  8884. if is_sqlite():
  8885. try:
  8886. async with engine.begin() as conn:
  8887. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  8888. logging.info("WAL checkpoint completed")
  8889. except Exception as e:
  8890. logging.warning("WAL checkpoint failed: %s", e)
  8891. await engine.dispose()
  8892. app = FastAPI(
  8893. title=app_settings.app_name,
  8894. description="Archive and manage Bambu Lab 3MF files",
  8895. version=APP_VERSION,
  8896. lifespan=lifespan,
  8897. )
  8898. # =============================================================================
  8899. # Authentication Middleware - Secures ALL API routes by default
  8900. # =============================================================================
  8901. # Public routes that don't require authentication even when auth is enabled
  8902. PUBLIC_API_ROUTES = {
  8903. # Auth routes needed before/during login
  8904. "/api/v1/auth/status",
  8905. "/api/v1/auth/login",
  8906. "/api/v1/auth/setup", # Needed for initial setup and recovery
  8907. # Advanced auth status needed for login page
  8908. "/api/v1/auth/advanced-auth/status",
  8909. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  8910. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  8911. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  8912. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  8913. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  8914. # OIDC routes that must be reachable without a JWT
  8915. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  8916. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  8917. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  8918. # Connected apps: the app's server swaps a code for the user's identity,
  8919. # authenticated by its client secret rather than a login token.
  8920. "/api/v1/connect/token",
  8921. # Version check for updates (no sensitive data)
  8922. "/api/v1/updates/version",
  8923. # Metrics endpoint handles its own prometheus_token authentication
  8924. "/api/v1/metrics",
  8925. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  8926. # this BEFORE a JWT is available to pick up the firstboot wizard's
  8927. # hostname / timezone / locale and the chrony NTP-gate state. The
  8928. # response contains user-set defaults and a public sync flag — no
  8929. # secrets. Without this entry the global auth middleware returns 401
  8930. # before the route handler runs, regardless of the route's own
  8931. # "no auth required" intent.
  8932. "/api/v1/system/appliance",
  8933. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  8934. # authenticates with a long-lived ``camwall``-scoped token in the query
  8935. # string — exactly like the camera streams two lists below, and for the same
  8936. # reason (no header to put a JWT in). "Public" here only means the middleware
  8937. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  8938. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  8939. # plain ``camera_stream`` token does NOT open this door.
  8940. "/api/v1/camwall/printers",
  8941. }
  8942. # Route prefixes that are public (for routes with dynamic segments)
  8943. PUBLIC_API_PREFIXES = [
  8944. # WebSocket connections handle their own auth
  8945. "/api/v1/ws",
  8946. # OIDC authorize redirects — include provider_id in path
  8947. "/api/v1/auth/oidc/authorize/",
  8948. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  8949. # a phone with no session, so no header can carry a JWT — the single-use
  8950. # capability token in the path IS the credential (same reasoning as the
  8951. # /dl/ slicer downloads below). The route grants nothing beyond writing
  8952. # good/reject on the one archive the token was minted for.
  8953. "/api/v1/archives/confirm/",
  8954. ]
  8955. # Route patterns that are public (read-only display data)
  8956. # These are checked with "in path" - needed because browsers load images/videos
  8957. # via <img src> and <video src> which don't include Authorization headers
  8958. PUBLIC_API_PATTERNS = [
  8959. # Thumbnails
  8960. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  8961. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  8962. # Images and media
  8963. "/photos/", # /archives/{id}/photos/{filename}
  8964. "/project-image/", # /archives/{id}/project-image/{path}
  8965. "/qrcode", # /archives/{id}/qrcode
  8966. "/timelapse", # /archives/{id}/timelapse (video)
  8967. "/cover", # /printers/{id}/cover
  8968. "/icon", # /external-links/{id}/icon
  8969. # Camera (streams loaded via <img> tag)
  8970. "/camera/stream", # /printers/{id}/camera/stream
  8971. "/camera/snapshot", # /printers/{id}/camera/snapshot
  8972. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  8973. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  8974. # string (same reasoning as the camera streams above — no header to carry a
  8975. # JWT). "Public" only means the middleware steps aside; the route still runs
  8976. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  8977. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  8978. "/overlay-status", # /printers/{id}/overlay-status
  8979. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  8980. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  8981. # download token in the URL path instead.
  8982. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  8983. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  8984. # and these patterns match by substring. Without its own entry the middleware
  8985. # 401s the slicer's header-less request before the route's token check runs,
  8986. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  8987. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  8988. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  8989. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  8990. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  8991. ]
  8992. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  8993. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  8994. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  8995. Format: comma-separated list of ``scheme://host[:port]`` origins.
  8996. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  8997. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  8998. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  8999. Invalid entries are dropped with a warning rather than failing startup, so
  9000. a typo in one origin doesn't take the whole deployment down.
  9001. """
  9002. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9003. if not raw:
  9004. return ()
  9005. valid: list[str] = []
  9006. for item in raw.split(","):
  9007. candidate = item.strip()
  9008. if not candidate:
  9009. continue
  9010. try:
  9011. parsed = urlparse(candidate)
  9012. except ValueError as e:
  9013. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9014. continue
  9015. if parsed.scheme not in ("http", "https"):
  9016. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9017. continue
  9018. if not parsed.netloc:
  9019. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9020. continue
  9021. if parsed.path and parsed.path != "/":
  9022. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9023. continue
  9024. if parsed.query or parsed.fragment:
  9025. _security_headers_logger.warning(
  9026. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9027. )
  9028. continue
  9029. if "*" in parsed.netloc:
  9030. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9031. continue
  9032. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9033. if valid:
  9034. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9035. return tuple(valid)
  9036. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9037. def _frame_ancestors(default_value: str) -> str:
  9038. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9039. ``default_value`` is the strict directive used when the operator has not
  9040. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9041. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9042. Settings URL builder's preview). When trusted origins
  9043. are configured, ``'self'`` is always included so same-origin embedding never
  9044. breaks even if an operator forgets to add their own origin to the list.
  9045. """
  9046. if _TRUSTED_FRAME_ORIGINS:
  9047. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9048. return f"frame-ancestors {default_value};"
  9049. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9050. # patterns are anchored on the exact emitted name so the relaxed policies
  9051. # below can never apply to any other asset.
  9052. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9053. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9054. # -> /assets/pdf.worker.min-<hash>.js
  9055. # Vite also emits a one-line chunk under the second name that only exports the
  9056. # worker's URL. The page imports it as a module, and a module script is run
  9057. # under the importing document's policy, never its own response's, so it
  9058. # matching as well changes nothing.
  9059. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9060. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9061. @app.middleware("http")
  9062. async def security_headers_middleware(request, call_next):
  9063. """Add standard HTTP security headers to every response."""
  9064. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9065. # changes nothing for Bambuddy's own pages — index.html has no inline
  9066. # scripts since the SW registration moved to /sw-register.js. The reason
  9067. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9068. # script injected into the HTML on the edge, with a fresh hash on every
  9069. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9070. # it clones the same nonce onto its injected <script>, and the inline
  9071. # script passes the policy without us needing 'unsafe-inline'. See
  9072. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9073. csp_nonce = secrets.token_urlsafe(16)
  9074. # Routes that render their own HTML need it too, or their inline script is
  9075. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9076. # one that does: it submits its own form so a verdict still costs one tap.
  9077. request.state.csp_nonce = csp_nonce
  9078. response = await call_next(request)
  9079. response.headers["X-Content-Type-Options"] = "nosniff"
  9080. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9081. # browsers honour CSP frame-ancestors instead, and the legacy
  9082. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9083. # When operators have explicitly allowlisted trusted frame origins (#1191
  9084. # — typically Home Assistant on a different port), drop X-Frame-Options
  9085. # and let the CSP-side frame-ancestors directive govern embedding.
  9086. if not _TRUSTED_FRAME_ORIGINS:
  9087. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9088. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9089. # Content-Security-Policy for the React SPA.
  9090. # Notes:
  9091. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9092. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9093. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9094. # - media-src blob:: timelapse video player uses Blob URLs.
  9095. # - font-src data:: some icon fonts are embedded as data URIs.
  9096. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9097. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9098. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9099. # default CSP would render a blank page.
  9100. response.headers["Content-Security-Policy"] = (
  9101. "default-src 'self'; "
  9102. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9103. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9104. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9105. "connect-src 'self'; "
  9106. "font-src 'self' data: https://fonts.gstatic.com; "
  9107. "worker-src 'self' blob:; "
  9108. "object-src 'none'; "
  9109. "base-uri 'self'; " + _frame_ancestors("'none'")
  9110. )
  9111. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9112. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9113. # its emscripten/embind glue generates invoker functions with `new
  9114. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9115. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9116. # own response — not the document's — so relaxing it here confines
  9117. # eval to that DOM-less worker context. The document policy below
  9118. # stays nonce-strict, and this response header has no effect when the
  9119. # file is merely fetched (a fetch's CSP is enforced against the
  9120. # requesting document, not the resource's own headers).
  9121. response.headers["Content-Security-Policy"] = (
  9122. "default-src 'self'; "
  9123. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9124. "connect-src 'self'; "
  9125. "object-src 'none'; "
  9126. "base-uri 'self'; " + _frame_ancestors("'none'")
  9127. )
  9128. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9129. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9130. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9131. # rule as the STEP worker above: the policy that governs a dedicated
  9132. # worker is the one delivered with its own script, so the wasm compile
  9133. # has to be permitted here rather than on the document. Unlike the STEP
  9134. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9135. response.headers["Content-Security-Policy"] = (
  9136. "default-src 'self'; "
  9137. "script-src 'self' 'wasm-unsafe-eval'; "
  9138. "connect-src 'self'; "
  9139. "object-src 'none'; "
  9140. "base-uri 'self'; " + _frame_ancestors("'none'")
  9141. )
  9142. else:
  9143. # The streaming overlay is embedded same-origin by the URL builder's
  9144. # preview in Settings (#1422), so this branch allows 'self'.
  9145. # Embedding from anywhere else is still refused: 'self'
  9146. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9147. # a clickjacking page on another host is blocked exactly as before.
  9148. # (The overlay draws status over a camera feed and its only interactive
  9149. # element is the logo link, so there is nothing to bait a click into
  9150. # even from a same-origin framer.) Cross-origin embedding of the
  9151. # overlay — Home Assistant on another port — remains what
  9152. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9153. # allowlist in.
  9154. #
  9155. # The connected-app consent page (/connect/authorize) gets the same
  9156. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9157. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9158. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9159. # requires every ancestor to be this origin, so a foreign page -- a
  9160. # sidebar link's site included -- still cannot frame the consent
  9161. # screen to bait a click.
  9162. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9163. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9164. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9165. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9166. # the policy served with their own script, so each gets it in its own
  9167. # branch above and the document policy stays as strict as it was.
  9168. response.headers["Content-Security-Policy"] = (
  9169. "default-src 'self'; "
  9170. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9171. "style-src 'self' 'unsafe-inline'; "
  9172. "img-src 'self' data: blob:; "
  9173. "media-src 'self' blob:; "
  9174. "connect-src 'self' ws: wss:; "
  9175. "font-src 'self' data:; "
  9176. "object-src 'none'; "
  9177. "base-uri 'self'; "
  9178. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9179. )
  9180. if request.url.scheme == "https":
  9181. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9182. return response
  9183. @app.middleware("http")
  9184. async def auth_middleware(request, call_next):
  9185. """Enforce authentication on all API routes when auth is enabled.
  9186. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9187. regardless of whether individual routes have auth dependencies.
  9188. """
  9189. from starlette.responses import JSONResponse
  9190. path = request.url.path
  9191. # Only apply to API routes
  9192. if not path.startswith("/api/"):
  9193. return await call_next(request)
  9194. # Allow public routes
  9195. if path in PUBLIC_API_ROUTES:
  9196. return await call_next(request)
  9197. # Allow public prefixes
  9198. for prefix in PUBLIC_API_PREFIXES:
  9199. if path.startswith(prefix):
  9200. return await call_next(request)
  9201. # Allow public patterns (read-only display data like thumbnails)
  9202. for pattern in PUBLIC_API_PATTERNS:
  9203. if pattern in path:
  9204. return await call_next(request)
  9205. # Check if auth is enabled. Fail CLOSED on any exception during the
  9206. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9207. # an attacker who could force a DB exception (e.g. file-descriptor
  9208. # exhaustion via login flood) bypass auth on every protected endpoint.
  9209. try:
  9210. async with async_session() as db:
  9211. from backend.app.core.auth import is_auth_enabled
  9212. auth_enabled = await is_auth_enabled(db)
  9213. if not auth_enabled:
  9214. # Auth disabled, allow all requests
  9215. return await call_next(request)
  9216. except Exception:
  9217. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9218. return JSONResponse(
  9219. status_code=503,
  9220. content={"detail": "Authentication service temporarily unavailable"},
  9221. )
  9222. # Auth is enabled - require valid token
  9223. auth_header = request.headers.get("Authorization")
  9224. x_api_key = request.headers.get("X-API-Key")
  9225. # Check for API key auth first
  9226. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9227. # API key authentication - let the request through to be validated by route handler
  9228. # API keys are validated per-route since they have different permission levels
  9229. return await call_next(request)
  9230. # Check for JWT auth
  9231. if not auth_header or not auth_header.startswith("Bearer "):
  9232. return JSONResponse(
  9233. status_code=401,
  9234. content={"detail": "Authentication required"},
  9235. headers={"WWW-Authenticate": "Bearer"},
  9236. )
  9237. # Validate JWT token
  9238. import jwt
  9239. try:
  9240. from backend.app.core.auth import (
  9241. ALGORITHM,
  9242. SECRET_KEY,
  9243. _is_token_fresh,
  9244. get_user_by_username,
  9245. is_jti_revoked,
  9246. )
  9247. token = auth_header.replace("Bearer ", "")
  9248. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9249. username = payload.get("sub")
  9250. if not username:
  9251. raise ValueError("No username in token")
  9252. jti = payload.get("jti")
  9253. if not jti:
  9254. raise ValueError("No jti in token")
  9255. iat = payload.get("iat")
  9256. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9257. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9258. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9259. async with async_session() as db:
  9260. if await is_jti_revoked(jti, db):
  9261. return JSONResponse(
  9262. status_code=401,
  9263. content={"detail": "Token has been revoked"},
  9264. headers={"WWW-Authenticate": "Bearer"},
  9265. )
  9266. user = await get_user_by_username(db, username)
  9267. if not user or not user.is_active:
  9268. return JSONResponse(
  9269. status_code=401,
  9270. content={"detail": "User not found or inactive"},
  9271. headers={"WWW-Authenticate": "Bearer"},
  9272. )
  9273. if not _is_token_fresh(iat, user):
  9274. return JSONResponse(
  9275. status_code=401,
  9276. content={"detail": "Token no longer valid"},
  9277. headers={"WWW-Authenticate": "Bearer"},
  9278. )
  9279. except jwt.ExpiredSignatureError:
  9280. return JSONResponse(
  9281. status_code=401,
  9282. content={"detail": "Token has expired"},
  9283. headers={"WWW-Authenticate": "Bearer"},
  9284. )
  9285. except (jwt.InvalidTokenError, ValueError, Exception):
  9286. return JSONResponse(
  9287. status_code=401,
  9288. content={"detail": "Invalid token"},
  9289. headers={"WWW-Authenticate": "Bearer"},
  9290. )
  9291. return await call_next(request)
  9292. @app.middleware("http")
  9293. async def trace_id_middleware(request, call_next):
  9294. """Stamp every HTTP request with a trace ID and echo it back.
  9295. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9296. @app.middleware decorators LIFO, so the last-decorated runs first
  9297. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9298. which means auth-middleware log lines (and every line emitted on the
  9299. way down to and back from the route handler) all carry the same
  9300. trace ID. If we put it before auth, auth's logs would be stamped
  9301. with the *previous* request's ID — useless for correlation.
  9302. Honours an inbound ``X-Trace-Id`` header so callers running their
  9303. own tracing can correlate their span IDs with our log lines, but
  9304. only if the value passes the whitelist gate in
  9305. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9306. rejected (too long, contains control chars, etc.) silently triggers
  9307. a freshly minted server-side ID rather than failing the request.
  9308. The minted (or echoed) ID is set on a ContextVar so that every log
  9309. record emitted during the request — application logs *and* uvicorn's
  9310. access log — carries it via TraceIDFilter, and is also written to
  9311. the ``X-Trace-Id`` response header so clients can pin a server-side
  9312. log search to the exact request they made.
  9313. """
  9314. from backend.app.core.trace import (
  9315. generate_trace_id,
  9316. normalise_inbound_trace_id,
  9317. trace_id_var,
  9318. )
  9319. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9320. trace_id = inbound if inbound is not None else generate_trace_id()
  9321. token = trace_id_var.set(trace_id)
  9322. try:
  9323. response = await call_next(request)
  9324. finally:
  9325. # Reset the ContextVar so a record emitted in a totally
  9326. # unrelated background task that just happens to inherit this
  9327. # context doesn't keep referencing this request's ID forever.
  9328. # In practice ContextVar.reset is best-effort under asyncio
  9329. # task-spawn semantics, but the cost is one attribute write so
  9330. # we may as well do it.
  9331. trace_id_var.reset(token)
  9332. response.headers["X-Trace-Id"] = trace_id
  9333. return response
  9334. # API routes
  9335. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9336. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9337. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9338. app.include_router(users.router, prefix=app_settings.api_prefix)
  9339. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9340. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9341. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9342. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9343. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9344. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9345. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9346. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9347. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9348. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9349. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9350. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9351. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  9352. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  9353. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  9354. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  9355. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  9356. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  9357. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  9358. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  9359. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  9360. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  9361. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  9362. app.include_router(updates.router, prefix=app_settings.api_prefix)
  9363. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  9364. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  9365. app.include_router(camera.router, prefix=app_settings.api_prefix)
  9366. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  9367. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  9368. app.include_router(projects.router, prefix=app_settings.api_prefix)
  9369. app.include_router(library.router, prefix=app_settings.api_prefix)
  9370. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  9371. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  9372. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  9373. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  9374. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  9375. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  9376. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  9377. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  9378. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  9379. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  9380. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  9381. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  9382. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  9383. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  9384. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  9385. app.include_router(system.router, prefix=app_settings.api_prefix)
  9386. app.include_router(support.router, prefix=app_settings.api_prefix)
  9387. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  9388. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  9389. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9390. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9391. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9392. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9393. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9394. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9395. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9396. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9397. # Serve static files (React build)
  9398. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9399. app.mount(
  9400. "/assets",
  9401. StaticFiles(directory=app_settings.static_dir / "assets"),
  9402. name="assets",
  9403. )
  9404. if (app_settings.static_dir / "img").exists():
  9405. app.mount(
  9406. "/img",
  9407. StaticFiles(directory=app_settings.static_dir / "img"),
  9408. name="img",
  9409. )
  9410. if (app_settings.static_dir / "icons").exists():
  9411. app.mount(
  9412. "/icons",
  9413. StaticFiles(directory=app_settings.static_dir / "icons"),
  9414. name="icons",
  9415. )
  9416. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9417. # falls through to the SPA catch-all and returns index.html, which the
  9418. # browser's font sanitizer rejects ("downloadable font: rejected by
  9419. # sanitizer").
  9420. if (app_settings.static_dir / "fonts").exists():
  9421. app.mount(
  9422. "/fonts",
  9423. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9424. name="fonts",
  9425. )
  9426. @app.get("/")
  9427. async def serve_frontend():
  9428. """Serve the React frontend."""
  9429. index_file = app_settings.static_dir / "index.html"
  9430. if index_file.exists():
  9431. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9432. return {
  9433. "message": "Bambuddy API",
  9434. "docs": "/docs",
  9435. "frontend": "Build and place React app in /static directory",
  9436. }
  9437. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9438. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9439. # forever, but the HTML wrapping it is the only file that knows which hash
  9440. # is current. Without explicit cache-control headers Chromium decides
  9441. # heuristically (typically 10% of the time since Last-Modified) and on
  9442. # long-running kiosks happily serves stale HTML across browser restarts.
  9443. # That stale HTML references an old bundle hash, the old bundle is also
  9444. # in the disk cache, and the user ends up running pre-update JS forever
  9445. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9446. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9447. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9448. @app.get("/health")
  9449. async def health_check():
  9450. """Health check endpoint."""
  9451. return {"status": "healthy"}
  9452. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9453. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9454. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9455. # in deployment debugging.
  9456. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9457. async def serve_manifest():
  9458. """Serve PWA manifest."""
  9459. manifest_file = app_settings.static_dir / "manifest.json"
  9460. if manifest_file.exists():
  9461. return FileResponse(manifest_file, media_type="application/manifest+json")
  9462. return {"error": "Manifest not found"}
  9463. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9464. async def serve_service_worker():
  9465. """Serve service worker."""
  9466. sw_file = app_settings.static_dir / "sw.js"
  9467. if sw_file.exists():
  9468. return FileResponse(
  9469. sw_file,
  9470. media_type="application/javascript",
  9471. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9472. )
  9473. return {"error": "Service worker not found"}
  9474. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9475. async def serve_sw_register():
  9476. """Serve the service-worker registration bootstrap script.
  9477. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9478. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9479. """
  9480. reg_file = app_settings.static_dir / "sw-register.js"
  9481. if reg_file.exists():
  9482. return FileResponse(reg_file, media_type="application/javascript")
  9483. return {"error": "sw-register.js not found"}
  9484. # ── GCode viewer static files ────────────────────────────────────────────────
  9485. # Catch-all route for React Router (must be last)
  9486. @app.get("/{full_path:path}")
  9487. async def serve_spa(full_path: str):
  9488. """Serve React app for client-side routing."""
  9489. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9490. if full_path.startswith("api/"):
  9491. from fastapi import HTTPException
  9492. raise HTTPException(status_code=404, detail="Not found")
  9493. index_file = app_settings.static_dir / "index.html"
  9494. if index_file.exists():
  9495. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9496. return {"error": "Frontend not built"}