main.py 538 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, or_, select, text
  19. from backend.app.api.routes import (
  20. ams_history,
  21. announcements,
  22. api_keys,
  23. archive_purge,
  24. archives,
  25. auth,
  26. bug_report,
  27. camera,
  28. camwall,
  29. cloud,
  30. connected_apps,
  31. discovery,
  32. external_links,
  33. filaments,
  34. finance,
  35. firmware,
  36. github_backup,
  37. groups,
  38. ha_sensors,
  39. inventory,
  40. kprofiles,
  41. labels,
  42. library,
  43. library_tags,
  44. library_trash,
  45. library_variants,
  46. local_backup,
  47. local_presets,
  48. location_ha_sensors,
  49. maintenance,
  50. makerworld,
  51. manyfold,
  52. metrics,
  53. mfa,
  54. notification_templates,
  55. notifications,
  56. obico,
  57. orca_cloud,
  58. overlay_branding,
  59. pending_uploads,
  60. pipeline_runs,
  61. print_log,
  62. print_queue,
  63. printer_locations,
  64. printer_sensor_history,
  65. printers,
  66. projects,
  67. scheduled_dryings,
  68. settings as settings_routes,
  69. slice_jobs,
  70. slicer_pipelines,
  71. slicer_presets,
  72. smart_plugs,
  73. sponsor_prompt,
  74. spoolbuddy,
  75. spoolman,
  76. spoolman_inventory,
  77. support,
  78. system,
  79. updates,
  80. user_notifications,
  81. users,
  82. virtual_printers,
  83. webhook,
  84. websocket,
  85. )
  86. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  87. from backend.app.api.routes.support import init_debug_logging
  88. from backend.app.core.config import APP_VERSION, settings as app_settings
  89. from backend.app.core.database import async_session, engine, init_db
  90. from backend.app.core.static_assets import AssetStaticFiles
  91. from backend.app.core.tasks import spawn_background_task
  92. from backend.app.core.websocket import ws_manager
  93. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  94. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  95. from backend.app.services.archive_cost_estimate import (
  96. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  97. )
  98. from backend.app.services.archive_purge import archive_purge_service
  99. from backend.app.services.bambu_ftp import (
  100. FileNotOnPrinterError,
  101. cache_3mf_download,
  102. clear_3mf_cache,
  103. download_file_async,
  104. download_file_try_paths_async,
  105. ftps_handshake_blocked,
  106. get_cached_3mf,
  107. get_ftp_retry_settings,
  108. normalize_3mf_name,
  109. with_ftp_retry,
  110. )
  111. from backend.app.services.bambu_mqtt import PrinterState
  112. from backend.app.services.camera_light import camera_light
  113. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  114. from backend.app.services.github_backup import github_backup_service
  115. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  116. from backend.app.services.homeassistant import homeassistant_service
  117. from backend.app.services.library_trash import library_trash_service
  118. from backend.app.services.local_backup import local_backup_service
  119. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  120. from backend.app.services.mqtt_relay import mqtt_relay
  121. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  122. from backend.app.services.notification_service import notification_service
  123. from backend.app.services.obico_detection import obico_detection_service
  124. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  125. from backend.app.services.print_scheduler import scheduler as print_scheduler
  126. from backend.app.services.print_storage import (
  127. REASON_FTP_TRANSFER_FAILED,
  128. REASON_FTPS_COOLOFF,
  129. external_storage_present,
  130. ftp_probe_paths,
  131. print_file_reachable_over_ftp,
  132. )
  133. from backend.app.services.printer_manager import (
  134. init_printer_connections,
  135. parse_plate_id,
  136. printer_manager,
  137. printer_state_to_dict,
  138. resolve_plate_id,
  139. )
  140. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  141. from backend.app.services.slot_nozzle import (
  142. nozzle_diameter_for_extruder,
  143. nozzle_flow_for_extruder,
  144. resolve_slot_nozzle,
  145. )
  146. from backend.app.services.smart_plug_manager import smart_plug_manager
  147. from backend.app.services.spool_assignment_notifications import (
  148. notify_missing_spool_assignments_on_print_start,
  149. )
  150. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  151. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  152. from backend.app.services.spoolman_tracking import (
  153. cleanup_tracking as _cleanup_spoolman_tracking,
  154. report_usage as _report_spoolman_usage,
  155. store_print_data as _store_spoolman_print_data,
  156. )
  157. from backend.app.services.tasmota import tasmota_service
  158. from backend.app.services.telegram_reactions import telegram_reaction_poller
  159. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  160. from backend.app.utils.ams_humidity import ams_humidity_percent
  161. from backend.app.utils.filament_types import printer_filament_type
  162. from backend.app.utils.fts_routing import extruder_for_inlet
  163. from backend.app.utils.local_time import utcnow_naive
  164. from backend.app.utils.print_jobs import is_internal_printer_job
  165. # =============================================================================
  166. # Dependency Check - runs before other imports to give helpful error messages
  167. # =============================================================================
  168. def _start_error_server(missing_packages: list):
  169. """Start a minimal HTTP server to display dependency errors in browser."""
  170. import os
  171. import signal
  172. from http.server import BaseHTTPRequestHandler, HTTPServer
  173. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  174. html = f"""<!DOCTYPE html>
  175. <html>
  176. <head>
  177. <title>Bambuddy - Setup Required</title>
  178. <style>
  179. body {{
  180. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  181. background: #0f172a; color: #e2e8f0;
  182. display: flex; justify-content: center; align-items: center;
  183. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  184. }}
  185. .container {{
  186. background: #1e293b; border-radius: 12px; padding: 40px;
  187. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  188. }}
  189. h1 {{ color: #f87171; margin-bottom: 10px; }}
  190. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  191. .packages {{
  192. background: #0f172a; border-radius: 8px; padding: 20px;
  193. margin: 20px 0; text-align: left;
  194. }}
  195. .packages ul {{ margin: 0; padding-left: 20px; }}
  196. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  197. .command {{
  198. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  199. margin: 15px 0; font-family: monospace; color: #4ade80;
  200. text-align: left; overflow-x: auto;
  201. }}
  202. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  203. </style>
  204. </head>
  205. <body>
  206. <div class="container">
  207. <h1>Setup Required</h1>
  208. <h2>Missing Python packages</h2>
  209. <div class="packages"><ul>{packages_html}</ul></div>
  210. <p>To fix, run this command on your server:</p>
  211. <div class="command">pip install -r requirements.txt</div>
  212. <p>Or if using a virtual environment:</p>
  213. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  214. <p class="note">After installing, restart Bambuddy:<br>
  215. <code>sudo systemctl restart bambuddy</code></p>
  216. </div>
  217. </body>
  218. </html>"""
  219. class ErrorHandler(BaseHTTPRequestHandler):
  220. def do_GET(self):
  221. self.send_response(503)
  222. self.send_header("Content-type", "text/html")
  223. self.end_headers()
  224. self.wfile.write(html.encode())
  225. def log_message(self, format, *args):
  226. print(f"[Error Server] {args[0]}")
  227. port = int(os.environ.get("PORT", 8000))
  228. print(f"\nStarting error server on http://0.0.0.0:{port}")
  229. print("Visit this URL in your browser to see the error details.\n")
  230. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  231. def shutdown(signum, frame):
  232. print("\nShutting down error server...")
  233. raise SystemExit(0)
  234. signal.signal(signal.SIGTERM, shutdown)
  235. signal.signal(signal.SIGINT, shutdown)
  236. server.serve_forever()
  237. def check_dependencies():
  238. """Check that all required packages are installed."""
  239. missing = []
  240. # Map of import name -> package name (for pip install)
  241. required = {
  242. "jwt": "PyJWT",
  243. "fastapi": "fastapi",
  244. "uvicorn": "uvicorn",
  245. "sqlalchemy": "sqlalchemy",
  246. "aiosqlite": "aiosqlite",
  247. "pydantic": "pydantic",
  248. "paho.mqtt": "paho-mqtt",
  249. }
  250. for module, package in required.items():
  251. try:
  252. __import__(module)
  253. except ImportError:
  254. missing.append(package)
  255. if missing:
  256. print("\n" + "=" * 60)
  257. print("ERROR: Missing required Python packages!")
  258. print("=" * 60)
  259. print(f"\nMissing packages: {', '.join(missing)}")
  260. print("\nTo fix, run:")
  261. print(" pip install -r requirements.txt")
  262. print("\nOr if using a virtual environment:")
  263. print(" ./venv/bin/pip install -r requirements.txt")
  264. print("=" * 60 + "\n")
  265. _start_error_server(missing)
  266. check_dependencies()
  267. # =============================================================================
  268. # Import settings first for logging configuration
  269. # Configure logging based on settings
  270. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  271. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  272. log_level = getattr(logging, log_level_str, logging.INFO)
  273. # Trace ID column ([-] when no request scope is active — startup, MQTT
  274. # callbacks, scheduled tasks not chained from a request — so the column
  275. # stays visually aligned and missing values are obvious in grep). See
  276. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  277. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  278. # Create root logger
  279. root_logger = logging.getLogger()
  280. root_logger.setLevel(log_level)
  281. # Trace-ID injection: this filter populates record.trace_id from the
  282. # per-request ContextVar so the format string above can reference it.
  283. # Attached to each HANDLER (not the root logger) because Python's
  284. # logging semantics only invoke a logger's filters on records that
  285. # *originated* at that logger — records propagated up from child
  286. # loggers (every named logger in the app) never trigger root's filter.
  287. # Putting it on the handlers means every record any handler emits gets
  288. # trace_id injected just before the formatter runs, regardless of which
  289. # logger created the record. Without this, the formatter raises
  290. # KeyError on every child-logger record and the record is silently
  291. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  292. # partially" bug we hit. See backend/app/core/trace.py for the
  293. # ContextVar the filter reads.
  294. from backend.app.core.trace import TraceIDFilter
  295. _trace_id_filter = TraceIDFilter()
  296. # Console handler - always enabled
  297. console_handler = logging.StreamHandler()
  298. console_handler.setLevel(log_level)
  299. console_handler.setFormatter(logging.Formatter(log_format))
  300. console_handler.addFilter(_trace_id_filter)
  301. root_logger.addHandler(console_handler)
  302. # File handler - only in production or if explicitly enabled
  303. if app_settings.log_to_file:
  304. log_file = app_settings.log_dir / "bambuddy.log"
  305. file_handler = RotatingFileHandler(
  306. log_file,
  307. maxBytes=app_settings.log_max_bytes,
  308. backupCount=app_settings.log_backup_count,
  309. encoding="utf-8",
  310. )
  311. file_handler.setLevel(log_level)
  312. file_handler.setFormatter(logging.Formatter(log_format))
  313. file_handler.addFilter(_trace_id_filter)
  314. root_logger.addHandler(file_handler)
  315. logging.info("Logging to file: %s", log_file)
  316. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  317. # access logger with propagate=False by default, so without this attach
  318. # there is no on-disk record of which endpoint triggered a server-state
  319. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  320. # for exactly this reason. Filtered to write methods only
  321. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  322. # frontend don't churn the rotation window faster than it's useful.
  323. from backend.app.core.logging_filters import (
  324. CancelledPoolNoiseFilter,
  325. WriteRequestsOnlyFilter,
  326. )
  327. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  328. uvicorn_access_logger.addHandler(file_handler)
  329. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  330. # Uvicorn's access logger has propagate=False (its own default), so the
  331. # root-attached TraceIDFilter never sees these records. Attach a
  332. # second instance directly so HTTP access lines carry the same trace
  333. # ID column as the application logs they correlate with.
  334. uvicorn_access_logger.addFilter(TraceIDFilter())
  335. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  336. # BaseHTTPMiddleware cancelling the inner task scope on client
  337. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  338. # underlying transaction leak; this filter only suppresses the residual
  339. # log records that pre-existing pools still emit during their cleanup.
  340. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  341. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  342. # handler (console included), whether or not file logging is on.
  343. from backend.app.core.logging_filters import QueryTokenRedactFilter # noqa: E402
  344. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  345. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  346. # Reduce noise from third-party libraries in production
  347. if not app_settings.debug:
  348. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  349. logging.getLogger("httpcore").setLevel(logging.WARNING)
  350. logging.getLogger("httpx").setLevel(logging.WARNING)
  351. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  352. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  353. # Track active prints: {(printer_id, filename): archive_id}
  354. _active_prints: dict[tuple[int, str], int] = {}
  355. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  356. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  357. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  358. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  359. # instead of running its own grab-now chain when present, so the finish photo
  360. # captures the better-framed pre-bed-drop moment without us having to force
  361. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  362. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  363. #
  364. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  365. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  366. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  367. # bank and the others are not — so the consumer can't tell them apart and
  368. # must not rotate again.
  369. _stage22_finish_frames: dict[int, bytes] = {}
  370. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  371. # `finally` block (whether it captured a frame or not). The consumer in
  372. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  373. # so the FINISH-state fallback path — where moment and completion are dispatched
  374. # back-to-back — doesn't race past the producer with an empty pop, and the
  375. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  376. # grab (Bambu printers allow only one RTSP client at a time).
  377. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  378. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  379. # layer-change and on print-progress advances (#2547) while the model is still
  380. # printing, then consumed by the FINISH-state finish-photo path when the
  381. # dispatcher recorded that it injected End G-code into this print. Bambu
  382. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  383. # plate-swap) has run, so a live grab there would capture the swapped/empty
  384. # plate.
  385. #
  386. # The load-bearing property: both drivers are print telemetry that stops before
  387. # the End G-code executes — no further layer_num increases, and mc_percent
  388. # freezes — so the last banked frame is always the finished print before the
  389. # swap. Anything added as a third driver must hold that same property.
  390. _inprint_frame_bank: dict[int, bytes] = {}
  391. # Monotonic timestamp of the last banked frame per printer — throttles banking
  392. # so tall prints don't add a camera grab on every layer.
  393. _inprint_frame_bank_ts: dict[int, float] = {}
  394. # Minimum seconds between banked frames, except the final object layer which
  395. # always refreshes for the best framing.
  396. _INPRINT_BANK_MIN_INTERVAL = 25.0
  397. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  398. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  399. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  400. # the first connected status update for that connection; transitions back
  401. # to False whenever we observe `state.connected = False` so the next
  402. # reconnect re-arms reconciliation. Keyed by printer_id.
  403. _printer_reconciled_since_connect: dict[int, bool] = {}
  404. # Same edge, same keying, for priming the printer's calibration table exactly
  405. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  406. # is otherwise filled only when someone opens the Profiles page or Configure
  407. # Slot, when a GitHub backup runs, or when the printer happens to answer
  408. # somebody else's query on the report topic. Until then the AMS slot card has
  409. # no K value to show on the printers whose trays carry none of their own
  410. # (#2854 — H2-series report cali_idx and nothing more).
  411. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  412. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  413. # {(printer_id, filename): archive_id}
  414. _expected_prints: dict[tuple[int, str], int] = {}
  415. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  416. # Used by usage tracker to map 3MF slots to physical AMS trays
  417. _print_ams_mappings: dict[int, list[int]] = {}
  418. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  419. _print_cost_center_ids: dict[int, int] = {}
  420. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  421. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  422. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  423. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  424. # for the queue path. Cleared on print completion or TTL eviction.
  425. _print_plate_ids: dict[int, int] = {}
  426. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  427. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  428. _last_progress_milestone: dict[int, int] = {}
  429. # Track whether first layer complete notification has been sent for current print
  430. _first_layer_notified: dict[int, bool] = {}
  431. # Track whether we already sent a kill-switch stop for the current unauthorized print
  432. _unauthorized_print_kill_sent: set[int] = set()
  433. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  434. # lookup briefly so an unknown active print does not query the database on
  435. # every status frame. A short TTL keeps settings changes responsive.
  436. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  437. _kill_switch_setting_cache: tuple[bool, float] | None = None
  438. # Provider notification started when the kill switch stops a print. The later
  439. # MQTT print-complete callback awaits this task and only sends its regular
  440. # provider notification when the immediate attempt failed.
  441. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  442. # HMS faults already notified, with when each was last seen:
  443. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  444. # fault that flickers beside a held notice was forgotten on every gap and
  445. # notified on every return (#3226). The window is long because the measured
  446. # gaps reach 64 s.
  447. _notified_hms_errors: dict[int, dict[str, float]] = {}
  448. _HMS_CLEAR_GRACE_SECONDS = 600.0
  449. # The print state each printer was last seen in, and the faults recorded before
  450. # it last changed, which are forgotten as soon as they are gone (see
  451. # _take_new_hms_faults).
  452. _hms_print_state: dict[int, str] = {}
  453. _hms_forget_when_gone: dict[int, set[str]] = {}
  454. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  455. # Used for snapshot-diff detection at print completion
  456. _timelapse_baselines: dict[int, set[str]] = {}
  457. # Track printers waiting for bed to cool after print completion.
  458. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  459. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  460. _bed_cool_waiters: dict[int, dict] = {}
  461. # Track printers where the user explicitly stopped the print from the queue UI.
  462. # When on_print_complete fires with status "failed" for these printers we treat it
  463. # as "cancelled" (stopped by user) so the correct notification email is sent.
  464. _user_stopped_printers: set[int] = set()
  465. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  466. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  467. # holds the previous observation so we only fire on the True → False edge (a
  468. # False → False repeat doesn't notify; an initial False at startup doesn't
  469. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  470. # holds the per-printer pending asyncio task that fires the notification
  471. # after a debounce window — cancelled if the printer reconnects before the
  472. # window elapses, so transient MQTT blips don't flood the user.
  473. _printer_last_connected: dict[int, bool] = {}
  474. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  475. # Debounce: a printer must stay offline this long before we notify. Sized
  476. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  477. # so a single stale-trigger cooldown isn't enough to fire — only a real
  478. # offline that survives one reconnect attempt notifies.
  479. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  480. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  481. # when status="failed" to label the print's failure_reason in archives.
  482. #
  483. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  484. # which is wrong on two counts:
  485. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  486. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  487. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  488. # the public wiki) as part of its user-cancel sequence. Matching on the module
  489. # alone caused user-cancellations to be archived as "Layer shift" failures.
  490. # We now match by full short code only — anything not in this map leaves
  491. # failure_reason=None rather than guessing.
  492. # Values are the canonical camelCase failure-reason keys, NOT display labels
  493. # (issue #2974). The vocabulary is enforced on writes by
  494. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  495. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  496. # Statistics breakdown. Storing a label here instead put a second spelling of
  497. # the same cause into one column: the Failure Analysis widget groups on the raw
  498. # value, so a print the backend classified and an identical one a user
  499. # classified counted as two different reasons, and the label form could never
  500. # be translated because there was no key for ``t()`` to resolve.
  501. _HMS_FAILURE_REASONS: dict[str, str] = {
  502. # Layer shift / step loss
  503. "0300_4057": "layerShift",
  504. "0300_4068": "layerShift",
  505. "0300_800C": "layerShift",
  506. # Filament runout (printer-side & per-AMS-slot)
  507. "0300_8004": "filamentRunout",
  508. "0700_8011": "filamentRunout",
  509. "0701_8011": "filamentRunout",
  510. "0702_8011": "filamentRunout",
  511. "0703_8011": "filamentRunout",
  512. "0704_8011": "filamentRunout",
  513. "0705_8011": "filamentRunout",
  514. "0706_8011": "filamentRunout",
  515. "0707_8011": "filamentRunout",
  516. "07FF_8011": "filamentRunout",
  517. # Clogged nozzle / extruder
  518. "0300_4006": "cloggedNozzle",
  519. "0300_8016": "cloggedNozzle",
  520. "0300_801C": "cloggedNozzle",
  521. "0700_8003": "cloggedNozzle",
  522. "0700_8007": "cloggedNozzle",
  523. "0700_8013": "cloggedNozzle",
  524. "0701_8003": "cloggedNozzle",
  525. "0701_8007": "cloggedNozzle",
  526. "0701_8013": "cloggedNozzle",
  527. "0702_8003": "cloggedNozzle",
  528. # AI print monitoring — spaghetti / the model coming off the plate.
  529. # `spaghettiDetached` is a key the archive editor already offers for this
  530. # failure mode, not a new one, so a derived reason opens the dropdown on
  531. # that option rather than blank — and survives the next save, which clears
  532. # any value the editor does not recognise.
  533. #
  534. # A module-0x0C row is safe here despite the warning above: that warning is
  535. # about matching on the module alone, and 0C00_8042 is a full short code
  536. # with a documented meaning ("The AI print monitor has detected a spaghetti
  537. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  538. # cannot collide.
  539. #
  540. # 0300_8003's own text ends "before continuing your print", but on an X2D
  541. # it arrives with the print already paused, offering only
  542. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  543. #
  544. # Two neighbours are left out on purpose, so this does not get re-derived:
  545. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  546. # reads as a warning about a print that is still running, not a halt.
  547. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  548. # the waste chute. That is not the print failing.
  549. #
  550. # That line is drawn from the text, not from `severity`, because severity
  551. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  552. # module/error word with no level in it, and bambu_mqtt.py gives every
  553. # print_error entry a flat severity=3. Matching on the short code alone is
  554. # the right shape for derive_failure_reason, not an omission.
  555. "0300_8003": "spaghettiDetached",
  556. "0C00_8042": "spaghettiDetached",
  557. }
  558. def _hms_short_code(attr: int, code: int | str) -> str:
  559. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  560. if isinstance(code, str):
  561. code_int = int(code.replace("0x", ""), 16) if code else 0
  562. else:
  563. code_int = int(code or 0)
  564. attr_int = int(attr or 0)
  565. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  566. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  567. """Derive the failure_reason key for an archived print.
  568. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  569. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  570. no HMS code matches (don't guess — null is honest). The keys are the
  571. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  572. translated at render time.
  573. """
  574. if status in ("aborted", "cancelled"):
  575. return "userCancelled"
  576. if status != "failed":
  577. return None
  578. for err in hms_errors or []:
  579. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  580. if short_code in _HMS_FAILURE_REASONS:
  581. return _HMS_FAILURE_REASONS[short_code]
  582. return None
  583. # Track created_by_id for expected prints so the user email can be sent even when
  584. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  585. # {(printer_id, filename): created_by_id}
  586. _expected_print_creators: dict[tuple[int, str], int] = {}
  587. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  588. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  589. # updates for the same printer in quick succession (~30 ms apart, observed in
  590. # the wild on H2D + dual AMS).
  591. #
  592. # Without this serialisation, two concurrent on_ams_change callbacks each read
  593. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  594. # the second commit hits
  595. # IntegrityError: duplicate key value violates unique constraint
  596. # "spool_assignment_printer_id_ams_id_tray_id_key"
  597. # SQLite's WAL serial-write semantics had been silently swallowing the race
  598. # until optional Postgres support landed (asyncpg allows true concurrent
  599. # transactions and surfaces the constraint violation).
  600. #
  601. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  602. # assign) are inside the lock. The Spoolman sync block further down stays
  603. # concurrent because it's network-bound and idempotent.
  604. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  605. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  606. """Return the per-printer assignment lock, creating it on first use."""
  607. lock = _ams_assignment_locks.get(printer_id)
  608. if lock is None:
  609. lock = asyncio.Lock()
  610. _ams_assignment_locks[printer_id] = lock
  611. return lock
  612. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  613. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  614. # tag tuple changes for the slot. Cleared when the slot is reported empty
  615. # so remove + reinsert reliably re-prompts the UI.
  616. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  617. async def _broadcast_unknown_tag(
  618. *,
  619. printer_id: int,
  620. ams_id: int,
  621. tray_id: int,
  622. tag_uid: str,
  623. tray_uuid: str,
  624. tray_type: str | None = None,
  625. tray_color: str | None = None,
  626. tray_sub_brands: str | None = None,
  627. tray_count: int | None = None,
  628. ) -> None:
  629. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  630. _logger = logging.getLogger(__name__)
  631. slot_key = (ams_id, tray_id)
  632. tag_key = (tag_uid or "", tray_uuid or "")
  633. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  634. if per_printer.get(slot_key) == tag_key:
  635. _logger.debug(
  636. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  637. printer_id,
  638. ams_id,
  639. tray_id,
  640. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  641. )
  642. return
  643. _logger.info(
  644. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  645. printer_id,
  646. ams_id,
  647. tray_id,
  648. tray_type,
  649. tray_color,
  650. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  651. )
  652. # Broadcast first; only commit the dedup if the WS write succeeds.
  653. # If broadcast raises, the next MQTT push retries instead of being
  654. # permanently silenced by a poisoned dedup entry.
  655. await ws_manager.broadcast(
  656. {
  657. "type": "unknown_tag",
  658. "printer_id": printer_id,
  659. "ams_id": ams_id,
  660. "tray_id": tray_id,
  661. "tag_uid": tag_uid,
  662. "tray_uuid": tray_uuid,
  663. "tray_type": tray_type,
  664. "tray_color": tray_color,
  665. "tray_sub_brands": tray_sub_brands,
  666. "tray_count": tray_count,
  667. }
  668. )
  669. per_printer[slot_key] = tag_key
  670. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  671. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  672. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  673. if per_printer is None:
  674. return
  675. per_printer.pop((ams_id, tray_id), None)
  676. # TTL for expected-print entries: evict registrations older than this to prevent
  677. # unbounded growth when a print is registered but never starts (e.g. printer
  678. # disconnect, app restart, print started from the printer panel).
  679. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  680. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  681. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  682. # Cleanup loop interval
  683. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  684. _expected_prints_cleanup_task: asyncio.Task | None = None
  685. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  686. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  687. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  688. possible_keys: list[tuple[int, str]] = []
  689. filename = (state.gcode_file or state.current_print or "").strip()
  690. subtask_name = (state.subtask_name or "").strip()
  691. if subtask_name:
  692. possible_keys.append((printer_id, subtask_name))
  693. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  694. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  695. if filename:
  696. base_name = filename.rsplit("/", 1)[-1]
  697. if base_name.endswith(".gcode.3mf"):
  698. root_name = base_name[: -len(".gcode.3mf")]
  699. possible_keys.append((printer_id, root_name))
  700. possible_keys.append((printer_id, base_name))
  701. possible_keys.append((printer_id, f"{root_name}.gcode"))
  702. possible_keys.append((printer_id, f"{root_name}.3mf"))
  703. elif base_name.endswith(".3mf"):
  704. root_name = base_name[: -len(".3mf")]
  705. possible_keys.append((printer_id, root_name))
  706. possible_keys.append((printer_id, base_name))
  707. elif base_name.endswith(".gcode"):
  708. root_name = base_name[: -len(".gcode")]
  709. possible_keys.append((printer_id, root_name))
  710. possible_keys.append((printer_id, f"{root_name}.3mf"))
  711. possible_keys.append((printer_id, base_name))
  712. else:
  713. possible_keys.append((printer_id, base_name))
  714. possible_keys.append((printer_id, f"{base_name}.3mf"))
  715. return possible_keys
  716. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  717. """Check the cheap, process-local print ownership signals."""
  718. if printer_manager.get_current_print_user(printer_id):
  719. return True
  720. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  721. async def _is_printer_kill_switch_enabled_cached() -> bool:
  722. """Return the kill-switch setting without querying on every MQTT frame."""
  723. global _kill_switch_setting_cache
  724. now = time.monotonic()
  725. if _kill_switch_setting_cache is not None:
  726. enabled, expires_at = _kill_switch_setting_cache
  727. if now < expires_at:
  728. return enabled
  729. async with async_session() as db:
  730. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  731. enabled = await is_printer_kill_switch_enabled(db)
  732. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  733. return enabled
  734. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  735. """Resolve whether the current print was started by Bambuddy.
  736. ``None`` means identity is not yet safe to decide. The kill switch must
  737. defer in that case: stopping a print is irreversible, and the first status
  738. frames after a restart may arrive before all subtask fields are populated.
  739. """
  740. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  741. return True
  742. possible_keys = _build_status_print_keys(printer_id, state)
  743. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  744. # is on disk. subtask_id is minted per print and pins the answer to the job
  745. # actually running, rather than to an unrelated one that reuses a filename.
  746. raw_subtask_id = getattr(state, "subtask_id", None)
  747. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  748. if subtask_id in ("", "0"):
  749. return None
  750. from backend.app.models.archive import PrintArchive
  751. result = await db.execute(
  752. select(PrintArchive)
  753. .where(
  754. PrintArchive.printer_id == printer_id,
  755. PrintArchive.status == "printing",
  756. PrintArchive.subtask_id == subtask_id,
  757. )
  758. .order_by(PrintArchive.created_at.desc())
  759. .limit(1)
  760. )
  761. archive = result.scalar_one_or_none()
  762. # An archive row on its own proves nothing: `on_print_start` archives every
  763. # print it observes, including ones started from Bambu Studio or Handy, and
  764. # stamps them with the same status and subtask_id. Authorizing on its mere
  765. # existence would disable the kill switch the moment the 3MF finishes
  766. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  767. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  768. # (carried over from the queue item that started it).
  769. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  770. # Rehydrate the fast in-memory path for subsequent status frames. Include
  771. # both the archive filename and every normalized key reported by MQTT.
  772. _active_prints[(printer_id, archive.filename)] = archive.id
  773. for key in possible_keys:
  774. _active_prints[key] = archive.id
  775. return True
  776. # No dispatch marker. Before calling this someone else's print, check whether
  777. # Bambuddy has a job of its own running on this printer: a library-file
  778. # dispatch has no archive at send time, and an archive created seconds later
  779. # by `on_print_start` carries neither marker. The queue row, which the
  780. # scheduler commits to status="printing" before the MQTT send, is the one
  781. # durable record every Bambuddy print has. It cannot be tied to this
  782. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  783. # print is irreversible, and refusing to act costs nothing but a log line.
  784. from backend.app.models.print_queue import PrintQueueItem
  785. dispatched_here = await db.scalar(
  786. select(PrintQueueItem.id)
  787. .where(
  788. PrintQueueItem.printer_id == printer_id,
  789. PrintQueueItem.status == "printing",
  790. )
  791. .limit(1)
  792. )
  793. if dispatched_here is not None:
  794. return None
  795. return False
  796. async def _send_kill_switch_provider_notification(
  797. printer_id: int,
  798. printer_name: str,
  799. data: dict,
  800. ) -> bool:
  801. """Send the immediate print-stopped provider notification.
  802. Returning a success flag lets the normal MQTT completion path retry when
  803. this early notification could not be delivered.
  804. """
  805. logger = logging.getLogger(__name__)
  806. try:
  807. async with async_session() as db:
  808. await notification_service.on_print_complete(
  809. printer_id,
  810. printer_name,
  811. "stopped",
  812. data,
  813. db,
  814. )
  815. return True
  816. except Exception as e:
  817. logger.warning(
  818. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  819. printer_id,
  820. e,
  821. )
  822. return False
  823. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  824. """Wait for an immediate kill-switch notification, if one was scheduled."""
  825. if task is None:
  826. return False
  827. try:
  828. return await task
  829. except Exception as e:
  830. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  831. return False
  832. async def _get_plug_energy(plug, db) -> dict | None:
  833. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  834. For HA plugs, configures the service with current settings from DB.
  835. For MQTT plugs, returns data from the subscription service.
  836. For REST plugs, polls the status URL with JSON path extraction.
  837. """
  838. if plug.plug_type == "homeassistant":
  839. from backend.app.api.routes.settings import get_homeassistant_settings
  840. ha_settings = await get_homeassistant_settings(db)
  841. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  842. return await homeassistant_service.get_energy(plug)
  843. elif plug.plug_type == "mqtt":
  844. # MQTT plugs report "today" energy, not lifetime total
  845. # For per-print tracking, we use "today" as the counter (resets at midnight)
  846. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  847. if mqtt_data:
  848. return {
  849. "power": mqtt_data.power,
  850. "today": mqtt_data.energy,
  851. "total": mqtt_data.energy, # Use today as total for per-print calculations
  852. }
  853. return None
  854. elif plug.plug_type == "rest":
  855. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  856. return await rest_smart_plug_service.get_energy(plug)
  857. else:
  858. return await tasmota_service.get_energy(plug)
  859. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  860. """Capture the smart plug lifetime counter on the archive at print start.
  861. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  862. tracking survives a backend restart mid-print. The print-end handler reads
  863. this value back from the DB and computes the delta against the current
  864. plug counter.
  865. """
  866. _logger = logging.getLogger(__name__)
  867. try:
  868. candidates = await energy_plug_candidates(db, printer_id)
  869. if not candidates:
  870. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  871. return False
  872. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  873. if selected is None:
  874. # Naming the plugs matters here: with several linked to one printer
  875. # this is the difference between "the meter is offline" and "you
  876. # linked only accessories" (#2859).
  877. _logger.warning(
  878. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  879. printer_id,
  880. archive.id,
  881. ", ".join(plug.name for plug in candidates),
  882. )
  883. return False
  884. plug, energy = selected
  885. archive.energy_start_kwh = float(energy["total"])
  886. # With the plug's snapshots, what lets the cost follow the price over
  887. # the print rather than take the price at its end (#1251). A price that
  888. # can't be had must not cost the print its energy reading.
  889. archive.energy_start_at = utcnow_naive()
  890. archive.energy_start_plug_id = plug.id
  891. try:
  892. from backend.app.services.energy_price import current_price
  893. archive.energy_start_price = await current_price(db)
  894. except Exception as e:
  895. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  896. archive.energy_start_price = None
  897. await db.commit()
  898. _logger.info(
  899. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  900. f" ({context})" if context else "",
  901. archive.id,
  902. plug.name,
  903. energy["total"],
  904. )
  905. return True
  906. except Exception as e:
  907. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  908. return False
  909. def register_expected_print(
  910. printer_id: int,
  911. filename: str,
  912. archive_id: int,
  913. ams_mapping: list[int] | None = None,
  914. created_by_id: int | None = None,
  915. cost_center_id: int | None = None,
  916. plate_id: int | None = None,
  917. ):
  918. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  919. # Store with multiple filename variations to catch different naming patterns
  920. _expected_prints[(printer_id, filename)] = archive_id
  921. # Also store without .3mf extension if present
  922. if filename.endswith(".3mf"):
  923. base = filename[:-4]
  924. _expected_prints[(printer_id, base)] = archive_id
  925. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  926. # Store AMS mapping for usage tracking at print completion
  927. if ams_mapping is not None:
  928. _print_ams_mappings[archive_id] = ams_mapping
  929. if cost_center_id is not None:
  930. _print_cost_center_ids[archive_id] = cost_center_id
  931. # Store plate_id for usage tracking when this is a single-plate dispatch from
  932. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  933. # file's filament total to the spool instead of just the printed plate (#1697).
  934. if plate_id is not None:
  935. _print_plate_ids[archive_id] = plate_id
  936. # Store created_by_id so the user start email can be sent even when the archive
  937. # itself has no created_by_id (e.g. library-file-based queue prints)
  938. if created_by_id is not None:
  939. _expected_print_creators[(printer_id, filename)] = created_by_id
  940. if filename.endswith(".3mf"):
  941. base = filename[:-4]
  942. _expected_print_creators[(printer_id, base)] = created_by_id
  943. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  944. # Record registration time for TTL-based eviction
  945. _registered_at = time.monotonic()
  946. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  947. if filename.endswith(".3mf"):
  948. base = filename[:-4]
  949. _expected_print_registered_at[(printer_id, base)] = _registered_at
  950. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  951. logging.getLogger(__name__).info(
  952. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  953. )
  954. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  955. """Undo :func:`register_expected_print` when the print never went out.
  956. Registration has to happen *before* the MQTT print command, because the
  957. printer can report the print before the line after the send executes. So
  958. every path that registers and then fails to send — a cancel winning the
  959. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  960. between — leaves an expectation for a print that will never arrive.
  961. The TTL sweep evicts those after two hours, which is far longer than it
  962. takes a user to react to a failed dispatch by pressing print again: that
  963. reprint would be folded into the *old* archive and take the stale
  964. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  965. Mirrors the sweep's rules, including the one that is easy to get wrong:
  966. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  967. file, so they may only be dropped once no live key still points at that
  968. archive.
  969. """
  970. keys = [(printer_id, filename)]
  971. if filename.endswith(".3mf"):
  972. base = filename[:-4]
  973. keys.append((printer_id, base))
  974. keys.append((printer_id, f"{base}.gcode"))
  975. removed = False
  976. for key in keys:
  977. if _expected_prints.pop(key, None) is not None:
  978. removed = True
  979. _expected_print_creators.pop(key, None)
  980. _expected_print_registered_at.pop(key, None)
  981. if archive_id not in set(_expected_prints.values()):
  982. _print_ams_mappings.pop(archive_id, None)
  983. _print_plate_ids.pop(archive_id, None)
  984. if removed:
  985. logging.getLogger(__name__).info(
  986. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  987. printer_id,
  988. filename,
  989. archive_id,
  990. )
  991. def _compute_run_filament_grams(
  992. status: str,
  993. archive_filament_used_grams: float | None,
  994. progress: float | int | None,
  995. usage_results: list[dict] | None,
  996. ) -> float | None:
  997. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  998. Priority for every status:
  999. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1000. weight delta — same source that drives "Total Consumed" on the
  1001. Inventory page, so Stats and Inventory totals stay aligned).
  1002. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1003. back to the canonical "this print used X" value).
  1004. 3. For partial statuses: ``estimate * progress%``.
  1005. 4. ``None`` if nothing is known.
  1006. """
  1007. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1008. if tracked_grams > 0:
  1009. return round(tracked_grams, 1)
  1010. if status == "completed":
  1011. return archive_filament_used_grams
  1012. if archive_filament_used_grams:
  1013. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1014. if scale > 0:
  1015. return round(archive_filament_used_grams * scale, 1)
  1016. return None
  1017. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1018. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1019. stored_ams_mapping = data.get("ams_mapping")
  1020. if not stored_ams_mapping and archive_id:
  1021. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1022. return stored_ams_mapping
  1023. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1024. """Resolve plate_id for print start without consuming stored direct-Print state.
  1025. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1026. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1027. read it back at print-start without popping (the entry is popped on print
  1028. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1029. """
  1030. if archive_id is None:
  1031. return None
  1032. return _print_plate_ids.get(archive_id)
  1033. def _partial_progress_scale(progress: int | float | None) -> float:
  1034. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1035. Used by every site that multiplies a "would-have-used" slicer estimate
  1036. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1037. so the three sites in ``_background_notifications`` (and the per-plate
  1038. override helper) can't drift apart on the coercion shape.
  1039. """
  1040. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1041. def _scope_notification_archive_data_to_plate(
  1042. archive_data: dict,
  1043. archive_file_path: str | None,
  1044. plate_id: int | None,
  1045. print_status: str,
  1046. progress: int | float | None,
  1047. base_dir: Path,
  1048. ) -> dict:
  1049. """Override summed-across-plates totals in ``archive_data`` with the values
  1050. for ``plate_id`` so the completion notification reports what was actually
  1051. printed, not the whole project (#1785).
  1052. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1053. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1054. the archive card's "whole project" headline, wrong for the completion
  1055. notification of a single-plate print. The queue UI already re-reads the
  1056. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1057. notification payload (filament grams, time estimate, per-slot breakdown).
  1058. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1059. no per-plate values — in every fail case the original ``archive_data`` is
  1060. returned unchanged so the notification still sends.
  1061. """
  1062. if plate_id is None or not archive_file_path:
  1063. return archive_data
  1064. from backend.app.utils.threemf_tools import (
  1065. extract_filament_usage_from_3mf,
  1066. extract_print_time_from_3mf,
  1067. )
  1068. archive_path = base_dir / archive_file_path
  1069. if not archive_path.exists():
  1070. return archive_data
  1071. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1072. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1073. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1074. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1075. if plate_time:
  1076. archive_data["print_time_seconds"] = plate_time
  1077. # Gate both the grams headline AND the per-slot breakdown on the same
  1078. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1079. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1080. # to the project-level grams the archive columns already provide rather
  1081. # than ship a project-level headline next to an all-zero per-plate
  1082. # breakdown.
  1083. if plate_grams > 0:
  1084. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1085. archive_data["filament_slots"] = [
  1086. {
  1087. "slot_id": s.get("slot_id"),
  1088. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1089. "type": s.get("type", ""),
  1090. "color": s.get("color", ""),
  1091. }
  1092. for s in plate_slots
  1093. ]
  1094. return archive_data
  1095. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1096. """Best-effort filament metadata from the MQTT print-start snapshot.
  1097. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1098. file during print, see #1533) so the fallback PrintArchive still has
  1099. enough filament info to support the inventory views and AMS-expansion
  1100. planning the operator opens it for. Returns a dict with optional
  1101. ``filament_type`` and ``filament_color`` keys in the same
  1102. comma-separated format the 3MF extractor produces, so the rest of the
  1103. codebase treats the fallback archive identically to a normal one.
  1104. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1105. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1106. entries). When supplied, only the slots actually consumed by this
  1107. print contribute. Without it the function falls back to every loaded
  1108. AMS slot — less accurate but still useful.
  1109. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1110. that the unit tests pass directly, AND the on_print_start callback
  1111. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1112. bambu_mqtt service hands to main.py at runtime. The original
  1113. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1114. handled the inner shape and silently returned ``{}`` for every real
  1115. print start, leaving fallback archives' filament fields NULL — the
  1116. exact regression the fix was meant to close. Reported with a log
  1117. proving the AMS state was right there at
  1118. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1119. """
  1120. result: dict[str, str] = {}
  1121. # Look at the on_print_start wrapper first, then the inner shape.
  1122. raw_data = (data or {}).get("raw_data")
  1123. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1124. if not isinstance(ams_root, dict):
  1125. ams_root = (data or {}).get("ams") or {}
  1126. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1127. if not isinstance(ams_units, list) or not ams_units:
  1128. return result
  1129. # Map global tray id (unit * 4 + tray) → (type, color).
  1130. loaded: dict[int, tuple[str, str]] = {}
  1131. for unit in ams_units:
  1132. if not isinstance(unit, dict):
  1133. continue
  1134. try:
  1135. unit_id = int(unit.get("id", 0))
  1136. except (TypeError, ValueError):
  1137. continue
  1138. for tray in unit.get("tray") or []:
  1139. if not isinstance(tray, dict):
  1140. continue
  1141. try:
  1142. tray_id = int(tray.get("id", 0))
  1143. except (TypeError, ValueError):
  1144. continue
  1145. ttype = (tray.get("tray_type") or "").strip()
  1146. tcolor = (tray.get("tray_color") or "").strip().upper()
  1147. if not ttype:
  1148. continue # Empty / unloaded slot.
  1149. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1150. if not loaded:
  1151. return result
  1152. if ams_mapping:
  1153. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1154. filaments = [loaded[g] for g in used_ids if g in loaded]
  1155. if not filaments:
  1156. return result # Mapping points entirely at slots we have no data for.
  1157. else:
  1158. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1159. types_joined = ",".join(f[0] for f in filaments)
  1160. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1161. # Column limits per backend/app/models/archive.py: filament_type=50,
  1162. # filament_color=200.
  1163. if types_joined:
  1164. result["filament_type"] = types_joined[:50]
  1165. if colors_joined:
  1166. result["filament_color"] = colors_joined[:200]
  1167. return result
  1168. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1169. """Start a layer-timelapse session for *archive_id* when the printer has
  1170. an external camera configured. Returns True if a session was started.
  1171. Three call sites in on_print_start (expected-archive promotion, fallback
  1172. archive creation, fresh-archive creation) used to inline this same
  1173. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1174. on the first pass). Centralising the conditional + call here makes the
  1175. contract testable in isolation and keeps the three sites locked in step.
  1176. """
  1177. if not (printer.external_camera_enabled and printer.external_camera_url):
  1178. return False
  1179. from backend.app.services.layer_timelapse import start_session
  1180. start_session(
  1181. printer_id,
  1182. archive_id,
  1183. printer.external_camera_url,
  1184. printer.external_camera_type or "mjpeg",
  1185. snapshot_url=printer.external_camera_snapshot_url,
  1186. rotation=getattr(printer, "camera_rotation", 0),
  1187. )
  1188. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1189. return True
  1190. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1191. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1192. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1193. — since #2926 — the description the parser already resolved, which is preferred
  1194. when present so the queue's failure reason reads the same as the status
  1195. response. The short code still produces the bracketed label, and still
  1196. resolves the sentence for a caller whose entries predate the field. An entry
  1197. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1198. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1199. label when no description is on file. Returns None for an empty list so
  1200. callers can leave error_message unset.
  1201. """
  1202. if not hms_errors:
  1203. return None
  1204. from backend.app.services.hms_errors import get_error_description
  1205. parts: list[str] = []
  1206. for err in hms_errors:
  1207. try:
  1208. # `_hms_short_code` rather than a local derivation: this one used to
  1209. # format the error without masking it to 16 bits, so an `hms[]` entry
  1210. # whose code carries an alert-level group produced a five-digit label
  1211. # like "0500_3000A" — not a code the user can look up, and never a
  1212. # catalogue key, so the sentence was lost with it.
  1213. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1214. except (TypeError, ValueError):
  1215. continue
  1216. description = err.get("description") or get_error_description(short_code)
  1217. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1218. # groups and is not a code anyone can look up; its full code in the
  1219. # printer screen's four groups is (#2728).
  1220. full_code = str(err.get("full_code") or "")
  1221. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1222. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1223. return "; ".join(parts) if parts else None
  1224. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1225. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1226. print completes successfully. Gated to status=='completed': failed, cancelled
  1227. and aborted prints do not count as usage. Caller is responsible for committing
  1228. the session. No-op when the queue item has no linked library file (e.g. reprints
  1229. from an archive). See #1008."""
  1230. if queue_status != "completed" or item.library_file_id is None:
  1231. return
  1232. from backend.app.models.library import LibraryFile
  1233. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1234. if lib_file is None:
  1235. return
  1236. lib_file.print_count = (lib_file.print_count or 0) + 1
  1237. lib_file.last_printed_at = datetime.now(timezone.utc)
  1238. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1239. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1240. When on_print_complete fires with status 'failed' for a printer in this set we
  1241. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1242. rather than a 'print failed' notification.
  1243. """
  1244. _user_stopped_printers.add(printer_id)
  1245. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1246. _last_status_broadcast: dict[int, str] = {}
  1247. # Track printers where we've updated nozzle_count
  1248. _nozzle_count_updated: set[int] = set()
  1249. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1250. """Wait the debounce window then fire `on_printer_offline` if the printer
  1251. is still offline.
  1252. Scheduled by `on_printer_status_change` on the connected → disconnected
  1253. edge (#1752). Cancelled by the same handler if the printer reconnects
  1254. before the window elapses, so a single MQTT blip + recovery doesn't
  1255. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1256. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1257. route through the same status-change callback, so this covers both.
  1258. """
  1259. logger = logging.getLogger(__name__)
  1260. try:
  1261. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1262. still_offline = not printer_manager.is_connected(printer_id)
  1263. logger.info(
  1264. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1265. printer_id,
  1266. still_offline,
  1267. )
  1268. if not still_offline:
  1269. return
  1270. async with async_session() as db:
  1271. from backend.app.models.printer import Printer
  1272. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1273. printer = result.scalar_one_or_none()
  1274. if not printer:
  1275. logger.warning(
  1276. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1277. printer_id,
  1278. )
  1279. return
  1280. logger.info(
  1281. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1282. printer_id,
  1283. printer.name,
  1284. )
  1285. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1286. except asyncio.CancelledError:
  1287. raise
  1288. except Exception as e:
  1289. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1290. finally:
  1291. _printer_offline_notify_tasks.pop(printer_id, None)
  1292. def _hms_notify_key(error) -> str:
  1293. """What identifies a fault for notification de-duplication.
  1294. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1295. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1296. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1297. and -0006 together) shared a key and only the first was ever notified. An
  1298. entry without a full code falls back to attr and code together.
  1299. """
  1300. full_code = getattr(error, "full_code", "") or ""
  1301. if full_code:
  1302. return full_code.upper()
  1303. return f"{error.attr:08X}:{error.code}"
  1304. def _hms_fault_counts(error) -> bool:
  1305. """Whether a fault counts as a problem: the same rule the frontend's
  1306. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1307. It counts when Bambu publishes text for it or it offers action buttons, and
  1308. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1309. no actions does not count: those are things like "the top cover is open" or
  1310. "the chamber is hot, fan speed increased", which a printer can hold through
  1311. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1312. it always has; those are prompts such as "unable to start drying" (#2728).
  1313. """
  1314. if error.severity < 1:
  1315. return False
  1316. has_actions = bool(getattr(error, "actions", None))
  1317. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1318. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1319. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1320. """The new faults that count (see ``_hms_fault_counts``).
  1321. These go to the MQTT relay; the caller also needs a description before it
  1322. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1323. used to read ``severity >= 2`` when severity held the part byte; on the real
  1324. level that would drop the task-stopping errors (#2728).
  1325. """
  1326. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1327. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1328. """The faults on this printer not notified yet, and record them as notified.
  1329. Tracking is updated before anything is sent, so concurrent status callbacks
  1330. cannot notify the same fault twice. A notified fault is forgotten once it
  1331. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1332. and on is notified once (#3226), while one that clears and comes back much
  1333. later is notified again.
  1334. When ``print_state`` changes (a print resumed, started or finished), every
  1335. fault recorded so far is forgotten the first time it is gone, without the
  1336. wait: a runout fixed before resuming must be notified if it happens again a
  1337. few minutes later, while the printer sits paused. Not only the faults gone
  1338. at the change itself, because the update that flips the state can still
  1339. carry the old fault (a ``print_error`` entry stays until a payload brings
  1340. ``hms``).
  1341. """
  1342. now = time.time()
  1343. current = {_hms_notify_key(e) for e in errors}
  1344. seen = _notified_hms_errors.setdefault(printer_id, {})
  1345. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1346. if print_state is not None:
  1347. print_state = print_state.upper()
  1348. if _hms_print_state.get(printer_id, print_state) != print_state:
  1349. forget_when_gone.update(seen)
  1350. _hms_print_state[printer_id] = print_state
  1351. for key, last_seen in list(seen.items()):
  1352. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1353. del seen[key]
  1354. forget_when_gone.discard(key)
  1355. new = current - seen.keys()
  1356. for key in current:
  1357. seen[key] = now
  1358. if not seen:
  1359. _notified_hms_errors.pop(printer_id, None)
  1360. if not forget_when_gone:
  1361. _hms_forget_when_gone.pop(printer_id, None)
  1362. return _hms_errors_to_notify(errors, new)
  1363. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1364. # "Printing", -1 and 255 are "no stage" (#3211).
  1365. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1366. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1367. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1368. Records it as notified. Called only for a printing state with progress above 0.
  1369. Progress before the first layer is not progress through the print (#3211).
  1370. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1371. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1372. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1373. 75% notification together with Print Started, and since 75 was then on
  1374. record, 25 and 50 could never fire. So nothing counts while the printer
  1375. reports a layer count but has not started layer 1.
  1376. Without a layer count -- a print whose first frame carried no
  1377. ``total_layer_num``, until the pushall that asks for it is answered
  1378. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1379. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1380. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1381. reports neither keeps the old behaviour rather than never notifying.
  1382. """
  1383. if (state.layer_num or 0) < 1:
  1384. if (state.total_layers or 0) > 0:
  1385. return None
  1386. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1387. return None
  1388. progress = state.progress or 0
  1389. current_milestone = 0
  1390. if progress >= 75:
  1391. current_milestone = 75
  1392. elif progress >= 50:
  1393. current_milestone = 50
  1394. elif progress >= 25:
  1395. current_milestone = 25
  1396. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1397. _last_progress_milestone[printer_id] = current_milestone
  1398. return current_milestone
  1399. return None
  1400. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1401. """Handle printer status changes - broadcast via WebSocket."""
  1402. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1403. # transitions disconnected → connected — which covers both Bambuddy
  1404. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1405. # `reconcile_stale_active_prints` exactly once for this connection so
  1406. # any archive still in `status="printing"` that can't actually be
  1407. # running anymore (printer IDLE / different subtask / empty subtask)
  1408. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1409. # finished during a disconnect window + a smart-plug power cycle
  1410. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1411. # next boot. Reconciliation runs concurrently — it must not block the
  1412. # WebSocket dedup / broadcast logic below, and the connected edge is
  1413. # marked True BEFORE the await so concurrent status updates inside
  1414. # the same connection don't re-trigger reconciliation.
  1415. #
  1416. # Wait for a real push_status before reconciling (#1679): MQTT
  1417. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1418. # the connection, BEFORE `_request_push_all` round-trips. At that
  1419. # instant the `PrinterState` is still on construction defaults — most
  1420. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1421. # If reconcile spawns here, every in-flight archive falls through to
  1422. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1423. # creates a duplicate archive on the real PRINT COMPLETE and
  1424. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1425. # keeps the #1542 mechanism intact: once the first real push_status
  1426. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1427. # fires again with the flag still False — reconcile then runs against
  1428. # actual evidence.
  1429. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1430. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1431. _printer_reconciled_since_connect[printer_id] = True
  1432. spawn_background_task(
  1433. reconcile_stale_active_prints(printer_id),
  1434. name=f"reconcile-stale-prints-{printer_id}",
  1435. )
  1436. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1437. # Re-arm so the next reconnect triggers reconciliation again.
  1438. _printer_reconciled_since_connect[printer_id] = False
  1439. # Same edge, for the calibration table the AMS card reads its K values from.
  1440. #
  1441. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1442. # tables to ask for. A `state_known` gate alone is not enough: the first
  1443. # real push_status is what makes the state known, and the nozzle fields do
  1444. # not always arrive in it. Latching there would spend this connection's one
  1445. # attempt on a printer that could not yet say what was fitted.
  1446. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1447. if (
  1448. state.connected
  1449. and state_known
  1450. and nozzle_known
  1451. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1452. ):
  1453. _printer_kprofiles_primed_since_connect[printer_id] = True
  1454. spawn_background_task(
  1455. prime_kprofile_table(printer_id),
  1456. name=f"prime-kprofiles-{printer_id}",
  1457. )
  1458. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1459. _printer_kprofiles_primed_since_connect[printer_id] = False
  1460. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1461. # else in the AMS report changing -- a power cycle does it to every slot --
  1462. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1463. # while the printer is idle; needs_check is cheap and throttled per slot.
  1464. # Guarded: nothing here may stop the status broadcast below.
  1465. try:
  1466. if not state.connected:
  1467. kprofile_drift.forget_printer(printer_id)
  1468. elif kprofile_drift.needs_check(printer_id, state):
  1469. spawn_background_task(
  1470. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1471. name=f"reapply-kprofiles-{printer_id}",
  1472. )
  1473. except Exception:
  1474. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1475. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1476. # connected → disconnected. The "back online" channel is already covered
  1477. # by the print-failure notification (firmware reports gcode_state=FAILED
  1478. # on reconnect of an interrupted print), so we don't add a symmetric
  1479. # online event here.
  1480. prev_connected = _printer_last_connected.get(printer_id)
  1481. _printer_last_connected[printer_id] = state.connected
  1482. if prev_connected is True and not state.connected:
  1483. existing = _printer_offline_notify_tasks.get(printer_id)
  1484. if existing is None or existing.done():
  1485. logging.getLogger(__name__).info(
  1486. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1487. printer_id,
  1488. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1489. )
  1490. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1491. _maybe_notify_printer_offline(printer_id),
  1492. name=f"printer-offline-notify-{printer_id}",
  1493. )
  1494. elif state.connected:
  1495. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1496. if pending is not None and not pending.done():
  1497. logging.getLogger(__name__).info(
  1498. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1499. printer_id,
  1500. )
  1501. pending.cancel()
  1502. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1503. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1504. temps = state.temperatures or {}
  1505. nozzle_temp = round(temps.get("nozzle", 0))
  1506. bed_temp = round(temps.get("bed", 0))
  1507. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1508. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1509. # Auto-detect dual-nozzle printers from MQTT temperature data
  1510. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1511. _nozzle_count_updated.add(printer_id)
  1512. # Update nozzle_count in database
  1513. async with async_session() as db:
  1514. from backend.app.models.printer import Printer
  1515. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1516. printer = result.scalar_one_or_none()
  1517. if printer and printer.nozzle_count != 2:
  1518. printer.nozzle_count = 2
  1519. await db.commit()
  1520. logging.getLogger(__name__).info(
  1521. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1522. )
  1523. # Include target temps for heating phase detection
  1524. bed_target = round(temps.get("bed_target", 0))
  1525. nozzle_target = round(temps.get("nozzle_target", 0))
  1526. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1527. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1528. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1529. #
  1530. # dry_countdown_stalled rides along because it is the one drying signal the
  1531. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1532. # dry_time stopped moving, so on the frame that flips it every other member
  1533. # of this key is identical and the push would be deduplicated away. Mid-print
  1534. # a temperature would eventually break the tie, but a parked command on an
  1535. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1536. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1537. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1538. ams_dry_key = (
  1539. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1540. if state.raw_data
  1541. else ()
  1542. )
  1543. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1544. #
  1545. # The filament identity fields are here because Configure Slot writes
  1546. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1547. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1548. # matched, this function returned before broadcasting, and the card kept
  1549. # showing the old filament until the 30s fallback poll or a page reload —
  1550. # even though the configure route asks the printer for a fresh pushall and
  1551. # that push does carry the new values. Reset always worked, because it
  1552. # clears tray_type.
  1553. #
  1554. # These fields only change when someone configures a slot or swaps a spool,
  1555. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1556. ams_tray_key = (
  1557. tuple(
  1558. (
  1559. t.get("id"),
  1560. t.get("tray_type", ""),
  1561. t.get("state"),
  1562. t.get("tray_color", ""),
  1563. t.get("tray_info_idx", ""),
  1564. t.get("tray_sub_brands", ""),
  1565. t.get("cali_idx"),
  1566. )
  1567. for a in (state.raw_data.get("ams") or [])
  1568. for t in a.get("tray", [])
  1569. )
  1570. if state.raw_data
  1571. else ()
  1572. )
  1573. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1574. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1575. # in the AMS change-hash (tray fields only, and widening that would fire
  1576. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1577. # screen changed no key at all and the card's inlet badges sat stale until a
  1578. # reload. Like the filament-backup flag, these only move when someone
  1579. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1580. fts_key = (
  1581. state.fila_switch.installed if state.fila_switch else False,
  1582. tuple(sorted(state.ams_switch_inlet.items())),
  1583. # Which hotend holds which slot. Unlike the two above this does move
  1584. # mid-print, on every filament change — but only between discrete slots,
  1585. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1586. # it live: it decides which hotend the Load dialog may offer and whether
  1587. # Unload has anything to act on.
  1588. tuple(
  1589. sorted(
  1590. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1591. # Sort on the extruder id alone: the other members are nullable
  1592. # and comparing None with an int raises.
  1593. key=lambda entry: entry[0],
  1594. )
  1595. ),
  1596. )
  1597. status_key = (
  1598. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1599. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1600. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1601. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1602. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1603. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1604. )
  1605. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1606. if not is_active_print:
  1607. _unauthorized_print_kill_sent.discard(printer_id)
  1608. elif printer_id in _unauthorized_print_kill_sent:
  1609. # stop_print() was already sent for this print; avoid all further
  1610. # ownership and settings work until the printer leaves an active state.
  1611. pass
  1612. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1613. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1614. _unauthorized_print_kill_sent.discard(printer_id)
  1615. else:
  1616. kill_switch_enabled = False
  1617. authorization: bool | None = None
  1618. status_logger = logging.getLogger(__name__)
  1619. try:
  1620. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1621. if kill_switch_enabled:
  1622. async with async_session() as db:
  1623. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1624. except Exception as e:
  1625. # Fail safe: a database/reconciliation error must never turn into an
  1626. # irreversible stop of a print whose ownership is still unknown.
  1627. authorization = None
  1628. status_logger.warning(
  1629. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1630. )
  1631. if not kill_switch_enabled or authorization is True:
  1632. _unauthorized_print_kill_sent.discard(printer_id)
  1633. elif authorization is None:
  1634. _unauthorized_print_kill_sent.discard(printer_id)
  1635. status_logger.debug(
  1636. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1637. printer_id,
  1638. )
  1639. else:
  1640. try:
  1641. stopped = printer_manager.stop_print(printer_id)
  1642. if stopped:
  1643. _unauthorized_print_kill_sent.add(printer_id)
  1644. printer_info = printer_manager.get_printer(printer_id)
  1645. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1646. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1647. notification_data = {
  1648. "status": "stopped",
  1649. "filename": state.gcode_file or state.current_print or "",
  1650. "subtask_name": state.subtask_name or "",
  1651. "progress": state.progress,
  1652. "reason": "unauthorized_print",
  1653. }
  1654. status_logger.warning(
  1655. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1656. printer_id,
  1657. state.state,
  1658. )
  1659. try:
  1660. await ws_manager.broadcast(
  1661. {
  1662. "type": "kill_switch_triggered",
  1663. "printer_id": printer_id,
  1664. "printer_name": printer_name,
  1665. "filename": filename,
  1666. "reason": "unauthorized_print",
  1667. }
  1668. )
  1669. except Exception as e:
  1670. status_logger.warning(
  1671. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1672. )
  1673. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1674. if previous_task is not None and not previous_task.done():
  1675. previous_task.cancel()
  1676. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1677. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1678. name=f"kill-switch-notification-{printer_id}",
  1679. )
  1680. else:
  1681. status_logger.warning(
  1682. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1683. printer_id,
  1684. state.state,
  1685. )
  1686. except Exception as e:
  1687. status_logger.warning(
  1688. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1689. )
  1690. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1691. try:
  1692. printer_info = printer_manager.get_printer(printer_id)
  1693. if printer_info:
  1694. await mqtt_relay.on_printer_status(
  1695. printer_id,
  1696. state,
  1697. printer_info.name,
  1698. printer_info.serial_number,
  1699. printer_manager.is_awaiting_plate_clear(printer_id),
  1700. )
  1701. except Exception:
  1702. pass # Don't fail status callback if MQTT fails
  1703. if _last_status_broadcast.get(printer_id) == status_key:
  1704. return # No change, skip WebSocket broadcast
  1705. _last_status_broadcast[printer_id] = status_key
  1706. # Check for progress milestone notifications (25%, 50%, 75%)
  1707. progress = state.progress or 0
  1708. is_printing = state.state in ("RUNNING", "PRINTING")
  1709. if is_printing and progress > 0:
  1710. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1711. if current_milestone is not None:
  1712. try:
  1713. from backend.app.models.printer import Printer
  1714. # Read the printer in a short session and release the connection
  1715. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1716. # pinned a pooled connection per milestone, per printer (issue #2572).
  1717. async with async_session() as db:
  1718. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1719. printer = result.scalar_one_or_none()
  1720. printer_name = printer.name if printer else f"Printer {printer_id}"
  1721. filename = state.subtask_name or state.gcode_file or "Unknown"
  1722. # remaining_time is in minutes, convert to seconds for notification
  1723. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1724. # Capture camera snapshot for notification image attachment (no DB held).
  1725. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1726. # Notification send needs a session (provider/template lookups).
  1727. async with async_session() as db:
  1728. await notification_service.on_print_progress(
  1729. printer_id,
  1730. printer_name,
  1731. filename,
  1732. current_milestone,
  1733. db,
  1734. remaining_time_seconds,
  1735. image_data=image_data,
  1736. )
  1737. except Exception as e:
  1738. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1739. elif progress < 5:
  1740. # Reset milestone tracking when print restarts or new print begins
  1741. _last_progress_milestone[printer_id] = 0
  1742. _first_layer_notified[printer_id] = False
  1743. # HMS error codes that should not trigger notifications even though they
  1744. # have known descriptions (e.g. user-initiated actions, not real errors).
  1745. _HMS_NOTIFICATION_SUPPRESS = {
  1746. "0500_400E", # Printing was cancelled (user action, not an error)
  1747. }
  1748. # Check for new HMS errors and send notifications
  1749. current_hms_errors = getattr(state, "hms_errors", []) or []
  1750. if current_hms_errors:
  1751. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1752. if new_errors:
  1753. try:
  1754. from backend.app.models.printer import Printer
  1755. # Read the printer in a short session and release the connection
  1756. # BEFORE the ~15s camera snapshot below (issue #2572).
  1757. async with async_session() as db:
  1758. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1759. printer = result.scalar_one_or_none()
  1760. printer_name = printer.name if printer else f"Printer {printer_id}"
  1761. # Format error details for notification
  1762. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1763. module_names = {
  1764. 0x03: "Print/Task",
  1765. 0x05: "Nozzle/Extruder",
  1766. 0x07: "AMS/Filament",
  1767. 0x0C: "Motion Controller",
  1768. 0x12: "Chamber",
  1769. }
  1770. # Capture camera snapshot once for all error notifications (no DB held).
  1771. error_image_data = await _capture_snapshot_for_notification(
  1772. printer_id, printer, logging.getLogger(__name__)
  1773. )
  1774. # Notification sends need a session (provider/template lookups).
  1775. async with async_session() as db:
  1776. sent_count = 0
  1777. for error in new_errors:
  1778. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1779. # Build short code like "0700_8010"
  1780. # Mask to 16 bits to handle printers that send larger values
  1781. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1782. error_code_masked = error_code_int & 0xFFFF
  1783. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1784. # Only notify for errors Bambu publishes text for — printers
  1785. # send undocumented codes that aren't real errors, and Bambu
  1786. # lists some with empty text. Resolved at parse time (#2926);
  1787. # short_code is still needed for the suppression set below.
  1788. description = error.description
  1789. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1790. continue
  1791. error_type = f"{module_name} Error"
  1792. error_detail = description
  1793. await notification_service.on_printer_error(
  1794. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1795. )
  1796. sent_count += 1
  1797. if sent_count:
  1798. logging.getLogger(__name__).info(
  1799. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1800. )
  1801. # Also publish to MQTT relay (no DB): every new fault that
  1802. # counts, with or without text, the same set the UI counts.
  1803. printer_info = printer_manager.get_printer(printer_id)
  1804. if printer_info:
  1805. errors_data = [
  1806. {
  1807. "code": e.code,
  1808. "attr": e.attr,
  1809. "module": e.module,
  1810. "severity": e.severity,
  1811. }
  1812. for e in new_errors
  1813. ]
  1814. await mqtt_relay.on_printer_error(
  1815. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1816. )
  1817. except Exception as e:
  1818. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1819. else:
  1820. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1821. # across a print state change) are forgotten. Some codes, e.g. chamber
  1822. # temperature regulation during PETG prints, toggle every few seconds.
  1823. _take_new_hms_faults(printer_id, [], state.state)
  1824. await ws_manager.send_printer_status(
  1825. printer_id,
  1826. printer_state_to_dict(
  1827. state,
  1828. printer_id,
  1829. printer_manager.get_model(printer_id),
  1830. printer_manager.get_drying_targets(printer_id),
  1831. ),
  1832. )
  1833. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1834. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1835. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1836. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1837. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1838. K-profiles are per-nozzle and the printer's calibration table is numbered
  1839. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1840. switch's other inlet therefore silently invalidates every configured slot in
  1841. it: the index stays put and now resolves against the other nozzle's table.
  1842. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1843. and 0.020 on the right kept the left profile after the move, and a manual
  1844. RFID re-read only re-asserted the same wrong one.
  1845. Configuring a slot is a deliberate preparation step, so this re-selects
  1846. rather than re-configures: only the calibration binding moves, and only for
  1847. slots whose spool already has a stored profile for the new nozzle. A slot
  1848. Bambuddy knows nothing about is left exactly as the operator left it.
  1849. """
  1850. logger = logging.getLogger(__name__)
  1851. target_extruder = extruder_for_inlet(inlet)
  1852. if target_extruder is None:
  1853. return
  1854. client = printer_manager.get_client(printer_id)
  1855. state = printer_manager.get_status(printer_id)
  1856. if not client or not state or not state.raw_data:
  1857. return
  1858. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1859. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1860. # the nozzle width, which changes both the K profile to select and the
  1861. # preset the slot should carry.
  1862. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1863. ams_raw = state.raw_data.get("ams")
  1864. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1865. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1866. if not unit:
  1867. return
  1868. try:
  1869. async with async_session() as db:
  1870. for tray in unit.get("tray", []):
  1871. tray_id = int(tray.get("id", -1))
  1872. if tray_id < 0 or not tray.get("tray_type"):
  1873. continue
  1874. current_idx = tray.get("cali_idx")
  1875. profile = await find_slot_kprofile_for_extruder(
  1876. db,
  1877. printer_id,
  1878. ams_id,
  1879. tray_id,
  1880. target_extruder,
  1881. nozzle_diameter,
  1882. printer_manager.get_model(printer_id),
  1883. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1884. )
  1885. if profile is None or profile.cali_idx is None:
  1886. continue
  1887. if current_idx == profile.cali_idx:
  1888. continue # Already on the right one.
  1889. logger.info(
  1890. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1891. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1892. printer_id,
  1893. ams_id,
  1894. tray_id,
  1895. inlet,
  1896. target_extruder,
  1897. profile.name,
  1898. current_idx,
  1899. profile.cali_idx,
  1900. profile.k_value,
  1901. )
  1902. client.extrusion_cali_sel(
  1903. ams_id=ams_id,
  1904. tray_id=tray_id,
  1905. cali_idx=profile.cali_idx,
  1906. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1907. nozzle_diameter=nozzle_diameter,
  1908. )
  1909. except Exception as e:
  1910. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1911. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  1912. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  1913. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  1914. from the delayed re-check -- which is why it takes the AMS data and print
  1915. state as arguments instead of reading them from the push (#3186).
  1916. """
  1917. logger = logging.getLogger(__name__)
  1918. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1919. # Auto-unlink spool assignments with stale fingerprints. Under the
  1920. # per-printer assignment lock since #3186: the held-removal re-check runs
  1921. # this outside any MQTT push, so it can now overlap one.
  1922. try:
  1923. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1924. from sqlalchemy.orm import selectinload
  1925. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1926. from backend.app.models.spool import Spool as _Spool
  1927. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1928. from backend.app.services.ams_slot_presence import spool_present
  1929. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1930. # Built-in assignments only. Since #2812 they survive a switch to
  1931. # Spoolman mode rather than being deleted by it, and this pass ends
  1932. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1933. # time as the AMS contents changed under the other mode, undoing the
  1934. # preservation more slowly but just as completely.
  1935. assignments = []
  1936. if not await spoolman_owns_assignments(db):
  1937. result = await db.execute(
  1938. select(SA)
  1939. .where(SA.printer_id == printer_id)
  1940. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1941. )
  1942. assignments = result.scalars().all()
  1943. # ``printing_now`` (top of this function) keeps a runout from
  1944. # unlinking the spool that fed the print — the next idle-time pass
  1945. # unlinks it if the user really did take it out.
  1946. stale = []
  1947. # Removals this pass is holding rather than unlinking (#3186).
  1948. held: set[tuple] = set()
  1949. for assignment in assignments:
  1950. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1951. if assignment.ams_id == 255:
  1952. ps = printer_manager.get_status(printer_id)
  1953. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1954. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1955. current_tray = None
  1956. for vt in vt_tray_raw:
  1957. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1958. current_tray = vt
  1959. break
  1960. if not current_tray:
  1961. # vt_tray data may not have arrived yet — keep assignment
  1962. continue
  1963. else:
  1964. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1965. if not current_tray:
  1966. if printing_now:
  1967. logger.info(
  1968. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1969. assignment.spool_id,
  1970. assignment.ams_id,
  1971. assignment.tray_id,
  1972. )
  1973. continue
  1974. # A whole AMS unit can drop out of one push and come back in
  1975. # the next; only a slot that stays gone is a removal (#3186).
  1976. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  1977. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  1978. held.add(hold_key)
  1979. logger.info(
  1980. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  1981. "unlinking if it is still gone in %ds",
  1982. assignment.spool_id,
  1983. assignment.ams_id,
  1984. assignment.tray_id,
  1985. int(slot_unlink_grace.GRACE_SECONDS),
  1986. )
  1987. continue
  1988. logger.info(
  1989. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1990. assignment.spool_id,
  1991. assignment.ams_id,
  1992. assignment.tray_id,
  1993. )
  1994. stale.append(assignment) # Slot empty
  1995. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1996. # A Bambu Lab spool is in this slot — check if it's the same spool
  1997. # that's currently assigned. If yes, keep the assignment (avoids
  1998. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1999. # the printer's filament preset on every startup).
  2000. tray_uuid = current_tray.get("tray_uuid", "")
  2001. tag_uid = current_tray.get("tag_uid", "")
  2002. spool = assignment.spool
  2003. spool_matches = False
  2004. if spool:
  2005. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2006. spool.tag_uid
  2007. and tag_uid
  2008. and tag_uid != "0000000000000000"
  2009. and spool.tag_uid.upper() == tag_uid.upper()
  2010. ):
  2011. spool_matches = True
  2012. if spool_matches:
  2013. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2014. cur_color = current_tray.get("tray_color", "")
  2015. cur_type = current_tray.get("tray_type", "")
  2016. fp_color = assignment.fingerprint_color or ""
  2017. fp_type = assignment.fingerprint_type or ""
  2018. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2019. assignment.fingerprint_color = cur_color
  2020. assignment.fingerprint_type = cur_type
  2021. logger.debug(
  2022. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2023. assignment.spool_id,
  2024. assignment.ams_id,
  2025. assignment.tray_id,
  2026. )
  2027. continue
  2028. # Different BL spool or unrecognized — unlink so auto-assign can match
  2029. logger.info(
  2030. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2031. assignment.spool_id,
  2032. assignment.ams_id,
  2033. assignment.tray_id,
  2034. tray_uuid,
  2035. )
  2036. stale.append(assignment)
  2037. else:
  2038. cur_color = current_tray.get("tray_color", "")
  2039. cur_type = current_tray.get("tray_type", "")
  2040. cur_state = current_tray.get("state")
  2041. fp_color = assignment.fingerprint_color or ""
  2042. fp_type = assignment.fingerprint_type or ""
  2043. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2044. # the slot was empty when the user pre-assigned via SpoolBuddy
  2045. # (the firmware drops ams_filament_setting on empty slots, so
  2046. # MQTT was deferred). The moment any filament gets inserted
  2047. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2048. # reconfigured spool — fire the deferred configuration.
  2049. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2050. # extruder" code) OR, on firmwares that don't use the state
  2051. # enum meaningfully, a non-empty tray_type when state is
  2052. # NOT one of the firmware's explicit empty signals (9, 10).
  2053. # state-only was wrong for firmwares that never set 11 — A1
  2054. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2055. # always report state=3 — so the replay never fired for them
  2056. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2057. # explicit "empty" signals authoritative over any stale
  2058. # tray_type that might survive the relay's auto-clearing.
  2059. #
  2060. # tray_exist_bits comes first because that guard cannot tell
  2061. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2062. # writes state=9 when the bit is 0 and leaves it there when the
  2063. # bit returns. A non-RFID spool inserted into a pre-assigned
  2064. # slot brings no tray_type with it, so the stale 9 made this
  2065. # expression false forever and the deferred config never fired
  2066. # — the deadlock #1322 removed from the assign path, still in
  2067. # place here (#3084, #3100).
  2068. loaded = spool_present(current_tray) is True or (
  2069. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2070. )
  2071. if not fp_type.strip() and loaded and assignment.spool:
  2072. try:
  2073. from backend.app.api.routes.inventory import (
  2074. apply_spool_to_slot_via_mqtt,
  2075. )
  2076. await apply_spool_to_slot_via_mqtt(
  2077. db=db,
  2078. current_user=None,
  2079. spool=assignment.spool,
  2080. printer_id=printer_id,
  2081. ams_id=assignment.ams_id,
  2082. tray_id=assignment.tray_id,
  2083. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2084. current_tray_type=cur_type,
  2085. )
  2086. logger.info(
  2087. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2088. assignment.spool_id,
  2089. printer_id,
  2090. assignment.ams_id,
  2091. assignment.tray_id,
  2092. )
  2093. except Exception:
  2094. logger.exception(
  2095. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2096. assignment.spool_id,
  2097. printer_id,
  2098. assignment.ams_id,
  2099. assignment.tray_id,
  2100. )
  2101. assignment.fingerprint_color = cur_color
  2102. assignment.fingerprint_type = cur_type
  2103. continue
  2104. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2105. # Blank tray data mid-print is a runout, not a swap: the
  2106. # firmware clears colour and type when it unloads a spool
  2107. # it just emptied. Unlinking here would erase the record
  2108. # of which spool fed the print so far.
  2109. if printing_now and not cur_color.strip() and not cur_type.strip():
  2110. logger.info(
  2111. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2112. "(runout?)",
  2113. assignment.spool_id,
  2114. assignment.ams_id,
  2115. assignment.tray_id,
  2116. )
  2117. continue
  2118. # Same reasoning off the print, on firmware's own say-so:
  2119. # a blank tray report from a slot whose tray_exist_bits
  2120. # bit is set describes a spool the AMS cannot identify —
  2121. # a non-RFID one, or one whose slot was reset — not a
  2122. # spool that was taken out. Deleting the assignment there
  2123. # threw away the identity the user had supplied, which is
  2124. # the only place it existed (#3100). A slot the bit calls
  2125. # empty, or one that carries no bit at all, still unlinks.
  2126. #
  2127. # Unless the slot was reported empty first: a removal
  2128. # already held means a spool came out and another went
  2129. # in, so the blank report keeps the hold running below
  2130. # rather than cancelling it (#3186).
  2131. if (
  2132. spool_present(current_tray) is True
  2133. and not cur_color.strip()
  2134. and not cur_type.strip()
  2135. and not slot_unlink_grace.is_held(
  2136. printer_id,
  2137. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2138. )
  2139. ):
  2140. logger.info(
  2141. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2142. "tray reports no filament data yet",
  2143. assignment.spool_id,
  2144. assignment.ams_id,
  2145. assignment.tray_id,
  2146. )
  2147. continue
  2148. # A blank report the presence bit does not vouch for is
  2149. # still only one push. An idle X1C cleared a whole AMS
  2150. # unit's bits, colour and type for a moment and lost
  2151. # four saved assignments that way (#3186); unlink only
  2152. # if the slot is still blank after the grace period.
  2153. if not cur_color.strip() and not cur_type.strip():
  2154. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2155. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2156. held.add(hold_key)
  2157. logger.info(
  2158. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2159. "unlinking if it is still blank in %ds",
  2160. assignment.spool_id,
  2161. assignment.ams_id,
  2162. assignment.tray_id,
  2163. int(slot_unlink_grace.GRACE_SECONDS),
  2164. )
  2165. continue
  2166. # Fingerprint mismatch — but check if tray now matches the
  2167. # assigned spool (e.g. auto-configure changed the tray).
  2168. # Both sides are reduced to the type the slot can carry
  2169. # before comparing: the assign path writes that rather
  2170. # than the spool's raw material (#2902), so a spool whose
  2171. # material is a product line — "PLA+", "HTPLA" — reports
  2172. # back as "PLA" and would otherwise fail this check and
  2173. # be auto-unlinked from the slot it was just assigned to.
  2174. # Reducing the printer's side too keeps slots configured
  2175. # by an older Bambuddy, still reporting "PLA+", matching.
  2176. spool = assignment.spool
  2177. if spool:
  2178. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2179. # Two ways the assign path can have arrived at the
  2180. # slot's type, so both count as "we wrote this".
  2181. # The material column is one; the spool's preset is
  2182. # the other, and it outranks the material when the
  2183. # spool has one -- a spool whose material says PLA
  2184. # and whose preset is "Bambu PLA Aero" puts
  2185. # PLA-AERO in the slot (#2902). Read from the stored
  2186. # preset name rather than resolving the preset,
  2187. # because this runs on every AMS push and a cloud
  2188. # lookup here would be both slow and unavailable on
  2189. # the unauthenticated replay path.
  2190. spool_types = {printer_filament_type(spool.material).upper()}
  2191. if spool.slicer_filament_name:
  2192. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2193. # An imported local preset stores its type outright,
  2194. # which is what the assign path used -- and the name
  2195. # above may be unset. One keyed read, and only on a
  2196. # mismatch, which is rare.
  2197. #
  2198. # slicer_filament is free text up to fifty characters,
  2199. # so the digits have to be checked against the range
  2200. # of the integer primary key they are about to be
  2201. # compared with. Postgres raises on an out-of-range
  2202. # integer rather than simply not matching, and that
  2203. # would poison this session and abandon the rest of
  2204. # the cleanup pass.
  2205. lp_ref = (spool.slicer_filament or "").strip()
  2206. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2207. from backend.app.models.local_preset import LocalPreset as _LP
  2208. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2209. if lp_type:
  2210. spool_types.add(printer_filament_type(lp_type).upper())
  2211. if (
  2212. _colors_similar(cur_color, spool_color)
  2213. and printer_filament_type(cur_type).upper() in spool_types
  2214. ):
  2215. logger.info(
  2216. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2217. assignment.spool_id,
  2218. assignment.ams_id,
  2219. assignment.tray_id,
  2220. )
  2221. assignment.fingerprint_color = cur_color
  2222. assignment.fingerprint_type = cur_type
  2223. continue
  2224. logger.info(
  2225. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2226. assignment.spool_id,
  2227. assignment.ams_id,
  2228. assignment.tray_id,
  2229. cur_color,
  2230. cur_type,
  2231. fp_color,
  2232. fp_type,
  2233. spool.rgba if spool else "?",
  2234. spool.material if spool else "?",
  2235. )
  2236. stale.append(assignment) # Spool changed
  2237. slot_unlink_grace.settle(printer_id, "inventory", held)
  2238. # Snapshot slots before delete — ORM attribute access after the
  2239. # commit would refresh against a deleted row.
  2240. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2241. for a in stale:
  2242. await db.delete(a)
  2243. if stale:
  2244. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2245. # Commit any changes (stale deletions and/or fingerprint updates)
  2246. await db.commit()
  2247. # Tell open browsers the assignment is gone (#2575). Only the manual
  2248. # REST assign/unassign endpoints broadcast this event; without it the
  2249. # frontend's spool-assignments cache keeps rendering the unlinked
  2250. # spool on the slot until an unrelated refetch — which reads exactly
  2251. # like "the fix didn't work" (reporter verified: a browser refresh
  2252. # after the swap showed the correct state all along).
  2253. for ams_id, tray_id in unlinked_slots:
  2254. await ws_manager.broadcast(
  2255. {
  2256. "type": "spool_assignment_changed",
  2257. "printer_id": printer_id,
  2258. "ams_id": ams_id,
  2259. "tray_id": tray_id,
  2260. }
  2261. )
  2262. except Exception as e:
  2263. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2264. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2265. """Delete Spoolman slot rows whose held removal has run its grace period.
  2266. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2267. talks to Spoolman for every tray; this only needs the local rows, so it
  2268. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2269. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2270. not in a slot the presence bit calls occupied -- and nothing else.
  2271. """
  2272. logger = logging.getLogger(__name__)
  2273. try:
  2274. async with async_session() as db:
  2275. from backend.app.api.routes.settings import get_setting
  2276. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2277. from backend.app.services.ams_slot_presence import spool_present
  2278. enabled = await get_setting(db, "spoolman_enabled")
  2279. if not enabled or enabled.lower() != "true":
  2280. return
  2281. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2282. if sync_mode and sync_mode != "auto":
  2283. return
  2284. trays: dict[tuple[int, int], dict] = {}
  2285. for ams_unit in ams_data or []:
  2286. if not isinstance(ams_unit, dict):
  2287. continue
  2288. for tray in ams_unit.get("tray", []):
  2289. if isinstance(tray, dict):
  2290. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2291. rows = (
  2292. (
  2293. await db.execute(
  2294. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2295. )
  2296. )
  2297. .scalars()
  2298. .all()
  2299. )
  2300. held: set[tuple] = set()
  2301. expired: list[tuple[int, int]] = []
  2302. for row in rows:
  2303. tray = trays.get((row.ams_id, row.tray_id))
  2304. if tray is None or printing_now:
  2305. continue
  2306. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2307. continue
  2308. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2309. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2310. continue
  2311. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2312. expired.append((row.ams_id, row.tray_id))
  2313. else:
  2314. held.add(hold_key)
  2315. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2316. if not expired:
  2317. return
  2318. # A statement rather than ORM deletes, like the sync pass: the two
  2319. # can overlap, and a row the other already removed must not fail
  2320. # this commit.
  2321. for ams_id, tray_id in expired:
  2322. await db.execute(
  2323. delete(SpoolmanSlotAssignment).where(
  2324. SpoolmanSlotAssignment.printer_id == printer_id,
  2325. SpoolmanSlotAssignment.ams_id == ams_id,
  2326. SpoolmanSlotAssignment.tray_id == tray_id,
  2327. )
  2328. )
  2329. await db.commit()
  2330. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2331. for ams_id, tray_id in expired:
  2332. await ws_manager.broadcast(
  2333. {
  2334. "type": "spool_assignment_changed",
  2335. "printer_id": printer_id,
  2336. "ams_id": ams_id,
  2337. "tray_id": tray_id,
  2338. }
  2339. )
  2340. except Exception as e:
  2341. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2342. async def _recheck_held_unlinks(printer_id: int) -> None:
  2343. """Re-run just the slot cleanup against the printer's current AMS state.
  2344. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2345. passes otherwise run only when the AMS hash changes, and a slot that went
  2346. empty and stayed empty may never change it again.
  2347. """
  2348. status = printer_manager.get_status(printer_id)
  2349. # A disconnected printer's state is its last report, not a new one: acting
  2350. # on it would "confirm" a removal nobody has seen for the whole grace
  2351. # period. Leave the holds; the first push after reconnecting decides.
  2352. if status is None or not status.connected:
  2353. return
  2354. ams_raw = status.raw_data.get("ams")
  2355. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2356. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2357. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2358. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2359. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2360. async def on_ams_change(printer_id: int, ams_data: list):
  2361. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2362. logger = logging.getLogger(__name__)
  2363. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2364. # on_print_complete may pop _active_sessions during our awaits (#880).
  2365. from backend.app.services.usage_tracker import _active_sessions
  2366. _print_active = printer_id in _active_sessions
  2367. # A slot that reports empty while a print is running is a filament runout,
  2368. # not a spool swap: the spool is still physically in the AMS, just
  2369. # consumed. Dropping either inventory backend's slot link there loses the
  2370. # only record of which spool fed the print, so the completion path can't
  2371. # charge the runout segment to anything. Both cleanup passes below consult
  2372. # this; computed once, up front, so neither depends on the other having run.
  2373. _unlink_state = printer_manager.get_status(printer_id)
  2374. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2375. # MQTT relay - publish AMS change
  2376. try:
  2377. printer_info = printer_manager.get_printer(printer_id)
  2378. if printer_info:
  2379. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2380. except Exception:
  2381. pass # Don't fail AMS callback if MQTT fails
  2382. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2383. # This ensures frontend gets immediate updates when AMS slots are configured
  2384. try:
  2385. state = printer_manager.get_status(printer_id)
  2386. if state:
  2387. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2388. await ws_manager.send_printer_status(
  2389. printer_id,
  2390. printer_state_to_dict(
  2391. state,
  2392. printer_id,
  2393. printer_manager.get_model(printer_id),
  2394. printer_manager.get_drying_targets(printer_id),
  2395. ),
  2396. )
  2397. except Exception as e:
  2398. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2399. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2400. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2401. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2402. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2403. # "no existing assignment" for the same (printer, ams, tray) and race to
  2404. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2405. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2406. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2407. try:
  2408. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2409. from sqlalchemy.orm import selectinload
  2410. from backend.app.api.routes.settings import get_setting
  2411. from backend.app.models.spool import Spool
  2412. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2413. from backend.app.services.spool_tag_matcher import (
  2414. auto_assign_spool,
  2415. create_spool_from_tray,
  2416. find_matching_untagged_spool,
  2417. get_spool_by_tag,
  2418. is_bambu_tag,
  2419. is_valid_tag,
  2420. link_tag_to_inventory_spool,
  2421. )
  2422. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2423. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2424. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2425. if not _spoolman_on or _spoolman_on.lower() != "true":
  2426. for ams_unit in ams_data:
  2427. if not isinstance(ams_unit, dict):
  2428. continue
  2429. ams_id = int(ams_unit.get("id", 0))
  2430. for tray in ams_unit.get("tray", []):
  2431. if not isinstance(tray, dict):
  2432. continue
  2433. tray_id = int(tray.get("id", 0))
  2434. tag_uid = tray.get("tag_uid", "")
  2435. tray_uuid = tray.get("tray_uuid", "")
  2436. tray_info_idx = tray.get("tray_info_idx", "")
  2437. if not tray.get("tray_type"):
  2438. # Slot reported empty — drop any cached unknown-tag
  2439. # broadcast so reinserting the same spool re-prompts.
  2440. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2441. continue # Empty slot
  2442. # Check if assignment already exists for this slot
  2443. existing = await db.execute(
  2444. select(SA)
  2445. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2446. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2447. )
  2448. existing_assignment = existing.scalar_one_or_none()
  2449. if existing_assignment:
  2450. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2451. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2452. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2453. # Skip during active prints: the usage tracker handles deduction
  2454. # precisely via 3MF data on print completion. Without this guard the
  2455. # AMS remain% SET and the usage tracker ADD both fire from the same
  2456. # MQTT message, doubling the deduction (#880).
  2457. if _print_active:
  2458. continue
  2459. remain_raw = tray.get("remain")
  2460. if (
  2461. remain_raw is not None
  2462. and existing_assignment.spool
  2463. and not existing_assignment.spool.weight_locked
  2464. ):
  2465. try:
  2466. remain_val = int(remain_raw)
  2467. except (TypeError, ValueError):
  2468. remain_val = -1
  2469. if 1 <= remain_val <= 100:
  2470. lw = existing_assignment.spool.label_weight or 1000
  2471. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2472. current_used = existing_assignment.spool.weight_used or 0
  2473. if new_used > current_used + 1:
  2474. logger.info(
  2475. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2476. existing_assignment.spool_id,
  2477. current_used,
  2478. new_used,
  2479. remain_val,
  2480. )
  2481. existing_assignment.spool.weight_used = new_used
  2482. await db.commit()
  2483. # Re-apply stored K-profile when the live tray's
  2484. # cali_idx drifted from the spool's stored profile.
  2485. # This catches "reset slot → re-read" and any other
  2486. # path where the firmware loses the user's K-profile
  2487. # selection while the SpoolAssignment row persists.
  2488. # Per the maintainer's rule: any time a spool tag is
  2489. # identified and matches inventory, the slot must be
  2490. # configured with the spool's stored settings. Without
  2491. # this block the existing-assignment branch only ran
  2492. # weight-sync and let the firmware-default cali_idx win.
  2493. try:
  2494. spool = existing_assignment.spool
  2495. if (
  2496. spool is not None
  2497. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2498. and spool.k_profiles
  2499. ):
  2500. state = printer_manager.get_status(printer_id)
  2501. slot_nozzle = resolve_slot_nozzle(
  2502. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2503. )
  2504. nozzle_diameter = slot_nozzle.diameter
  2505. slot_extruder = slot_nozzle.extruder
  2506. # Prefer exact extruder match, fall back to
  2507. # extruder-agnostic kp for the same printer +
  2508. # nozzle. Avoids hard-skipping when the AMS is
  2509. # mapped differently than at calibration time.
  2510. matching_kp = None
  2511. fallback_kp = None
  2512. for kp in spool.k_profiles:
  2513. if (
  2514. kp.printer_id != printer_id
  2515. or kp.nozzle_diameter != nozzle_diameter
  2516. or kp.cali_idx is None
  2517. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2518. ):
  2519. continue
  2520. if (
  2521. slot_extruder is not None
  2522. and kp.extruder is not None
  2523. and kp.extruder == slot_extruder
  2524. ):
  2525. matching_kp = kp
  2526. break
  2527. if fallback_kp is None:
  2528. fallback_kp = kp
  2529. chosen_kp = matching_kp or fallback_kp
  2530. if chosen_kp is not None:
  2531. live_cali_idx = tray.get("cali_idx")
  2532. # Only fire MQTT when the printer's live
  2533. # cali_idx differs from the stored value.
  2534. # Avoids spamming the broker on every
  2535. # MQTT push during steady-state operation.
  2536. if live_cali_idx != chosen_kp.cali_idx:
  2537. client = printer_manager.get_client(printer_id)
  2538. if client:
  2539. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2540. client.extrusion_cali_sel(
  2541. ams_id=ams_id,
  2542. tray_id=tray_id,
  2543. cali_idx=chosen_kp.cali_idx,
  2544. filament_id=cali_filament_id,
  2545. nozzle_diameter=nozzle_diameter,
  2546. )
  2547. logger.info(
  2548. "Re-applied K-profile cali_idx=%d for spool %d "
  2549. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2550. chosen_kp.cali_idx,
  2551. spool.id,
  2552. printer_id,
  2553. ams_id,
  2554. tray_id,
  2555. live_cali_idx,
  2556. )
  2557. except Exception:
  2558. logger.exception(
  2559. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2560. printer_id,
  2561. ams_id,
  2562. tray_id,
  2563. )
  2564. continue
  2565. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2566. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2567. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2568. if not spool:
  2569. # Try matching an untagged inventory spool (same material/color)
  2570. spool = await find_matching_untagged_spool(db, tray)
  2571. if spool:
  2572. await link_tag_to_inventory_spool(db, spool, tray)
  2573. elif _auto_add_unknown:
  2574. spool = await create_spool_from_tray(db, tray)
  2575. else:
  2576. # Auto-add disabled: surface the slot so the
  2577. # user can add it manually via the UI.
  2578. await _broadcast_unknown_tag(
  2579. printer_id=printer_id,
  2580. ams_id=ams_id,
  2581. tray_id=tray_id,
  2582. tag_uid=tag_uid,
  2583. tray_uuid=tray_uuid,
  2584. tray_type=tray.get("tray_type"),
  2585. tray_color=tray.get("tray_color"),
  2586. tray_sub_brands=tray.get("tray_sub_brands"),
  2587. tray_count=len(ams_unit.get("tray", [])),
  2588. )
  2589. continue
  2590. # Slot matched (existing tag, untagged inventory
  2591. # match, or freshly auto-created spool) — drop any
  2592. # stale dedup so a future tag swap re-prompts.
  2593. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2594. await auto_assign_spool(
  2595. printer_id,
  2596. ams_id,
  2597. tray_id,
  2598. spool,
  2599. printer_manager,
  2600. db,
  2601. tray_info_idx=tray_info_idx,
  2602. )
  2603. await db.commit()
  2604. await ws_manager.broadcast(
  2605. {
  2606. "type": "spool_auto_assigned",
  2607. "printer_id": printer_id,
  2608. "ams_id": ams_id,
  2609. "tray_id": tray_id,
  2610. "spool_id": spool.id,
  2611. }
  2612. )
  2613. logger.info(
  2614. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2615. spool.id,
  2616. printer_id,
  2617. ams_id,
  2618. tray_id,
  2619. )
  2620. elif is_valid_tag(tag_uid, tray_uuid):
  2621. # Non-BL spool with some tag — let user choose
  2622. await _broadcast_unknown_tag(
  2623. printer_id=printer_id,
  2624. ams_id=ams_id,
  2625. tray_id=tray_id,
  2626. tag_uid=tag_uid,
  2627. tray_uuid=tray_uuid,
  2628. tray_type=tray.get("tray_type"),
  2629. tray_color=tray.get("tray_color"),
  2630. tray_sub_brands=tray.get("tray_sub_brands"),
  2631. tray_count=len(ams_unit.get("tray", [])),
  2632. )
  2633. # No-tag slots (generic non-RFID filament) are left alone:
  2634. # nothing to identify, prompting "+ Add" would just create
  2635. # ghost spools with empty tags on every confirm.
  2636. except Exception as e:
  2637. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2638. try:
  2639. async with async_session() as db:
  2640. from backend.app.api.routes.settings import get_setting
  2641. from backend.app.models.printer import Printer
  2642. # Check if Spoolman is enabled
  2643. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2644. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2645. return
  2646. # Check sync mode
  2647. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2648. if sync_mode and sync_mode != "auto":
  2649. return # Only sync on auto mode
  2650. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2651. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2652. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2653. # always owned by per-print tracking, never by AMS auto-sync. The
  2654. # setting is still read by the settings UI for backwards compat but
  2655. # has no effect on the sync path here.
  2656. # Get Spoolman URL
  2657. spoolman_url = await get_setting(db, "spoolman_url")
  2658. if not spoolman_url:
  2659. return
  2660. # Get or create Spoolman client
  2661. client = await get_spoolman_client()
  2662. if not client:
  2663. try:
  2664. client = await init_spoolman_client(spoolman_url)
  2665. except ValueError as exc:
  2666. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2667. return
  2668. # Check if Spoolman is reachable
  2669. if not await client.health_check():
  2670. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2671. return
  2672. # Get printer name for location
  2673. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2674. printer = result.scalar_one_or_none()
  2675. printer_name = printer.name if printer else f"Printer {printer_id}"
  2676. # OPTIMIZATION: Fetch all spools once before processing trays
  2677. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2678. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2679. try:
  2680. cached_spools = await client.get_spools()
  2681. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2682. except Exception as e:
  2683. logger.error(
  2684. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2685. printer_id,
  2686. e,
  2687. )
  2688. return
  2689. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2690. from sqlalchemy.orm import selectinload
  2691. from backend.app.models.spool_assignment import SpoolAssignment
  2692. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2693. from backend.app.services.ams_slot_presence import spool_present
  2694. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2695. # Built-in remaining weight, used by sync_ams_tray only when the
  2696. # firmware reports an unusable remain%/tray_weight for a slot.
  2697. #
  2698. # Left empty since #2812. This block runs in Spoolman mode only,
  2699. # and until then the built-in table was emptied on the switch, so
  2700. # there was never anything here to read and the fallback was inert.
  2701. # Preserving those rows makes it live again, and it is keyed by slot
  2702. # rather than by spool: after a mode switch the tray may well hold
  2703. # different filament, and ``create_spool`` writes ``remaining_weight``
  2704. # unconditionally, so a stale figure would be seeded into a brand new
  2705. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2706. # intent survives for whoever revisits the cross-mode fallback.
  2707. inventory_weights: dict[tuple[int, int], float] = {}
  2708. if not await spoolman_owns_assignments(db):
  2709. try:
  2710. assign_result = await db.execute(
  2711. select(SpoolAssignment)
  2712. .options(selectinload(SpoolAssignment.spool))
  2713. .where(SpoolAssignment.printer_id == printer_id)
  2714. )
  2715. for assignment in assign_result.scalars().all():
  2716. spool = assignment.spool
  2717. if spool and spool.label_weight > 0:
  2718. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2719. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2720. except Exception as e:
  2721. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2722. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2723. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2724. try:
  2725. slot_result = await db.execute(
  2726. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2727. )
  2728. for slot in slot_result.scalars().all():
  2729. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2730. except Exception as e:
  2731. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2732. # Sync each AMS tray and collect slot changes for DB persistence
  2733. synced = 0
  2734. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2735. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2736. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2737. for ams_unit in ams_data:
  2738. if not isinstance(ams_unit, dict):
  2739. continue
  2740. ams_id = int(ams_unit.get("id", 0))
  2741. trays = ams_unit.get("tray", [])
  2742. for tray_data in trays:
  2743. if not isinstance(tray_data, dict):
  2744. continue
  2745. tray_id_raw = int(tray_data.get("id", 0))
  2746. tray = client.parse_ams_tray(ams_id, tray_data)
  2747. if not tray:
  2748. # Empty tray slot — record for local assignment cleanup
  2749. # and drop any cached unknown-tag broadcast so a
  2750. # reinserted spool re-prompts.
  2751. #
  2752. # Not during a running print: a slot that empties there
  2753. # is a filament runout, and the spool is still in the
  2754. # AMS. `spoolman_slot_assignments` is how a tag-less
  2755. # spool assigned through the Bambuddy UI is resolved at
  2756. # completion (#1459), so deleting the row mid-print
  2757. # loses the runout segment's usage — the same failure
  2758. # the internal inventory's auto-unlink had.
  2759. #
  2760. # Nor when firmware's presence bit says the slot is
  2761. # occupied. parse_ams_tray calls a tray with no type or
  2762. # no colour empty, and a spool the AMS cannot read has
  2763. # neither until something configures it — so a tag-less
  2764. # spool assigned through the UI had its row deleted by
  2765. # the first idle push after it was inserted. Same
  2766. # deletion as the internal inventory's in #3100, same
  2767. # answer, so the two modes stay in step.
  2768. #
  2769. # And only once the slot has stayed empty for the grace
  2770. # period -- the internal inventory's #3186 answer, for
  2771. # the same one-push blank.
  2772. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2773. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2774. if not printing_now and (
  2775. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2776. ):
  2777. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2778. empty_slots.append((ams_id, tray_id_raw))
  2779. else:
  2780. spoolman_held.add(hold_key)
  2781. logger.info(
  2782. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2783. "unlinking if it is still empty in %ds",
  2784. ams_id,
  2785. tray_id_raw,
  2786. linked_spool,
  2787. int(slot_unlink_grace.GRACE_SECONDS),
  2788. )
  2789. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2790. continue
  2791. spool_tag = (
  2792. tray.tray_uuid
  2793. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2794. else tray.tag_uid
  2795. )
  2796. # Provide the hint only when no RFID is available
  2797. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2798. try:
  2799. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2800. result = await client.sync_ams_tray(
  2801. tray,
  2802. printer_name,
  2803. db,
  2804. # Per-print tracking is the only weight writer (#1119).
  2805. # AMS auto-sync still maintains spool metadata / slot
  2806. # assignments but no longer touches remaining_weight.
  2807. disable_weight_sync=True,
  2808. cached_spools=cached_spools,
  2809. inventory_remaining=inv_remaining,
  2810. spoolman_spool_id_hint=hint,
  2811. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2812. )
  2813. if result is None and spool_tag and not auto_add_unknown_rfid:
  2814. # Spoolman skipped auto-create per user setting — surface
  2815. # the slot so the UI can offer "+ Add to inventory".
  2816. await _broadcast_unknown_tag(
  2817. printer_id=printer_id,
  2818. ams_id=ams_id,
  2819. tray_id=tray.tray_id,
  2820. tag_uid=tray.tag_uid or "",
  2821. tray_uuid=tray.tray_uuid or "",
  2822. tray_type=tray.tray_type,
  2823. tray_color=tray.tray_color,
  2824. tray_sub_brands=tray.tray_sub_brands,
  2825. tray_count=len(trays),
  2826. )
  2827. elif result:
  2828. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2829. if result:
  2830. synced += 1
  2831. if result.get("id"):
  2832. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2833. # If a new spool was created, add it to the cache
  2834. # so subsequent trays can find it if they reference the same tag
  2835. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2836. if not spool_exists:
  2837. cached_spools.append(result)
  2838. logger.debug(
  2839. "[Printer %s] Added newly created spool %s to cache",
  2840. printer_id,
  2841. result["id"],
  2842. )
  2843. # Reconcile slot_preset_mappings (the same row internal
  2844. # mode keeps in sync via inventory + spool_tag_matcher).
  2845. # Without this the slot card surfaces the previous spool's
  2846. # preset name — same bug shape, different inventory mode.
  2847. from backend.app.services.slot_preset_writer import (
  2848. upsert_slot_preset_for_spoolman_spool,
  2849. )
  2850. await upsert_slot_preset_for_spoolman_spool(
  2851. db=db,
  2852. spoolman_spool=result,
  2853. tray_info_idx=tray.tray_info_idx or "",
  2854. tray_sub_brands=tray.tray_sub_brands or "",
  2855. tray_type=tray.tray_type or "",
  2856. printer_id=printer_id,
  2857. ams_id=ams_id,
  2858. tray_id=tray.tray_id,
  2859. )
  2860. except Exception as e:
  2861. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2862. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2863. if synced > 0:
  2864. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2865. # Persist slot assignment changes to the local table
  2866. if slot_changes or empty_slots:
  2867. try:
  2868. for ams_id, tray_id, spool_id in slot_changes:
  2869. await db.execute(
  2870. text(
  2871. "INSERT INTO spoolman_slot_assignments"
  2872. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2873. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2874. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2875. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2876. ),
  2877. {
  2878. "printer_id": printer_id,
  2879. "ams_id": ams_id,
  2880. "tray_id": tray_id,
  2881. "spool_id": spool_id,
  2882. },
  2883. )
  2884. for ams_id, tray_id in empty_slots:
  2885. await db.execute(
  2886. delete(SpoolmanSlotAssignment).where(
  2887. SpoolmanSlotAssignment.printer_id == printer_id,
  2888. SpoolmanSlotAssignment.ams_id == ams_id,
  2889. SpoolmanSlotAssignment.tray_id == tray_id,
  2890. )
  2891. )
  2892. await db.commit()
  2893. except Exception as e:
  2894. await db.rollback()
  2895. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2896. else:
  2897. # Tell open browsers the slot changed. This loop rewrites
  2898. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2899. # above, and the AMS slot card reads that row ahead of the
  2900. # live tray_info_idx -- so with no event the card keeps
  2901. # showing the previous spool's preset name. Internal mode
  2902. # raises spool_auto_assigned for the same reason; this loop
  2903. # broadcast nothing at all, which made Spoolman mode the
  2904. # worse half of the same bug. On the else branch so a
  2905. # failed commit stays silent and a broadcast failure cannot
  2906. # roll back rows that are already committed.
  2907. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2908. await ws_manager.broadcast(
  2909. {
  2910. "type": "spool_assignment_changed",
  2911. "printer_id": printer_id,
  2912. "ams_id": ams_id,
  2913. "tray_id": tray_id,
  2914. }
  2915. )
  2916. except Exception as e:
  2917. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2918. # Largest finish photo attached to a notification; a bigger one is still linked.
  2919. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  2920. async def _finish_photo_for_notification(
  2921. db, archive, archive_id: int, filename: str
  2922. ) -> tuple[str | None, bytes | None]:
  2923. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  2924. With authentication off the link is the archive's own photo route, as it
  2925. always was: it opens without a login and doesn't expire. With
  2926. authentication on that route needs a media token, which nothing tapping a
  2927. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  2928. link only ever answered 401. The photo is then saved as a notification
  2929. photo as well (utils/notification_photos.py) and the link points there: an
  2930. unguessable name that opens this one photo and nothing else, for 3 days.
  2931. The link is relative when no External URL is set. Bytes over
  2932. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  2933. ``(None, None)`` when the photo can't be found.
  2934. """
  2935. from backend.app.api.routes.settings import get_setting
  2936. from backend.app.core.auth import is_auth_enabled
  2937. from backend.app.utils.archive_paths import find_archive_photo
  2938. from backend.app.utils.notification_photos import save_notification_photo
  2939. log = logging.getLogger(__name__)
  2940. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  2941. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  2942. photo_bytes: bytes | None = None
  2943. try:
  2944. photo_path = find_archive_photo(archive, filename)
  2945. if photo_path is not None:
  2946. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2947. except Exception as e:
  2948. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2949. try:
  2950. auth_on = await is_auth_enabled(db)
  2951. except Exception:
  2952. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  2953. if auth_on:
  2954. url = None
  2955. if photo_bytes:
  2956. try:
  2957. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  2958. url = f"{base}/api/v1/notifications/photos/{name}"
  2959. except Exception as e:
  2960. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  2961. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  2962. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  2963. return url, None
  2964. if photo_bytes:
  2965. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2966. return url, photo_bytes
  2967. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  2968. """Capture a camera snapshot for notification image attachment.
  2969. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2970. Uses: external camera > buffered frame > fresh capture.
  2971. Turns the chamber light on for the picture when the printer asks for it
  2972. (#1655). ``light=False`` is for callers that capture all through a print,
  2973. where the light would flash with every frame.
  2974. """
  2975. if not printer:
  2976. return None
  2977. async with camera_light(printer if light else None):
  2978. return await _capture_snapshot_frame(printer_id, printer, logger)
  2979. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  2980. """The capture behind ``_capture_snapshot_for_notification``."""
  2981. try:
  2982. from backend.app.api.routes.settings import get_setting
  2983. async with async_session() as db:
  2984. capture_enabled = await get_setting(db, "capture_finish_photo")
  2985. if capture_enabled is not None and capture_enabled.lower() != "true":
  2986. return None
  2987. # Try external camera first
  2988. if printer.external_camera_enabled and printer.external_camera_url:
  2989. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2990. from backend.app.api.routes.camera import live_frame_for_capture
  2991. from backend.app.services.external_camera import capture_frame
  2992. # An external camera allows one reader, so capturing while a viewer
  2993. # is attached fails (#2707). A None here falls through to the paths
  2994. # below exactly as a failed capture did.
  2995. defer, buffered = live_frame_for_capture(printer_id)
  2996. if defer:
  2997. frame_data = buffered
  2998. else:
  2999. frame_data = await capture_frame(
  3000. printer.external_camera_url,
  3001. printer.external_camera_type or "mjpeg",
  3002. snapshot_url=printer.external_camera_snapshot_url,
  3003. )
  3004. if frame_data and len(frame_data) <= 2_500_000:
  3005. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3006. return _apply_camera_rotation(frame_data, printer, logger)
  3007. # Try buffered frame from active stream
  3008. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3009. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3010. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3011. buffered_frame = get_buffered_frame(printer_id)
  3012. if (active_for_printer or active_chamber) and buffered_frame:
  3013. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3014. if len(buffered_frame) <= 2_500_000:
  3015. return _apply_camera_rotation(buffered_frame, printer, logger)
  3016. # Fresh capture from printer camera
  3017. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3018. from backend.app.services.camera import capture_camera_frame_bytes
  3019. frame_data = await capture_camera_frame_bytes(
  3020. printer.ip_address, printer.access_code, printer.model, timeout=15
  3021. )
  3022. if frame_data and len(frame_data) <= 2_500_000:
  3023. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3024. return _apply_camera_rotation(frame_data, printer, logger)
  3025. except Exception as e:
  3026. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3027. return None
  3028. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3029. """#1867: bank a recent in-print camera frame for the finish photo.
  3030. Called on every layer change and (#2547) on every print-progress advance.
  3031. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3032. path has a pre-End-G-code image for prints that end with a plate swap.
  3033. Both drivers are print telemetry that stops the instant printing ends: no
  3034. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3035. plate swap) executes. So the last banked frame is always the finished print,
  3036. never the swapped plate — that property is what the #1867 path relies on and
  3037. it must survive any change to the throttle below.
  3038. Layer changes alone were not enough: they stop when the *final* layer
  3039. begins, which on a three-minute last layer left the bank stale by the whole
  3040. length of that layer (#2547). Progress keeps ticking through it.
  3041. Best-effort: any failure just leaves the previous banked frame.
  3042. """
  3043. logger = logging.getLogger(__name__)
  3044. client = printer_manager.get_client(printer_id)
  3045. state = client.state if client else None
  3046. if not state or state.state != "RUNNING":
  3047. return
  3048. # Only during actual extrusion — firmware ticks layer_num during the
  3049. # pre-print calibration sequence, whose sub-stages are non-zero.
  3050. if state.mc_print_sub_stage not in (None, 0):
  3051. return
  3052. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3053. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3054. # now that progress advances also drive banking, that exemption would fire a
  3055. # camera grab on every percent tick of the last layer. Bambu printers accept
  3056. # one RTSP client at a time, so each grab contends with the live view.
  3057. now = time.monotonic()
  3058. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3059. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3060. return
  3061. total = state.total_layers or 0
  3062. try:
  3063. async with async_session() as db:
  3064. from backend.app.models.printer import Printer
  3065. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3066. printer = result.scalar_one_or_none()
  3067. if not printer:
  3068. return
  3069. # Reuses the notification snapshot path, which honours the
  3070. # `capture_finish_photo` setting (returns None when disabled) so we
  3071. # don't bank frames the user never asked for. Without the chamber light
  3072. # (#1655): this runs every 25 seconds for the whole print.
  3073. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3074. if frame:
  3075. _inprint_frame_bank[printer_id] = frame
  3076. _inprint_frame_bank_ts[printer_id] = now
  3077. logger.debug(
  3078. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3079. printer_id,
  3080. layer_num,
  3081. total,
  3082. len(frame),
  3083. )
  3084. except Exception as e:
  3085. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3086. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3087. """Apply camera rotation to snapshot image if configured."""
  3088. from backend.app.services.camera import apply_camera_rotation
  3089. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3090. async def _send_print_start_notification(
  3091. printer_id: int,
  3092. data: dict,
  3093. archive_data: dict | None = None,
  3094. logger=None,
  3095. ):
  3096. """Helper to send print start notification with optional archive data."""
  3097. if logger is None:
  3098. logger = logging.getLogger(__name__)
  3099. try:
  3100. async with async_session() as db:
  3101. from backend.app.models.printer import Printer
  3102. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3103. printer = result.scalar_one_or_none()
  3104. printer_name = printer.name if printer else f"Printer {printer_id}"
  3105. # Capture camera snapshot for notification image attachment
  3106. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3107. if image_data:
  3108. if archive_data is None:
  3109. archive_data = {}
  3110. archive_data["image_data"] = image_data
  3111. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3112. # Send user-specific email notification for print start
  3113. if archive_data and archive_data.get("created_by_id"):
  3114. await notification_service.send_user_print_email(
  3115. event_type="user_print_start",
  3116. created_by_id=archive_data["created_by_id"],
  3117. printer_name=printer_name,
  3118. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3119. db=db,
  3120. )
  3121. except Exception as e:
  3122. logger.warning("Notification on_print_start failed: %s", e)
  3123. async def _dispatch_user_print_email(
  3124. status: str,
  3125. created_by_id: int | None,
  3126. printer_name: str,
  3127. filename: str,
  3128. db,
  3129. image_data: bytes | None = None,
  3130. finish_photo_url: str | None = None,
  3131. ) -> None:
  3132. """Send a user-specific print-completion email based on print status.
  3133. Maps the normalised print status to the correct event type and delegates
  3134. to :meth:`NotificationService.send_user_print_email`. A single helper
  3135. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3136. "stopped"`` dispatch block at every call site.
  3137. Does nothing if *created_by_id* is ``None``.
  3138. """
  3139. if created_by_id is None:
  3140. return
  3141. if status == "completed":
  3142. event_type = "user_print_complete"
  3143. elif status == "failed":
  3144. event_type = "user_print_failed"
  3145. elif status in ("stopped", "aborted", "cancelled"):
  3146. event_type = "user_print_stopped"
  3147. else:
  3148. return
  3149. await notification_service.send_user_print_email(
  3150. event_type=event_type,
  3151. created_by_id=created_by_id,
  3152. printer_name=printer_name,
  3153. filename=filename,
  3154. db=db,
  3155. image_data=image_data,
  3156. finish_photo_url=finish_photo_url,
  3157. )
  3158. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3159. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3160. try:
  3161. from backend.app.services.archive import extract_printable_objects_from_archive
  3162. client = printer_manager.get_client(printer_id)
  3163. if not client:
  3164. return
  3165. # Extract with positions for UI overlay, scoped to the plate that
  3166. # is printing — resolve_plate_id is the same resolver /cover uses,
  3167. # so the object list can't disagree with the thumbnail it is drawn
  3168. # over (#2522).
  3169. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3170. app_settings.base_dir / archive.file_path,
  3171. plate_number=resolve_plate_id(client.state),
  3172. )
  3173. if printable_objects:
  3174. client.state.printable_objects = printable_objects
  3175. client.state.printable_objects_bbox_all = bbox_all
  3176. client.state.skipped_objects = []
  3177. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3178. except Exception as e:
  3179. logger.debug("Failed to extract printable objects from archive: %s", e)
  3180. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3181. """Put the skip-objects list back after a restart mid-print.
  3182. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3183. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3184. which the #1304 guard suppresses on the first RUNNING push after startup.
  3185. Everything else this hook restores (the archive, the usage-tracking session,
  3186. the timelapse baseline) was already handled; the object list was not, so a
  3187. restart mid-print took skip-objects away for the rest of that print.
  3188. Nothing recovered it either: the printer card gates its Skip button on the
  3189. object count, and the one endpoint that can rebuild the list is reachable
  3190. only from the modal that button opens.
  3191. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3192. leftover ``status="printing"`` row from a completion we never saw cannot
  3193. hand this print someone else's objects. Without one, nothing is loaded
  3194. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3195. case on demand.
  3196. """
  3197. client = printer_manager.get_client(printer_id)
  3198. if client is None or client.state.printable_objects:
  3199. return
  3200. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3201. if subtask_id in ("", "0"):
  3202. return
  3203. from backend.app.models.archive import PrintArchive
  3204. archive = await db.scalar(
  3205. select(PrintArchive)
  3206. .where(
  3207. PrintArchive.printer_id == printer_id,
  3208. PrintArchive.status == "printing",
  3209. PrintArchive.subtask_id == subtask_id,
  3210. )
  3211. .order_by(PrintArchive.created_at.desc())
  3212. .limit(1)
  3213. )
  3214. if archive is not None:
  3215. _load_objects_from_archive(archive, printer_id, logger)
  3216. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3217. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3218. # past it; the second covers a handshake that failed again on the way back and
  3219. # armed a fresh one. Module-level so tests can shrink them.
  3220. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3221. # Retry ladder for the other temporary give-up: the file service answered and
  3222. # the transfer still did not finish, which at print start is usually the printer
  3223. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3224. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3225. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3226. # two cover a printer that stays busy well into the print.
  3227. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3228. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3229. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3230. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3231. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3232. # by view, so two views race), the cool-off retry task, and print completion.
  3233. # Without this they each read file_path == "" and each run a full copy, so the row
  3234. # ends up pointing at one timestamped directory while the others sit orphaned.
  3235. #
  3236. # Keyed by printer rather than archive because a printer runs one print at a time,
  3237. # which makes the two equally strong here — and it bounds the dict by printer
  3238. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3239. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3240. # resuming, so "no waiters" is not a question this API can answer.
  3241. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3242. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3243. """Fill in a no-3MF archive from a 3MF that turned up later.
  3244. Returns True when the row was upgraded. Safe to call speculatively: it
  3245. verifies the archive still exists, is still a fallback, and that the file
  3246. is a readable 3MF before touching anything.
  3247. Serialised per printer — see ``_fallback_recovery_locks``.
  3248. """
  3249. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3250. async with lock:
  3251. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3252. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3253. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3254. import zipfile
  3255. from backend.app.models.archive import PrintArchive
  3256. from backend.app.services.archive import ArchiveService
  3257. logger = logging.getLogger(__name__)
  3258. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3259. return False
  3260. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3261. # A truncated or half-written download is worse than no download: it
  3262. # would replace an honest empty archive with wrong metadata.
  3263. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3264. return False
  3265. async with async_session() as db:
  3266. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3267. if archive is None or archive.deleted_at is not None:
  3268. return False
  3269. if archive.file_path:
  3270. # Already recovered, or never was a fallback. Either way there is a
  3271. # real 3MF attached and overwriting it is not this function's job.
  3272. return False
  3273. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3274. service = ArchiveService(db)
  3275. recovered = await service.archive_print(
  3276. printer_id=printer_id,
  3277. source_file=source_3mf,
  3278. print_data={**print_data, "status": archive.status or "printing"},
  3279. subtask_id=archive.subtask_id,
  3280. update_archive_id=archive.id,
  3281. )
  3282. if recovered is None:
  3283. return False
  3284. logger.info(
  3285. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3286. archive_id,
  3287. source_3mf,
  3288. recovered.file_size,
  3289. )
  3290. # `archive_updated`, not `archive_created` — the row was already on the
  3291. # Archives page as an empty card and is now filled in, not new.
  3292. await ws_manager.send_archive_updated(
  3293. {
  3294. "id": recovered.id,
  3295. "printer_id": recovered.printer_id,
  3296. "filename": recovered.filename,
  3297. "print_name": recovered.print_name,
  3298. "status": recovered.status,
  3299. }
  3300. )
  3301. return True
  3302. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3303. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3304. Called from the paths that pull a 3MF for a print that is already under way
  3305. — chiefly the cover endpoint, which downloads the very file the archive flow
  3306. could not get and, before #2957, used it for a thumbnail and nothing else.
  3307. The bytes are already local, so this costs a parse and a row update.
  3308. No-op when the running print has a real archive, which is the common case.
  3309. """
  3310. from backend.app.models.archive import PrintArchive
  3311. logger = logging.getLogger(__name__)
  3312. # `_active_prints` is keyed on the raw names seen at print start — the
  3313. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3314. # Callers here arrive with whichever variant their own path produced, so
  3315. # match on the same normalization the download cache uses rather than on an
  3316. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3317. # endpoint find an archive registered under "Desktop_Goose".
  3318. wanted = normalize_3mf_name(name)
  3319. archive_id = None
  3320. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3321. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3322. archive_id = value
  3323. break
  3324. if archive_id is None:
  3325. return False
  3326. async with async_session() as db:
  3327. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3328. # Cheap pre-check so the common case (a normal archive) does no work.
  3329. if archive is None or archive.file_path or archive.deleted_at is not None:
  3330. return False
  3331. try:
  3332. return await _recover_fallback_archive(archive_id, path, printer_id)
  3333. except Exception as e:
  3334. # Recovery is opportunistic. A failure here must never take down the
  3335. # caller, which is usually just trying to render a thumbnail.
  3336. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3337. return False
  3338. def _schedule_fallback_3mf_retry(
  3339. printer_id: int,
  3340. archive_id: int,
  3341. filenames: list[str],
  3342. delays: tuple[float, ...] | None = None,
  3343. reason: str = REASON_FTPS_COOLOFF,
  3344. ) -> None:
  3345. """Re-attempt the 3MF download after a temporary give-up.
  3346. ``reason`` says which give-up this is, and picks the default ladder: an
  3347. FTPS cool-off has to be waited out, while a transfer that timed out under
  3348. contention is worth asking about again straight away (#3063). It is only
  3349. read for the ladder and the log line -- the retry itself is identical, since
  3350. in both cases the file is on the printer and the last attempt at it failed
  3351. for a reason that does not last.
  3352. """
  3353. logger = logging.getLogger(__name__)
  3354. if delays is None:
  3355. delays = (
  3356. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3357. if reason == REASON_FTP_TRANSFER_FAILED
  3358. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3359. )
  3360. async def _retry() -> None:
  3361. from backend.app.models.archive import PrintArchive
  3362. from backend.app.models.printer import Printer
  3363. for delay in delays:
  3364. await asyncio.sleep(delay)
  3365. async with async_session() as db:
  3366. archive = (
  3367. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3368. ).scalar_one_or_none()
  3369. if archive is None or archive.deleted_at is not None or archive.file_path:
  3370. return
  3371. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3372. if printer is None:
  3373. return
  3374. # Read the fields while the session is open rather than touching
  3375. # a detached instance minutes later, mid-download.
  3376. printer_ip = printer.ip_address
  3377. printer_code = printer.access_code
  3378. printer_model = printer.model
  3379. # Someone else may have fetched it in the meantime — the cover
  3380. # endpoint routinely does, and its copy is the same bytes.
  3381. for name in filenames:
  3382. cached = get_cached_3mf(printer_id, name)
  3383. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3384. return
  3385. if ftps_handshake_blocked(printer_ip):
  3386. logger.info(
  3387. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3388. printer_id,
  3389. archive_id,
  3390. )
  3391. continue
  3392. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3393. for candidate in filenames:
  3394. # Bare name only. These come from the print-start flow, which
  3395. # already strips the path, but the local temp write must not
  3396. # depend on that holding for every future caller — a name that
  3397. # is absolute or contains ".." would otherwise escape the data
  3398. # volume via the `/` operator.
  3399. name = Path(candidate).name
  3400. if not name or name in (".", ".."):
  3401. continue
  3402. if not name.endswith(".3mf"):
  3403. name = f"{name}.3mf"
  3404. temp_path = app_settings.archive_dir / "temp" / name
  3405. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3406. try:
  3407. hit = await download_file_try_paths_async(
  3408. printer_ip,
  3409. printer_code,
  3410. ftp_probe_paths(name),
  3411. temp_path,
  3412. socket_timeout=ftp_timeout,
  3413. printer_model=printer_model,
  3414. )
  3415. except Exception as e:
  3416. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3417. continue
  3418. if not hit:
  3419. continue
  3420. cache_3mf_download(printer_id, name, temp_path)
  3421. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3422. return
  3423. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3424. async def _guarded() -> None:
  3425. try:
  3426. await _retry()
  3427. except asyncio.CancelledError:
  3428. raise
  3429. except Exception as e:
  3430. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3431. finally:
  3432. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3433. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3434. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3435. if existing and not existing.done():
  3436. existing.cancel()
  3437. task = asyncio.create_task(_guarded())
  3438. _fallback_3mf_retry_tasks[printer_id] = task
  3439. logger.info(
  3440. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3441. archive_id,
  3442. reason,
  3443. printer_id,
  3444. ", ".join(f"{d:g}s" for d in delays),
  3445. )
  3446. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3447. """Whether an archive created here should ask for the print's outcome (#1898).
  3448. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3449. branches below: a queued job already has its archive and takes the
  3450. expected-print branch, where the queue item's own ``confirm_outcome``
  3451. decides. The queue is still consulted, because a restart mid-print empties
  3452. ``_expected_prints`` — without the check the setting could override a queue
  3453. item that deliberately has the flag off. Any failure answers "don't ask":
  3454. an unwanted prompt is worse than a missing one, and this must never be the
  3455. reason a print goes unarchived.
  3456. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3457. leaves one behind when a completion cannot be matched to it
  3458. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3459. only takes it back once the printer has sat connected and terminal for
  3460. minutes. Until then every screen-started print on that printer would
  3461. silently lose its prompt, so the row is held against ``observed_name`` by
  3462. the same comparison a completion uses: a positive disagreement means the row
  3463. is about some other run and this print is external after all.
  3464. """
  3465. logger = logging.getLogger(__name__)
  3466. try:
  3467. # A savepoint rather than a rollback of the caller's transaction on
  3468. # failure: a failed statement leaves the transaction unusable, but a
  3469. # full rollback also expires every object the caller has loaded (the
  3470. # printer, the archive it just created), and on an async session the
  3471. # next attribute read then raises instead of reloading. Everything here
  3472. # is a read, so undoing the savepoint loses nothing.
  3473. async with db.begin_nested():
  3474. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3475. except Exception as e:
  3476. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3477. return False
  3478. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3479. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3480. from backend.app.api.routes.settings import get_setting, setting_is_true
  3481. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3482. return False
  3483. from backend.app.models.print_queue import PrintQueueItem
  3484. dispatched_here = await db.scalar(
  3485. select(PrintQueueItem)
  3486. .where(
  3487. PrintQueueItem.printer_id == printer_id,
  3488. PrintQueueItem.status == "printing",
  3489. )
  3490. .limit(1)
  3491. )
  3492. if dispatched_here is None:
  3493. return True
  3494. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3495. observed = (observed_name or "").strip()
  3496. if not expected or not observed or _subtask_names_match(expected, observed):
  3497. logger.info(
  3498. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3499. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3500. printer_id,
  3501. dispatched_here.id,
  3502. )
  3503. return False
  3504. logger.info(
  3505. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3506. "%r; treating this as an externally started print.",
  3507. dispatched_here.id,
  3508. printer_id,
  3509. expected,
  3510. observed,
  3511. )
  3512. return True
  3513. async def _dispatch_outcome_confirmation_safely(
  3514. db,
  3515. printer_id: int,
  3516. printer_name: str,
  3517. data: dict,
  3518. archive_id: int,
  3519. archive_data: dict | None = None,
  3520. ) -> None:
  3521. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3522. The completion task sends the per-user print email on the same session
  3523. right after the prompt. A failed statement in the prompt leaves that
  3524. session needing a rollback, and without one the email step fails with
  3525. PendingRollbackError; the prompt is the optional part, so it must not be
  3526. the reason the email never goes out.
  3527. """
  3528. try:
  3529. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3530. except Exception as e:
  3531. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3532. try:
  3533. await db.rollback()
  3534. except Exception:
  3535. pass
  3536. async def dispatch_outcome_confirmation(
  3537. db,
  3538. printer_id: int,
  3539. printer_name: str,
  3540. data: dict,
  3541. archive_id: int,
  3542. archive_data: dict | None = None,
  3543. ) -> bool:
  3544. """Emit the post-print outcome prompt for a completed archive (#1898).
  3545. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3546. queue item, or from ``confirm_outcome_external_prints`` for a print
  3547. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3548. question still open. Mints the per-archive capability token the one-tap
  3549. verdict links carry.
  3550. Lives here rather than inline in ``on_print_complete``'s notification task
  3551. because that task swallows every exception: extracted, the gate and the two
  3552. emissions can be driven by a test, which is the only thing standing between
  3553. a regression here and a farm that quietly stops asking.
  3554. Returns whether a prompt was sent.
  3555. """
  3556. logger = logging.getLogger(__name__)
  3557. from backend.app.models.archive import PrintArchive
  3558. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3559. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3560. return False
  3561. import secrets as _secrets
  3562. # A spent token stays on the row so the one-tap route can recognise it, so
  3563. # "has a token" no longer means "answerable". A prompt going out now needs a
  3564. # live one: mint a new token whenever the stored one is already spent, or
  3565. # every button in the new message would land on the already-answered page.
  3566. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3567. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3568. confirm_archive.confirm_token_used_at = None
  3569. await db.commit()
  3570. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3571. base = await get_external_base_url(db)
  3572. if not await get_setting(db, "external_url"):
  3573. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3574. # absolute URL, so an unconfigured install used to get a message body
  3575. # with two unusable relative paths and no buttons at all. The shared
  3576. # fallback at least produces tappable links; say which setting makes
  3577. # them resolve from a phone.
  3578. logger.warning(
  3579. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3580. "Set Settings → External URL so they resolve away from this host.",
  3581. base,
  3582. )
  3583. token = confirm_archive.confirm_token
  3584. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3585. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3586. confirm_url = f"{base}/archives?confirm={archive_id}"
  3587. await ws_manager.send_print_confirm_request(
  3588. printer_id,
  3589. {
  3590. "archive_id": archive_id,
  3591. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3592. },
  3593. )
  3594. await notification_service.on_print_confirm_request(
  3595. printer_id,
  3596. printer_name,
  3597. data,
  3598. db,
  3599. archive_data=archive_data,
  3600. good_url=good_url,
  3601. reject_url=reject_url,
  3602. confirm_url=confirm_url,
  3603. archive_id=archive_id,
  3604. )
  3605. return True
  3606. async def on_print_start(printer_id: int, data: dict):
  3607. """Handle print start - archive the 3MF file immediately."""
  3608. logger = logging.getLogger(__name__)
  3609. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3610. # Clear any stale user-stopped flag from previous print cycles
  3611. _user_stopped_printers.discard(printer_id)
  3612. # A new print starts its milestones from zero (#3211). The status path only
  3613. # resets on progress below 5 while not printing, which a printer that goes
  3614. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3615. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3616. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3617. _last_progress_milestone[printer_id] = 0
  3618. _kill_switch_notification_tasks.pop(printer_id, None)
  3619. # #1721: drop any leftover pre-captured finish frame from a prior print
  3620. # so a never-consumed cache entry can't bleed into the new print's photo.
  3621. _stage22_finish_frames.pop(printer_id, None)
  3622. # #1867: same for the in-print frame bank — a queued print must not reuse
  3623. # the previous job's banked frame.
  3624. _inprint_frame_bank.pop(printer_id, None)
  3625. _inprint_frame_bank_ts.pop(printer_id, None)
  3626. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3627. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3628. # print's flag instead of inheriting it.
  3629. print_dispatch_context.adopt(printer_id)
  3630. # Cancel any active bed cooldown waiter for this printer
  3631. if _bed_cool_waiters.pop(printer_id, None):
  3632. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3633. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3634. from backend.app.api.routes.printers import clear_cover_cache
  3635. clear_cover_cache(printer_id)
  3636. await ws_manager.send_print_start(printer_id, data)
  3637. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3638. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3639. # MQTT relay - publish print start
  3640. try:
  3641. printer_info = printer_manager.get_printer(printer_id)
  3642. if printer_info:
  3643. await mqtt_relay.on_print_start(
  3644. printer_id,
  3645. printer_info.name,
  3646. printer_info.serial_number,
  3647. data.get("filename", ""),
  3648. data.get("subtask_name", ""),
  3649. )
  3650. except Exception:
  3651. pass # Don't fail print start callback if MQTT fails
  3652. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3653. # and mapping, and the seeded tray-change log.
  3654. #
  3655. # Unconditional, for both inventory backends. This only *captures* — the
  3656. # writing is still split, with the internal tracker skipped at completion
  3657. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3658. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3659. # tray-change log, and that log is the only record of which spool fed
  3660. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3661. # it on one side only would leave Spoolman users with the mid-print
  3662. # restart bug this fixes for everyone else.
  3663. try:
  3664. async with async_session() as db:
  3665. from backend.app.api.routes.settings import get_setting
  3666. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3667. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3668. await usage_on_print_start(
  3669. printer_id,
  3670. data,
  3671. printer_manager,
  3672. db=db,
  3673. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3674. )
  3675. except Exception as e:
  3676. logger.warning("Usage tracker on_print_start failed: %s", e)
  3677. # Track if notification was sent (to avoid sending twice)
  3678. notification_sent = False
  3679. # Smart plug automation: turn on plug when print starts
  3680. try:
  3681. async with async_session() as db:
  3682. await smart_plug_manager.on_print_start(printer_id, db)
  3683. except Exception as e:
  3684. logger.warning("Smart plug on_print_start failed: %s", e)
  3685. async with async_session() as db:
  3686. from backend.app.models.printer import Printer
  3687. from backend.app.services.bambu_ftp import list_files_async
  3688. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3689. printer = result.scalar_one_or_none()
  3690. # Plate detection check - pause if objects detected on build plate
  3691. logger.info(
  3692. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3693. )
  3694. if printer and printer.plate_detection_enabled:
  3695. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3696. # Release the pooled DB connection before the plate-detection camera
  3697. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3698. # printer SELECT has run so far — nothing to persist — so this commit
  3699. # is a data-noop that ends the read transaction and returns the
  3700. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3701. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3702. # archive lookups below re-acquire a fresh connection on next execute.
  3703. await db.commit()
  3704. try:
  3705. from backend.app.services.plate_detection import check_plate_empty
  3706. # Build ROI tuple from printer settings if available
  3707. roi = None
  3708. if all(
  3709. [
  3710. printer.plate_detection_roi_x is not None,
  3711. printer.plate_detection_roi_y is not None,
  3712. printer.plate_detection_roi_w is not None,
  3713. printer.plate_detection_roi_h is not None,
  3714. ]
  3715. ):
  3716. roi = (
  3717. printer.plate_detection_roi_x,
  3718. printer.plate_detection_roi_y,
  3719. printer.plate_detection_roi_w,
  3720. printer.plate_detection_roi_h,
  3721. )
  3722. # Auto-turn on chamber light if it's off for better detection
  3723. light_was_off = False
  3724. client = printer_manager.get_client(printer_id)
  3725. if client and client.state:
  3726. light_was_off = not client.state.chamber_light
  3727. if light_was_off:
  3728. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3729. client.set_chamber_light(True)
  3730. # Wait for light to physically turn on and camera to adjust exposure
  3731. await asyncio.sleep(2.5)
  3732. plate_photo_data = None
  3733. objects_detected = False
  3734. try:
  3735. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3736. plate_result = await check_plate_empty(
  3737. printer_id=printer_id,
  3738. ip_address=printer.ip_address,
  3739. access_code=printer.access_code,
  3740. model=printer.model,
  3741. include_debug_image=False,
  3742. external_camera_url=printer.external_camera_url,
  3743. external_camera_type=printer.external_camera_type,
  3744. use_external=printer.external_camera_enabled,
  3745. roi=roi,
  3746. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3747. )
  3748. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3749. if objects_detected:
  3750. # Objects detected - pause the print!
  3751. logger.warning(
  3752. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3753. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3754. )
  3755. pause_client = printer_manager.get_client(printer_id)
  3756. if pause_client:
  3757. pause_client.pause_print()
  3758. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3759. # Snapshot while the light's still on — restoring it first
  3760. # would leave the notification with a dark photo.
  3761. try:
  3762. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3763. except Exception as snap_err:
  3764. logger.warning(
  3765. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3766. )
  3767. finally:
  3768. # Restore chamber light to original state as soon as the
  3769. # camera is done with it, whatever happened above.
  3770. if light_was_off and client:
  3771. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3772. try:
  3773. client.set_chamber_light(False)
  3774. except Exception as light_err:
  3775. logger.warning(
  3776. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3777. printer_id,
  3778. light_err,
  3779. )
  3780. if objects_detected:
  3781. # Send notification about plate not empty
  3782. await ws_manager.broadcast(
  3783. {
  3784. "type": "plate_not_empty",
  3785. "printer_id": printer_id,
  3786. "printer_name": printer.name,
  3787. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3788. }
  3789. )
  3790. # Also send push notification
  3791. try:
  3792. await notification_service.on_plate_not_empty(
  3793. printer_id=printer_id,
  3794. printer_name=printer.name,
  3795. db=db,
  3796. difference_percent=plate_result.difference_percent,
  3797. image_data=plate_photo_data,
  3798. )
  3799. except Exception as notif_err:
  3800. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3801. else:
  3802. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3803. except Exception as plate_err:
  3804. # Don't block print on plate detection errors
  3805. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3806. if not printer:
  3807. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3808. if not notification_sent:
  3809. await _send_print_start_notification(printer_id, data, logger=logger)
  3810. return
  3811. if not printer.auto_archive:
  3812. # auto-archive disabled — check if there's an expected print (dispatched
  3813. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3814. # If so, fall through to the expected-print handling below so the archive
  3815. # is tracked in _active_prints and usage tracking works at completion.
  3816. _fn = data.get("filename", "")
  3817. _sn = data.get("subtask_name", "")
  3818. _check_keys: list[tuple[int, str]] = []
  3819. if _sn:
  3820. _check_keys += [
  3821. (printer_id, _sn),
  3822. (printer_id, f"{_sn}.3mf"),
  3823. (printer_id, f"{_sn}.gcode.3mf"),
  3824. ]
  3825. if _fn:
  3826. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3827. _check_keys.append((printer_id, _base_fn))
  3828. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3829. _check_keys += [
  3830. (printer_id, _no_archive_base),
  3831. (printer_id, f"{_no_archive_base}.3mf"),
  3832. ]
  3833. _has_expected = any(k in _expected_prints for k in _check_keys)
  3834. if not _has_expected:
  3835. # No expected print — truly external print (started from slicer/touchscreen)
  3836. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3837. if not notification_sent:
  3838. _no_archive_creator: int | None = None
  3839. for _key in _check_keys:
  3840. _expected_prints.pop(_key, None)
  3841. _expected_print_registered_at.pop(_key, None)
  3842. popped_creator = _expected_print_creators.pop(_key, None)
  3843. if _no_archive_creator is None:
  3844. _no_archive_creator = popped_creator
  3845. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3846. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3847. return
  3848. else:
  3849. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3850. # Get the filename and subtask_name
  3851. filename = data.get("filename", "")
  3852. subtask_name = data.get("subtask_name", "")
  3853. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3854. # present, it lets us match an archive across a backend restart (#972):
  3855. # same id → same print → resume the existing row instead of cancelling
  3856. # it and recreating from scratch (which loses started_at). Treat "0"
  3857. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3858. raw_mqtt = data.get("raw_data") or {}
  3859. subtask_id = raw_mqtt.get("subtask_id")
  3860. if subtask_id is not None:
  3861. subtask_id = str(subtask_id).strip()
  3862. if subtask_id in ("", "0"):
  3863. subtask_id = None
  3864. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3865. # Skip the printer's own jobs — a calibration run is not a user's print.
  3866. # See is_internal_printer_job for what counts and why both fields are
  3867. # tested; the pressure-advance line reports as a subtask name with no
  3868. # /usr/ path, which the old prefix-only test here missed entirely.
  3869. #
  3870. # No notification either. The event describes the printer calibrating
  3871. # itself, so "Print started" is as wrong as the archive was, and the
  3872. # matching completion is suppressed in on_print_complete for the same
  3873. # reason.
  3874. if is_internal_printer_job(filename, subtask_name):
  3875. logger.info(
  3876. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3877. filename,
  3878. subtask_name,
  3879. )
  3880. return
  3881. if not filename and not subtask_name:
  3882. # Send notification without archive data (no filename)
  3883. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3884. if not notification_sent:
  3885. await _send_print_start_notification(printer_id, data, logger=logger)
  3886. return
  3887. # Check if this is an expected print from reprint/scheduled
  3888. # Build list of possible keys to check
  3889. expected_keys = []
  3890. if subtask_name:
  3891. expected_keys.append((printer_id, subtask_name))
  3892. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3893. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3894. if filename:
  3895. fname = filename.split("/")[-1] if "/" in filename else filename
  3896. expected_keys.append((printer_id, fname))
  3897. # Strip extensions to match
  3898. base = fname.replace(".gcode", "").replace(".3mf", "")
  3899. expected_keys.append((printer_id, base))
  3900. expected_keys.append((printer_id, f"{base}.3mf"))
  3901. expected_archive_id = None
  3902. for key in expected_keys:
  3903. expected_archive_id = _expected_prints.pop(key, None)
  3904. _expected_print_registered_at.pop(key, None)
  3905. if expected_archive_id:
  3906. # Clean up other possible keys for this print
  3907. for other_key in expected_keys:
  3908. _expected_prints.pop(other_key, None)
  3909. _expected_print_registered_at.pop(other_key, None)
  3910. break
  3911. if expected_archive_id:
  3912. # This is a reprint/scheduled print - use existing archive, don't create new one
  3913. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3914. from backend.app.models.archive import PrintArchive
  3915. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3916. archive = result.scalar_one_or_none()
  3917. if archive:
  3918. # Update archive status to printing
  3919. archive.status = "printing"
  3920. archive.started_at = datetime.now(timezone.utc)
  3921. # The previous run's answer is still on this row and the
  3922. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3923. # so without a reset the second run inherits the first run's
  3924. # verdict: no prompt at all, and a green "good" badge on a run
  3925. # nobody ever judged.
  3926. if archive.confirm_requested:
  3927. archive.user_verdict = None
  3928. archive.user_verdict_source = None
  3929. archive.user_verdict_at = None
  3930. archive.confirm_token = None
  3931. archive.confirm_token_used_at = None
  3932. # Reprint of an archive reuses the source row. Without resetting
  3933. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3934. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3935. # extracts the *original* print's last frame, which then ships in
  3936. # the completion notification (#1707). Clear the path so the
  3937. # scanner runs fresh; also unlink the old video file so reprints
  3938. # don't accumulate orphans in the archive directory. Photos list
  3939. # is left alone — accumulating one finish photo per run is fine.
  3940. # The print-start baseline (#2704) is stale for the same reason:
  3941. # it describes the printer before the previous run. The capture
  3942. # below overwrites it, but clear it here too so an early failure
  3943. # can't leave the scan diffing against the wrong snapshot.
  3944. archive.timelapse_baseline = None
  3945. stale_timelapse_relpath = archive.timelapse_path
  3946. if stale_timelapse_relpath:
  3947. archive.timelapse_path = None
  3948. try:
  3949. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3950. if stale_path.is_file():
  3951. stale_path.unlink()
  3952. logger.info(
  3953. "Deleted stale timelapse %s on reprint of archive %s",
  3954. stale_timelapse_relpath,
  3955. expected_archive_id,
  3956. )
  3957. except OSError as e:
  3958. logger.warning(
  3959. "Failed to delete stale timelapse %s on reprint: %s",
  3960. stale_timelapse_relpath,
  3961. e,
  3962. )
  3963. # Persist a restart-stable id so a later restart resumes this
  3964. # archive by subtask_id instead of name-matching + duplicating
  3965. # it (#1485). The printer often hasn't echoed subtask_id back
  3966. # this soon after dispatch, so fall back to the id Bambuddy
  3967. # minted when it sent the print command. Scoped to this
  3968. # expected-print branch on purpose: an expected match means
  3969. # Bambuddy dispatched this exact print in this process, so the
  3970. # client's last-dispatch id genuinely belongs to it — using it
  3971. # for an externally-started print could mis-tag the archive.
  3972. effective_subtask_id = subtask_id
  3973. if not effective_subtask_id:
  3974. _client = printer_manager.get_client(printer_id)
  3975. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3976. if _dispatched:
  3977. effective_subtask_id = str(_dispatched).strip() or None
  3978. # Update on first-set OR on reprint (the queue dispatcher mints
  3979. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3980. # the rewrite for reprints leaves the archive holding the FIRST
  3981. # run's id; if MQTT then reconnects mid-print, the reconciler
  3982. # (#1542) compares the stale stored id against the printer's
  3983. # live id, sees a mismatch, and synthesises a bogus PRINT
  3984. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3985. # in #1807. Inequality check preserves the noop-on-stable-push
  3986. # behaviour the earlier `not archive.subtask_id` guard provided.
  3987. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3988. archive.subtask_id = effective_subtask_id
  3989. # #1403 follow-up: VP-queue archives are created with
  3990. # printer_id=None at queue-add time (we don't know which
  3991. # printer will run the job yet). When the print actually
  3992. # starts on a specific printer the expected-archive lookup
  3993. # used to skip this assignment, leaving printer_id=None
  3994. # forever — which then disables the "Scan for timelapse"
  3995. # button in ArchivesPage (gated on !archive.printer_id).
  3996. if archive.printer_id != printer_id:
  3997. archive.printer_id = printer_id
  3998. await db.commit()
  3999. # Track as active print
  4000. _active_prints[(printer_id, archive.filename)] = archive.id
  4001. if subtask_name:
  4002. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4003. # Start timelapse session if external camera is enabled (#1353).
  4004. # Queue / VP-dispatched prints land here in the expected-archive
  4005. # branch and used to skip start_session entirely — frames were
  4006. # never captured and the post-print stitch silently returned None.
  4007. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4008. # Inject ams_mapping into usage tracker session — the session was created
  4009. # before expected-print promotion, so it may have ams_mapping=None when
  4010. # the MQTT request topic subscription failed (common on P1S/A1).
  4011. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4012. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4013. if _stored_map or _stored_plate_id is not None:
  4014. try:
  4015. from backend.app.services.usage_tracker import _active_sessions
  4016. _ut_session = _active_sessions.get(printer_id)
  4017. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4018. _ut_session.ams_mapping = _stored_map
  4019. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4020. # plate_id injection covers direct-Print of plate N of a multi-plate
  4021. # 3MF — queue prints already capture it via the on_print_start queue
  4022. # lookup, but direct-Print never goes through the queue (#1697).
  4023. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4024. _ut_session.plate_id = _stored_plate_id
  4025. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4026. except Exception:
  4027. pass
  4028. # Set up energy tracking (#941: persist start on archive row)
  4029. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4030. await ws_manager.send_archive_updated(
  4031. {
  4032. "id": archive.id,
  4033. "status": "printing",
  4034. }
  4035. )
  4036. # Send notification with archive data (reprint/scheduled)
  4037. if not notification_sent:
  4038. # Use archive's created_by_id; fall back to the creator registered via
  4039. # register_expected_print (handles library-file-based queue items where
  4040. # the freshly-created archive has no created_by_id yet).
  4041. # Pop ALL matching keys so no stale entries remain in the dict.
  4042. fallback_creator = None
  4043. for key in expected_keys:
  4044. popped = _expected_print_creators.pop(key, None)
  4045. if fallback_creator is None:
  4046. fallback_creator = popped
  4047. archive_data = {
  4048. "print_time_seconds": archive.print_time_seconds,
  4049. "created_by_id": archive.created_by_id or fallback_creator,
  4050. }
  4051. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4052. # Extract printable objects from the archived 3MF file
  4053. _load_objects_from_archive(archive, printer_id, logger)
  4054. # Store Spoolman tracking data for per-filament usage reporting
  4055. try:
  4056. await _store_spoolman_print_data(
  4057. printer_id,
  4058. archive.id,
  4059. archive.file_path,
  4060. db,
  4061. printer_manager,
  4062. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4063. plate_id=_get_start_plate_id(archive.id),
  4064. )
  4065. except Exception as e:
  4066. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4067. # Price the print from its spools now rather than only at completion (#3261)
  4068. _schedule_archive_cost_estimate(
  4069. printer_id,
  4070. archive.id,
  4071. printer_manager,
  4072. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4073. plate_id=_get_start_plate_id(archive.id),
  4074. session_factory=async_session,
  4075. )
  4076. # Capture timelapse file baseline for snapshot-diff on completion
  4077. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4078. # hit this branch — without the baseline the completion-time scan
  4079. # falls into its "take baseline now" fallback, which snapshots
  4080. # AFTER the new MP4 already exists and never matches a diff
  4081. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4082. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4083. return # Skip creating a new archive
  4084. # Check if there's already a "printing" archive for this printer/file
  4085. # This prevents duplicates when backend restarts during an active print
  4086. from backend.app.models.archive import PrintArchive
  4087. existing_archive: PrintArchive | None = None
  4088. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4089. # across a backend restart for the same print, so this is the most
  4090. # reliable way to reattach. We also accept a previously stale-cancelled
  4091. # archive here so users upgrading mid-print get revived when the row
  4092. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4093. if subtask_id:
  4094. by_id = await db.execute(
  4095. select(PrintArchive)
  4096. .where(PrintArchive.printer_id == printer_id)
  4097. .where(PrintArchive.subtask_id == subtask_id)
  4098. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4099. .order_by(PrintArchive.created_at.desc())
  4100. .limit(1)
  4101. )
  4102. candidate = by_id.scalar_one_or_none()
  4103. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4104. existing_archive = candidate
  4105. # Fallback match: name-based lookup. Kept as-is for prints whose
  4106. # subtask_id is missing ("0" / local / non-cloud prints).
  4107. if existing_archive is None:
  4108. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4109. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4110. # A print started from the printer's screen names its file in full,
  4111. # so the forms above double its extension. The file itself is the
  4112. # one exact match, and nothing looser is added (#3009).
  4113. if _subtask_is_the_file(subtask_name, filename):
  4114. archive_filenames.append(subtask_name)
  4115. existing = await db.execute(
  4116. select(PrintArchive)
  4117. .where(PrintArchive.printer_id == printer_id)
  4118. .where(PrintArchive.status == "printing")
  4119. .where(
  4120. or_(
  4121. PrintArchive.print_name == check_name,
  4122. PrintArchive.filename.in_(archive_filenames),
  4123. )
  4124. )
  4125. .order_by(PrintArchive.created_at.desc())
  4126. .limit(1)
  4127. )
  4128. existing_archive = existing.scalar_one_or_none()
  4129. if existing_archive:
  4130. # subtask_id match → always resume, regardless of age. Same print,
  4131. # just a backend restart. Revive if it was previously stale-cancelled.
  4132. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4133. if subtask_match:
  4134. if existing_archive.status == "cancelled":
  4135. logger.warning(
  4136. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4137. existing_archive.id,
  4138. subtask_id,
  4139. )
  4140. existing_archive.status = "printing"
  4141. existing_archive.failure_reason = None
  4142. await db.commit()
  4143. else:
  4144. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4145. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4146. if existing_archive.energy_start_kwh is None:
  4147. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4148. if not notification_sent:
  4149. archive_data = {
  4150. "print_time_seconds": existing_archive.print_time_seconds,
  4151. "created_by_id": existing_archive.created_by_id,
  4152. }
  4153. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4154. _load_objects_from_archive(existing_archive, printer_id, logger)
  4155. return
  4156. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4157. # stale from the printer's *current* progress, not wall-clock age.
  4158. # A genuinely long print used to trip a blind 4h cutoff and have its
  4159. # live archive cancelled + duplicated on every backend restart
  4160. # (#1485). If the printer reports real progress, this name-matched
  4161. # 'printing' archive IS that ongoing print — resume it whatever its
  4162. # age. Only treat it as a stale leftover when the printer clearly
  4163. # shows a different, freshly-started print: near-0% progress on an
  4164. # archive far too old to still be at 0%. Unknown progress (printer
  4165. # not connected) never cancels — resuming is the safe default.
  4166. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4167. live_status = printer_manager.get_status(printer_id)
  4168. live_progress = getattr(live_status, "progress", None) if live_status else None
  4169. looks_stale = (
  4170. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4171. )
  4172. if looks_stale:
  4173. logger.warning(
  4174. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4175. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4176. )
  4177. existing_archive.status = "cancelled"
  4178. # Canonical key, not a sentence (issue #2974). "No status update
  4179. # received" is what both stale paths actually observed; which of
  4180. # the two it was is already carried by ``status`` -- cancelled
  4181. # here, the reconciled outcome at the reconnect site -- so one
  4182. # key loses no information and gives the Statistics breakdown a
  4183. # single bucket instead of two untranslatable prose strings.
  4184. existing_archive.failure_reason = "noStatusUpdate"
  4185. await db.commit()
  4186. # Fall through to create new archive (don't return)
  4187. else:
  4188. logger.info(
  4189. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4190. )
  4191. # Track this as the active print
  4192. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4193. # Attach subtask_id retroactively so future restarts can resume.
  4194. # Compare for inequality (not "is empty") to also pick up reprint
  4195. # dispatches that mint a fresh id — see #1807 for the bogus
  4196. # "Print Stopped" the strict-empty guard caused on reconnect.
  4197. if subtask_id and existing_archive.subtask_id != subtask_id:
  4198. existing_archive.subtask_id = subtask_id
  4199. await db.commit()
  4200. # Also set up energy tracking if not already tracked (#941: persisted column)
  4201. if existing_archive.energy_start_kwh is None:
  4202. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4203. # Send notification with archive data (existing archive)
  4204. if not notification_sent:
  4205. archive_data = {
  4206. "print_time_seconds": existing_archive.print_time_seconds,
  4207. "created_by_id": existing_archive.created_by_id,
  4208. }
  4209. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4210. # Extract printable objects from the archived 3MF file
  4211. _load_objects_from_archive(existing_archive, printer_id, logger)
  4212. return
  4213. # Build list of possible 3MF filenames to try
  4214. possible_names = []
  4215. # Bambu printers typically store files as "Name.gcode.3mf"
  4216. # The subtask_name is usually the best source for the filename
  4217. if subtask_name:
  4218. if _subtask_is_the_file(subtask_name, filename):
  4219. # A print started from the printer's own screen reports the
  4220. # file's full name, extension included. That is the file, so
  4221. # no extension is appended to it (#3009).
  4222. possible_names.append(subtask_name)
  4223. else:
  4224. # Try common Bambu naming patterns
  4225. possible_names.append(f"{subtask_name}.gcode.3mf")
  4226. possible_names.append(f"{subtask_name}.3mf")
  4227. # Try original filename with .3mf extension
  4228. if filename:
  4229. # Extract just the filename part, not the full path
  4230. fname = filename.split("/")[-1] if "/" in filename else filename
  4231. if fname.endswith(".3mf"):
  4232. possible_names.append(fname)
  4233. elif fname.endswith(".gcode"):
  4234. base = fname.rsplit(".", 1)[0]
  4235. possible_names.append(f"{base}.gcode.3mf")
  4236. possible_names.append(f"{base}.3mf")
  4237. else:
  4238. possible_names.append(f"{fname}.gcode.3mf")
  4239. possible_names.append(f"{fname}.3mf")
  4240. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4241. space_variants = []
  4242. for name in possible_names:
  4243. if " " in name:
  4244. space_variants.append(name.replace(" ", "_"))
  4245. possible_names.extend(space_variants)
  4246. # Remove duplicates while preserving order
  4247. seen = set()
  4248. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4249. logger.info("Trying filenames: %s", possible_names)
  4250. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4251. # here means none of the expected-/existing-archive write branches ran
  4252. # (they all return earlier) — only SELECTs have executed on this path, so
  4253. # this commit persists nothing; it ends the read transaction so the
  4254. # connection returns to the pool during the download. That download tries
  4255. # up to five remote paths per candidate filename with retry/backoff and
  4256. # can run for minutes under FTP contention; holding the session across it
  4257. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4258. # work runs during the download — the new-archive writes below re-acquire
  4259. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4260. await db.commit()
  4261. # Try to find and download the 3MF file
  4262. temp_path = None
  4263. downloaded_filename = None
  4264. # Cache check: cover endpoint may have already pulled this 3MF during
  4265. # the print (frontend opens the card and shows the thumbnail) — reuse
  4266. # that file instead of re-downloading 36MB over the same FTP link that
  4267. # just served it (#972). The cache keys on a normalized filename so
  4268. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4269. for try_filename in possible_names:
  4270. if not try_filename.endswith(".3mf"):
  4271. continue
  4272. cached = get_cached_3mf(printer_id, try_filename)
  4273. if cached:
  4274. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4275. temp_path = cached
  4276. downloaded_filename = try_filename
  4277. break
  4278. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4279. # H2-series and P2S the answer is routinely no — the file stays on
  4280. # internal eMMC and port 990 only ever serves external storage — and
  4281. # then the whole sweep below (six filenames x five directories x four
  4282. # retries, then the directory walk) is ~110 connections that cannot
  4283. # succeed. Skip it and say why (#2780).
  4284. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4285. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4286. # running rather than because the file is somewhere unreachable. The
  4287. # distinction is the whole of #2957: one is permanent, the other clears
  4288. # in minutes with the file still sitting on the printer.
  4289. blocked_by_ftps_cooloff = False
  4290. # Set when a probe reached the printer and still came back without the
  4291. # file -- a timeout mid-transfer, a refused connection, anything that is
  4292. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4293. # caught by name below, so a file that genuinely is not on the card
  4294. # leaves this False and schedules nothing. Anything else means the
  4295. # transfer, not the file, is what failed, and that does not last (#3063).
  4296. ftp_transfer_failed = False
  4297. # The print's name, for a fallback archive whose `subtask_name` the
  4298. # plate guard below had to disown. Display only, and deliberately kept
  4299. # apart from `subtask_name`: that variable is what every file lookup
  4300. # here is built from, and once a name has been shown to fetch another
  4301. # plate's 3MF it must not key `_active_prints` either, or the cover
  4302. # endpoint hands the same contradicted file to
  4303. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4304. display_name_after_plate_reject: str | None = None
  4305. # Get FTP retry settings
  4306. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4307. # ...but "the printer put it on eMMC" is where it went, not whether we
  4308. # can read it. An H2D with a card in mirrors the job to /cache and
  4309. # serves it happily, and skipping on the URL alone cost that reporter
  4310. # every archive for two days (#2856). So ask the printer instead of
  4311. # guessing: the dispatch named the exact file, which is one connection
  4312. # walking five paths rather than the sweep's ~110. Only when the probe
  4313. # comes back empty does the verdict's reason stand.
  4314. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4315. if ftps_handshake_blocked(printer.ip_address):
  4316. # Deliberately NOT recorded as a cool-off give-up. This branch
  4317. # only runs on an unreachable verdict, and that verdict is the
  4318. # honest, permanent reason the archive is empty — the probe was
  4319. # a long shot on top of it. Blaming the cool-off here would
  4320. # schedule a retry for a file sitting on internal eMMC, which is
  4321. # the sweep #2780 removed (#2957).
  4322. logger.debug(
  4323. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4324. storage.probe_filename,
  4325. printer_id,
  4326. )
  4327. else:
  4328. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4329. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4330. try:
  4331. probe_hit = await download_file_try_paths_async(
  4332. printer.ip_address,
  4333. printer.access_code,
  4334. ftp_probe_paths(storage.probe_filename),
  4335. probe_path,
  4336. socket_timeout=ftp_timeout,
  4337. printer_model=printer.model,
  4338. )
  4339. except Exception as e:
  4340. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4341. probe_hit = False
  4342. if probe_hit:
  4343. downloaded_filename = storage.probe_filename
  4344. temp_path = probe_path
  4345. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4346. # Naming the path, not just the file: a printer that keeps
  4347. # uploads around for weeks can serve a same-named copy of an
  4348. # earlier slice, and without the directory in the log that
  4349. # mismatch is invisible rather than merely rare (#1820).
  4350. logger.info(
  4351. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4352. downloaded_filename,
  4353. probe_hit,
  4354. printer_id,
  4355. storage.reason,
  4356. )
  4357. if not storage.reachable and not downloaded_filename:
  4358. # Same opening words whether or not a probe ran, because that is
  4359. # the phrase support asks people to grep for — only the tail says
  4360. # which of the two happened.
  4361. logger.info(
  4362. "Skipping the 3MF lookup for printer %s: %s — %s",
  4363. printer_id,
  4364. storage.reason,
  4365. "no copy of it on external storage either"
  4366. if storage.probe_filename
  4367. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4368. )
  4369. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4370. if not try_filename.endswith(".3mf"):
  4371. continue
  4372. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4373. # printers, so try it first — deferring it to last cost #972's reporter
  4374. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4375. # landing on the path that actually had the file.
  4376. remote_paths = [
  4377. f"/{try_filename}",
  4378. f"/cache/{try_filename}",
  4379. f"/model/{try_filename}",
  4380. f"/data/{try_filename}",
  4381. f"/data/Metadata/{try_filename}",
  4382. ]
  4383. temp_path = app_settings.archive_dir / "temp" / try_filename
  4384. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4385. for remote_path in remote_paths:
  4386. if ftps_handshake_blocked(printer.ip_address):
  4387. # The printer's FTPS service is not completing a TLS
  4388. # handshake, so it has no path we could reach — walking the
  4389. # remaining candidates only re-runs the same failure
  4390. # (#2780). Fall through to the no-3MF archive now.
  4391. #
  4392. # Remember *why*, though. This is the one give-up that is
  4393. # temporary: the cool-off clears in minutes and the file was
  4394. # on the printer the whole time. The fallback archive is
  4395. # stamped with it so a retry can be scheduled, and so the
  4396. # Archives banner stops blaming storage (#2957).
  4397. blocked_by_ftps_cooloff = True
  4398. logger.warning(
  4399. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4400. printer_id,
  4401. )
  4402. break
  4403. logger.debug("Trying FTP download: %s", remote_path)
  4404. try:
  4405. if ftp_retry_enabled:
  4406. downloaded = await with_ftp_retry(
  4407. download_file_async,
  4408. printer.ip_address,
  4409. printer.access_code,
  4410. remote_path,
  4411. temp_path,
  4412. timeout=ftp_timeout,
  4413. socket_timeout=ftp_timeout,
  4414. printer_model=printer.model,
  4415. max_retries=ftp_retry_count,
  4416. retry_delay=ftp_retry_delay,
  4417. operation_name=f"Download 3MF from {remote_path}",
  4418. cooloff_ip=printer.ip_address,
  4419. non_retry_exceptions=(FileNotOnPrinterError,),
  4420. )
  4421. else:
  4422. downloaded = await download_file_async(
  4423. printer.ip_address,
  4424. printer.access_code,
  4425. remote_path,
  4426. temp_path,
  4427. timeout=ftp_timeout,
  4428. socket_timeout=ftp_timeout,
  4429. printer_model=printer.model,
  4430. )
  4431. if downloaded:
  4432. downloaded_filename = try_filename
  4433. logger.info("Downloaded: %s", remote_path)
  4434. # Populate shared cache so the cover endpoint (if it
  4435. # runs next) doesn't refetch the same 36MB over FTP.
  4436. cache_3mf_download(printer_id, try_filename, temp_path)
  4437. break
  4438. # with_ftp_retry returns None once it has spent its budget,
  4439. # and download_file_async returns False on a timeout, so an
  4440. # exhausted transfer arrives here rather than as an
  4441. # exception (#3063).
  4442. ftp_transfer_failed = True
  4443. except FileNotOnPrinterError:
  4444. # 550 — file isn't at this path. Advance to next candidate
  4445. # without burning the retry budget.
  4446. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4447. except Exception as e:
  4448. ftp_transfer_failed = True
  4449. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4450. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4451. break
  4452. # If still not found, try listing directories to find matching file
  4453. # Different printer models use different directory structures. Skipped
  4454. # when the printer's FTPS handshake is failing — the directory walk is
  4455. # five more connections that cannot get further than the download did.
  4456. if (
  4457. not downloaded_filename
  4458. and storage.reachable
  4459. and (filename or subtask_name)
  4460. and not ftps_handshake_blocked(printer.ip_address)
  4461. ):
  4462. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4463. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4464. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4465. for search_dir in search_dirs:
  4466. if downloaded_filename:
  4467. break
  4468. try:
  4469. dir_files = await list_files_async(
  4470. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4471. )
  4472. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4473. if threemf_files:
  4474. logger.info(
  4475. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4476. )
  4477. for f in dir_files:
  4478. if f.get("is_directory"):
  4479. continue
  4480. fname = f.get("name", "")
  4481. # Normalize both for comparison (spaces and underscores are equivalent)
  4482. fname_normalized = fname.lower().replace(" ", "_")
  4483. search_normalized = search_term.replace(" ", "_")
  4484. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4485. logger.info("Found matching file in %s: %s", search_dir, fname)
  4486. temp_path = app_settings.archive_dir / "temp" / fname
  4487. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4488. remote_full_path = posixpath.join(search_dir, fname)
  4489. if ftp_retry_enabled:
  4490. downloaded = await with_ftp_retry(
  4491. download_file_async,
  4492. printer.ip_address,
  4493. printer.access_code,
  4494. remote_full_path,
  4495. temp_path,
  4496. timeout=ftp_timeout,
  4497. socket_timeout=ftp_timeout,
  4498. printer_model=printer.model,
  4499. max_retries=ftp_retry_count,
  4500. retry_delay=ftp_retry_delay,
  4501. operation_name=f"Download 3MF from {remote_full_path}",
  4502. cooloff_ip=printer.ip_address,
  4503. )
  4504. else:
  4505. downloaded = await download_file_async(
  4506. printer.ip_address,
  4507. printer.access_code,
  4508. remote_full_path,
  4509. temp_path,
  4510. timeout=ftp_timeout,
  4511. socket_timeout=ftp_timeout,
  4512. printer_model=printer.model,
  4513. )
  4514. if downloaded:
  4515. downloaded_filename = fname
  4516. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4517. cache_3mf_download(printer_id, fname, temp_path)
  4518. break
  4519. # The listing named the file, so it is on the card;
  4520. # only the transfer failed (#3063).
  4521. ftp_transfer_failed = True
  4522. except Exception as e:
  4523. logger.debug("Failed to list %s: %s", search_dir, e)
  4524. # Validate the downloaded 3MF actually matches the plate that's running
  4525. # (#1204): subtask_name lags across consecutive plates of the same model,
  4526. # so the first FTP candidate (built from subtask_name) can land on the
  4527. # previous plate's still-resident upload. Cross-check the slice_info
  4528. # plate index against the plate parsed from gcode_file (always fresh —
  4529. # it's the field whose change triggered this callback).
  4530. if downloaded_filename and temp_path:
  4531. expected_plate = parse_plate_id(filename)
  4532. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4533. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4534. logger.warning(
  4535. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4536. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4537. downloaded_filename,
  4538. actual_plate,
  4539. expected_plate,
  4540. subtask_name,
  4541. )
  4542. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4543. retry_succeeded = False
  4544. if corrected_subtask and corrected_subtask != subtask_name:
  4545. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4546. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4547. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4548. for remote_path in (
  4549. f"/{try_filename}",
  4550. f"/cache/{try_filename}",
  4551. f"/model/{try_filename}",
  4552. f"/data/{try_filename}",
  4553. f"/data/Metadata/{try_filename}",
  4554. ):
  4555. try:
  4556. if ftp_retry_enabled:
  4557. downloaded = await with_ftp_retry(
  4558. download_file_async,
  4559. printer.ip_address,
  4560. printer.access_code,
  4561. remote_path,
  4562. retry_temp_path,
  4563. timeout=ftp_timeout,
  4564. socket_timeout=ftp_timeout,
  4565. printer_model=printer.model,
  4566. max_retries=ftp_retry_count,
  4567. retry_delay=ftp_retry_delay,
  4568. operation_name=f"Re-download 3MF from {remote_path}",
  4569. cooloff_ip=printer.ip_address,
  4570. non_retry_exceptions=(FileNotOnPrinterError,),
  4571. )
  4572. else:
  4573. downloaded = await download_file_async(
  4574. printer.ip_address,
  4575. printer.access_code,
  4576. remote_path,
  4577. retry_temp_path,
  4578. timeout=ftp_timeout,
  4579. socket_timeout=ftp_timeout,
  4580. printer_model=printer.model,
  4581. )
  4582. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4583. logger.info(
  4584. "[CALLBACK] Re-download succeeded with corrected name %s "
  4585. "(plate %s) — replacing wrong file",
  4586. try_filename,
  4587. expected_plate,
  4588. )
  4589. try:
  4590. temp_path.unlink(missing_ok=True)
  4591. except OSError:
  4592. pass
  4593. temp_path = retry_temp_path
  4594. downloaded_filename = try_filename
  4595. subtask_name = corrected_subtask
  4596. cache_3mf_download(printer_id, try_filename, temp_path)
  4597. retry_succeeded = True
  4598. break
  4599. elif downloaded:
  4600. # Wrong plate again — discard and keep trying
  4601. try:
  4602. retry_temp_path.unlink(missing_ok=True)
  4603. except OSError:
  4604. pass
  4605. except FileNotOnPrinterError:
  4606. continue
  4607. except Exception as e:
  4608. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4609. if retry_succeeded:
  4610. break
  4611. # If the retry didn't find a matching file, drop the wrong 3MF
  4612. # so the no-3MF fallback below creates an archive whose name
  4613. # at least reflects the right plate.
  4614. if not retry_succeeded:
  4615. logger.warning(
  4616. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4617. expected_plate,
  4618. )
  4619. try:
  4620. temp_path.unlink(missing_ok=True)
  4621. except OSError:
  4622. pass
  4623. temp_path = None
  4624. downloaded_filename = None
  4625. # Whatever the sweep's transport did earlier, it is not why
  4626. # this archive ends up empty: a 3MF downloaded fine, it was
  4627. # just the wrong plate. Retrying would re-fetch that same
  4628. # contradicted file under the same stale names and hand it
  4629. # to _recover_fallback_archive, which checks that a
  4630. # candidate is a readable 3MF but not which plate it is --
  4631. # so the row would be filled in with another plate's
  4632. # filament and cost, the exact swap #2957 removed (#3063).
  4633. ftp_transfer_failed = False
  4634. # Disown the name for *lookups*: it has just been shown to
  4635. # fetch another plate's 3MF, and it keys `_active_prints`
  4636. # below, where the cover endpoint's own download of that
  4637. # same name would find this archive and fill it in with the
  4638. # file we are discarding here.
  4639. #
  4640. # Keep it for the *title*, which is a separate question.
  4641. # ``swap_plate_suffix`` returns None both for a name that
  4642. # carries no "- Plate N" / "_plate_N" suffix and for no
  4643. # name at all, and those are not the same situation: a name
  4644. # without a suffix holds no stale plate number to be wrong
  4645. # about. Blanking both uses at once dropped the project
  4646. # name too, and the row fell through to the gcode_file path
  4647. # titled "plate_1" though the real name was in hand.
  4648. # #1204's own premise is consecutive plates *of the same
  4649. # model*, so the project part is right either way (#3126).
  4650. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4651. subtask_name = corrected_subtask or ""
  4652. if not downloaded_filename or not temp_path:
  4653. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4654. # Create a fallback archive without 3MF data so the print is still tracked
  4655. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4656. try:
  4657. from backend.app.models.archive import PrintArchive
  4658. # Why the card is empty. The two temporary causes outrank the
  4659. # storage verdict because they say the sweep never got a fair
  4660. # answer: a cool-off skipped it at the transport, and a failed
  4661. # transfer reached the printer but never finished. Either way
  4662. # the file is still on the card, so reporting where the printer
  4663. # files its jobs would describe a setting that is not the
  4664. # problem (#2957, #3063).
  4665. if blocked_by_ftps_cooloff:
  4666. no_3mf_reason = REASON_FTPS_COOLOFF
  4667. elif storage.reachable and ftp_transfer_failed:
  4668. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4669. else:
  4670. no_3mf_reason = storage.reason
  4671. # Derive print name from subtask_name or filename. The
  4672. # plate guard's disowned name comes second: it is a real name
  4673. # for a real print, and only the gcode_file path is left
  4674. # otherwise -- which titles the row "plate_1" (#3126).
  4675. print_name = subtask_name or display_name_after_plate_reject or filename
  4676. if print_name:
  4677. # Clean up the name (remove extensions, path parts)
  4678. print_name = print_name.split("/")[-1]
  4679. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4680. else:
  4681. print_name = "Unknown Print"
  4682. # Recover estimated print time from MQTT (best-effort for notifications)
  4683. fallback_print_time = None
  4684. mqtt_remaining = data.get("remaining_time")
  4685. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4686. fallback_print_time = int(mqtt_remaining)
  4687. if fallback_print_time is None:
  4688. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4689. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4690. fallback_print_time = int(mc_remaining * 60)
  4691. # Best-effort filament metadata from MQTT — see
  4692. # _extract_filament_data_from_mqtt. Without this the fallback
  4693. # archive's filament fields stayed NULL even though the AMS
  4694. # state at print start was sitting right there in `data`.
  4695. # The slicer's ams_mapping (when present) narrows the result
  4696. # to slots actually used by the print (#1533).
  4697. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4698. # Create minimal archive entry
  4699. fallback_archive = PrintArchive(
  4700. printer_id=printer_id,
  4701. filename=filename or f"{print_name}.3mf",
  4702. file_path="", # Empty - no 3MF file available
  4703. file_size=0,
  4704. print_name=print_name,
  4705. print_time_seconds=fallback_print_time,
  4706. status="printing",
  4707. started_at=datetime.now(timezone.utc),
  4708. subtask_id=subtask_id,
  4709. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4710. filament_type=mqtt_filament_meta.get("filament_type"),
  4711. filament_color=mqtt_filament_meta.get("filament_color"),
  4712. extra_data={
  4713. "no_3mf_available": True,
  4714. # Why the card is empty, when we know -- see above. The
  4715. # banner reads this to stop telling H2/P2 owners to
  4716. # switch on a setting that is already on and would not
  4717. # have helped (#2780).
  4718. "no_3mf_reason": no_3mf_reason,
  4719. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4720. "_print_data": data,
  4721. },
  4722. )
  4723. db.add(fallback_archive)
  4724. await db.commit()
  4725. await db.refresh(fallback_archive)
  4726. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4727. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4728. # Track as active print
  4729. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4730. if filename:
  4731. _active_prints[(printer_id, filename)] = fallback_archive.id
  4732. if subtask_name:
  4733. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4734. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4735. # Record starting energy if smart plug available (#941: persisted column)
  4736. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4737. # Send WebSocket notification
  4738. await ws_manager.send_archive_created(
  4739. {
  4740. "id": fallback_archive.id,
  4741. "printer_id": fallback_archive.printer_id,
  4742. "filename": fallback_archive.filename,
  4743. "print_name": fallback_archive.print_name,
  4744. "status": fallback_archive.status,
  4745. }
  4746. )
  4747. # MQTT relay - publish archive created
  4748. try:
  4749. await mqtt_relay.on_archive_created(
  4750. archive_id=fallback_archive.id,
  4751. print_name=fallback_archive.print_name,
  4752. printer_name=printer.name,
  4753. status=fallback_archive.status,
  4754. )
  4755. except Exception:
  4756. pass # Don't fail if MQTT fails
  4757. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4758. try:
  4759. await _store_spoolman_print_data(
  4760. printer_id,
  4761. fallback_archive.id,
  4762. fallback_archive.file_path,
  4763. db,
  4764. printer_manager,
  4765. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4766. plate_id=_get_start_plate_id(fallback_archive.id),
  4767. )
  4768. except Exception as e:
  4769. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4770. # Both temporary give-ups are worth coming back for, and for
  4771. # the same reason: the file is on the printer and the last look
  4772. # failed at the transport rather than finding nothing. One waits
  4773. # out the handshake block (#2957), the other waits for the
  4774. # printer to stop being busy (#3063). Deliberately not scheduled
  4775. # for a storage verdict: a file on internal eMMC will not appear
  4776. # at any FTPS path however long we wait, and retrying it is
  4777. # exactly the sweep #2780 removed.
  4778. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4779. # `possible_names`, not the raw MQTT strings: it is the exact
  4780. # list this flow just tried, already stripped of any path
  4781. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4782. # some firmware) and deduped.
  4783. _schedule_fallback_3mf_retry(
  4784. printer_id=printer_id,
  4785. archive_id=fallback_archive.id,
  4786. filenames=list(possible_names),
  4787. reason=no_3mf_reason,
  4788. )
  4789. # Send notification without archive data (file not found)
  4790. if not notification_sent:
  4791. await _send_print_start_notification(printer_id, data, logger=logger)
  4792. # The same baseline the other two on_print_start branches take
  4793. # (#2704), and last for the same reason they are: it lists the
  4794. # printer's timelapse directory, so a slow card must not delay
  4795. # the _active_prints registration, the energy reading, the
  4796. # archive-created event or the start notification above it.
  4797. #
  4798. # This branch never took one, so every no-3MF archive reached
  4799. # completion with no baseline in memory and none on the row, and
  4800. # the completion scan fell into its "snapshot now" fallback --
  4801. # which runs after the printer has written the video, so the new
  4802. # file landed inside the baseline and no diff ever matched
  4803. # (#2957 follow-up).
  4804. #
  4805. # Skipped when the FTPS cool-off is what produced this fallback:
  4806. # the listing needs the same connection that just failed, so it
  4807. # could only record that the card was unreadable. The scan
  4808. # handles that case by refusing to choose between candidates.
  4809. if not blocked_by_ftps_cooloff:
  4810. await _capture_timelapse_baseline_at_start(
  4811. printer, printer_id, logger, archive_id=fallback_archive.id
  4812. )
  4813. return
  4814. except Exception as e:
  4815. logger.error("Failed to create fallback archive: %s", e)
  4816. # Send notification without archive data (file not found)
  4817. if not notification_sent:
  4818. await _send_print_start_notification(printer_id, data, logger=logger)
  4819. return
  4820. try:
  4821. # Archive the file with status "printing"
  4822. service = ArchiveService(db)
  4823. archive = await service.archive_print(
  4824. printer_id=printer_id,
  4825. source_file=temp_path,
  4826. print_data={**data, "status": "printing"},
  4827. subtask_id=subtask_id,
  4828. )
  4829. if archive:
  4830. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4831. # Set on the row rather than passed to archive_print, which also
  4832. # serves the queue dispatcher — there the queue item decides.
  4833. # Guarded because this branch has no ``except``: an unhandled
  4834. # write error would take the _active_prints registration, the
  4835. # start notification, the energy reading and the timelapse
  4836. # baseline below it with it, and a missing prompt is by far the
  4837. # cheaper failure.
  4838. archive_id = archive.id
  4839. try:
  4840. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4841. archive.confirm_requested = True
  4842. await db.commit()
  4843. except Exception as e:
  4844. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  4845. # The rollback expires every loaded object, and on an async
  4846. # session reading one afterwards raises instead of
  4847. # reloading, so the two this branch goes on to use are
  4848. # fetched again. The archive itself was committed by
  4849. # archive_print; only the flag is lost.
  4850. try:
  4851. await db.rollback()
  4852. archive = await db.get(PrintArchive, archive_id)
  4853. printer = await db.get(Printer, printer_id)
  4854. except Exception as reload_error:
  4855. logger.warning(
  4856. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  4857. )
  4858. # Track this active print (use both original filename and downloaded filename)
  4859. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4860. if filename and filename != downloaded_filename:
  4861. _active_prints[(printer_id, filename)] = archive.id
  4862. if subtask_name:
  4863. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4864. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4865. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4866. # Record starting energy from smart plug if available (#941: persisted column)
  4867. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4868. await ws_manager.send_archive_created(
  4869. {
  4870. "id": archive.id,
  4871. "printer_id": archive.printer_id,
  4872. "filename": archive.filename,
  4873. "print_name": archive.print_name,
  4874. "status": archive.status,
  4875. }
  4876. )
  4877. # MQTT relay - publish archive created
  4878. try:
  4879. await mqtt_relay.on_archive_created(
  4880. archive_id=archive.id,
  4881. print_name=archive.print_name,
  4882. printer_name=printer.name,
  4883. status=archive.status,
  4884. )
  4885. except Exception:
  4886. pass # Don't fail if MQTT fails
  4887. # Send notification with archive data (new archive created)
  4888. if not notification_sent:
  4889. archive_data = {
  4890. "print_time_seconds": archive.print_time_seconds,
  4891. "created_by_id": archive.created_by_id,
  4892. }
  4893. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4894. # Extract printable objects for skip object functionality
  4895. try:
  4896. from backend.app.services.archive import extract_printable_objects_from_3mf
  4897. client = printer_manager.get_client(printer_id)
  4898. if client:
  4899. with open(temp_path, "rb") as f:
  4900. threemf_data = f.read()
  4901. # Extract with positions for UI overlay, scoped to the
  4902. # plate that is printing — an all-plates 3MF carries
  4903. # every plate's objects (#2522).
  4904. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4905. threemf_data,
  4906. plate_number=resolve_plate_id(client.state),
  4907. include_positions=True,
  4908. )
  4909. if printable_objects:
  4910. # Store objects in printer state
  4911. client.state.printable_objects = printable_objects
  4912. client.state.printable_objects_bbox_all = bbox_all
  4913. client.state.skipped_objects = [] # Reset skipped objects for new print
  4914. logger.info(
  4915. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4916. )
  4917. except Exception as e:
  4918. logger.debug("Failed to extract printable objects: %s", e)
  4919. # Store Spoolman tracking data for per-filament usage reporting
  4920. try:
  4921. await _store_spoolman_print_data(
  4922. printer_id,
  4923. archive.id,
  4924. archive.file_path,
  4925. db,
  4926. printer_manager,
  4927. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4928. plate_id=_get_start_plate_id(archive.id),
  4929. )
  4930. except Exception as e:
  4931. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4932. # Price the print from its spools now rather than only at completion (#3261)
  4933. _schedule_archive_cost_estimate(
  4934. printer_id,
  4935. archive.id,
  4936. printer_manager,
  4937. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4938. plate_id=_get_start_plate_id(archive.id),
  4939. session_factory=async_session,
  4940. )
  4941. # Capture timelapse file baseline for snapshot-diff on completion
  4942. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4943. finally:
  4944. # Keep temp_path around until print completes so the cover endpoint
  4945. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4946. # the file. If the cache entry was evicted early (file vanished),
  4947. # clean up any stragglers here to avoid leaking disk on retries.
  4948. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4949. if temp_path and temp_path.exists() and cached_now != temp_path:
  4950. temp_path.unlink()
  4951. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4952. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4953. # tests can shrink them without waiting out real delays.
  4954. #
  4955. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4956. # looking. Across 247 support bundles the attempt that found the video was #1
  4957. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4958. # decaying one, which is the signature of a budget that expires while files are
  4959. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4960. # prints make big videos and the printer writes them after the print ends, so
  4961. # the poll now runs for minutes and costs one FTP LIST per round.
  4962. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4963. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4964. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4965. def _timelapse_scan_max_attempts() -> int:
  4966. """Round cap for the poll, derived from the wall-clock budget.
  4967. The deadline alone is not a sufficient bound: it assumes each round really
  4968. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4969. and an FTP list that fails immediately would otherwise spin against the
  4970. printer at full speed for the whole window. Whichever bound is reached
  4971. first ends the poll.
  4972. """
  4973. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4974. # A zero interval makes the wall-clock budget meaningless; fall back to
  4975. # the round count the production interval would have given.
  4976. return 32
  4977. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4978. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4979. """Video filenames already attached to some other archive of this printer.
  4980. Used to disambiguate when more than one file is new since the baseline —
  4981. which happens when a previous print's video landed after this print's
  4982. baseline was taken. Ordering the candidates would be the obvious fix and is
  4983. the wrong one: it can only be done on mtime or on the filename timestamp,
  4984. both of which come from the printer's own clock, and a LAN-only printer
  4985. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4986. ``attach_timelapse`` saves the video into the archive directory under the
  4987. printer's original filename, and the later MP4 conversion keeps the stem,
  4988. so the stem of ``timelapse_path`` recovers what was claimed.
  4989. """
  4990. from backend.app.models.archive import PrintArchive
  4991. rows = await db.execute(
  4992. select(PrintArchive.timelapse_path).where(
  4993. PrintArchive.printer_id == printer_id,
  4994. PrintArchive.id != exclude_archive_id,
  4995. PrintArchive.timelapse_path.is_not(None),
  4996. )
  4997. )
  4998. return {Path(p).stem for p in rows.scalars().all() if p}
  4999. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5000. """Whether an *empty* timelapse listing for *printer* can be believed.
  5001. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5002. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5003. from one holding no videos. Everywhere that only wants to know "is there a
  5004. video yet" the difference does not matter — both mean "not yet, retry".
  5005. It matters where an empty listing is recorded as a *baseline*. Recording
  5006. "the card held nothing" for a card that was never read means every video on
  5007. it counts as new once the cool-off expires, and the completion scan then
  5008. attaches a stale video to this print and deletes it from the printer
  5009. (#2957 follow-up). Those two callers ask this first.
  5010. """
  5011. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5012. ip_address = getattr(printer, "ip_address", None)
  5013. if not ip_address:
  5014. return True
  5015. return not ftps_handshake_blocked(ip_address)
  5016. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5017. """List video files from printer's timelapse directory.
  5018. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5019. Returns (video_files, found_path) where video_files is a list of file dicts
  5020. and found_path is the directory where they were found, or ([], None).
  5021. An empty return does not distinguish "no videos" from "could not read the
  5022. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5023. baseline callers consult before believing one.
  5024. """
  5025. from backend.app.services.bambu_ftp import list_files_async
  5026. logger = logging.getLogger(__name__)
  5027. # No card in the slot means no /timelapse to walk — four connections that
  5028. # can only fail, on a path whose failures are swallowed and so would go on
  5029. # costing time silently forever (#2780).
  5030. #
  5031. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5032. # inside the loop's own try/except, so a caller that passed something
  5033. # unexpected used to get an empty listing rather than an exception. Keep
  5034. # that, instead of making this gate the first thing that can raise here.
  5035. printer_id = getattr(printer, "id", None)
  5036. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5037. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5038. return [], None
  5039. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5040. try:
  5041. found_files = await list_files_async(
  5042. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5043. )
  5044. if found_files:
  5045. video_files = [
  5046. f
  5047. for f in found_files
  5048. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5049. ]
  5050. if video_files:
  5051. return video_files, timelapse_path
  5052. except Exception as e:
  5053. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5054. continue
  5055. return [], None
  5056. async def _capture_timelapse_baseline_at_start(
  5057. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5058. ) -> None:
  5059. """Snapshot the printer's timelapse directory at print start so the
  5060. completion-time scan can pick the new file by set-difference.
  5061. Must be called from every on_print_start path that proceeds to a real
  5062. print — both the new-archive branch and the expected-archive branch (which
  5063. queue / VP-dispatched prints take). Without a baseline,
  5064. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5065. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5066. so the new file ends up in the "baseline" set and no diff ever matches.
  5067. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5068. unreliable — the snapshot-diff approach sidesteps that entirely.
  5069. When ``archive_id`` is known the baseline is also written to the archive
  5070. row, so it survives a restart and the manual "Scan for Timelapse" button
  5071. can run the same diff instead of falling back to clock-based matching
  5072. (#2704). Only baselines taken at print start are persisted — one taken at
  5073. completion already contains the new video and would poison a later scan.
  5074. """
  5075. names: set[str] | None = None
  5076. try:
  5077. if not _timelapse_listing_is_trustworthy(printer):
  5078. # Recorded anyway, deliberately. An empty baseline taken off a card
  5079. # we could not read is not authoritative, but it is still the right
  5080. # *default*: Bambuddy deletes each video from the printer once it is
  5081. # attached, so the usual card holds exactly one video at completion
  5082. # and an empty baseline resolves it correctly. Persisting NULL
  5083. # instead would send completion to take its own snapshot, by which
  5084. # point this print's video is on the card and would be swallowed by
  5085. # it. The ambiguity is handled where it actually bites — see
  5086. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5087. logger.warning(
  5088. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5089. "handshake cool-off, so the card could not be read — treating it as empty",
  5090. printer_id,
  5091. )
  5092. baseline_files, _ = await _list_timelapse_videos(printer)
  5093. names = {f.get("name", "") for f in baseline_files}
  5094. _timelapse_baselines[printer_id] = names
  5095. logger.info(
  5096. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5097. len(names),
  5098. printer_id,
  5099. )
  5100. except Exception as e:
  5101. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5102. if archive_id is None:
  5103. return
  5104. try:
  5105. async with async_session() as db:
  5106. from backend.app.models.archive import PrintArchive
  5107. archive = await db.get(PrintArchive, archive_id)
  5108. if archive is not None:
  5109. # Written even when the listing failed, and then as NULL. A
  5110. # reprint reuses the archive row, so leaving the previous run's
  5111. # baseline in place would have the scan diff this print against
  5112. # the state of the printer before the *last* one — and a stale
  5113. # baseline reads as authoritative, where NULL correctly falls
  5114. # back to a fresh snapshot.
  5115. archive.timelapse_baseline = sorted(names) if names is not None else None
  5116. await db.commit()
  5117. except Exception as e:
  5118. # In-memory baseline still covers the normal completion path.
  5119. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5120. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  5121. """Poll the printer for this print's timelapse and attach it.
  5122. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5123. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5124. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5125. (#2704). Comparing the current listing against the set of filenames that
  5126. existed when the print started needs no clock at all, because the printer
  5127. writes the video only once the print has ended.
  5128. Baseline precedence: the caller's in-memory set, then the one persisted on
  5129. the archive at print start, then a snapshot taken now. The last of those is
  5130. a poor substitute — by completion the new video may already be on the card,
  5131. in which case it lands in the "baseline" and no diff can ever match — but it
  5132. is all that is available for a print that began before Bambuddy started.
  5133. On success the video is deleted from the printer, which keeps ``/timelapse``
  5134. down to the unclaimed files and makes the next diff unambiguous.
  5135. """
  5136. logger = logging.getLogger(__name__)
  5137. # Cleared when the baseline had to be taken off a card we could not read, so
  5138. # the attach step refuses to choose between several candidates (#2957).
  5139. baseline_trusted = True
  5140. # --- Phase 1: establish the baseline -------------------------------------
  5141. try:
  5142. async with async_session() as db:
  5143. from backend.app.models.printer import Printer
  5144. service = ArchiveService(db)
  5145. archive = await service.get_archive(archive_id)
  5146. if not archive:
  5147. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5148. return
  5149. if archive.timelapse_path:
  5150. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5151. return
  5152. if not archive.printer_id:
  5153. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5154. return
  5155. if baseline_names is not None:
  5156. logger.info(
  5157. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5158. len(baseline_names),
  5159. archive_id,
  5160. )
  5161. elif archive.timelapse_baseline is not None:
  5162. # Persisted at print start — survives a restart mid-print.
  5163. baseline_names = set(archive.timelapse_baseline)
  5164. logger.info(
  5165. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5166. len(baseline_names),
  5167. archive_id,
  5168. )
  5169. else:
  5170. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5171. printer = result.scalar_one_or_none()
  5172. if not printer:
  5173. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5174. return
  5175. if not _timelapse_listing_is_trustworthy(printer):
  5176. # The card is unreadable at the one moment a baseline has to
  5177. # be taken, so the empty listing below means "we never
  5178. # looked", not "these are all new". Carry on with it anyway
  5179. # — the usual card holds exactly one video, which resolves
  5180. # correctly — but stop the poll from *choosing* between
  5181. # several, which is how a stale video got attached to this
  5182. # print and then deleted off the printer (#2957 follow-up).
  5183. baseline_trusted = False
  5184. logger.warning(
  5185. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5186. "handshake cool-off. A single new video still resolves; several will not be "
  5187. "guessed between — use Scan for Timelapse to pick one by hand",
  5188. archive_id,
  5189. archive.printer_id,
  5190. )
  5191. baseline_files, _ = await _list_timelapse_videos(printer)
  5192. baseline_names = {f.get("name", "") for f in baseline_files}
  5193. logger.info(
  5194. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5195. len(baseline_names),
  5196. archive_id,
  5197. )
  5198. except Exception as e:
  5199. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5200. return
  5201. # --- Phase 2: poll for a file that was not there when the print began -----
  5202. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5203. max_attempts = _timelapse_scan_max_attempts()
  5204. seen_names: set[str] = set()
  5205. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5206. attempt = 0
  5207. while True:
  5208. await asyncio.sleep(delay)
  5209. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5210. attempt += 1
  5211. try:
  5212. from backend.app.models.printer import Printer
  5213. # Read phase: fetch archive + printer in a short session and release
  5214. # the pooled connection BEFORE the FTP list/download below. Holding it
  5215. # across the FTP round-trips left one connection idle-in-transaction per
  5216. # in-flight scan (issue #2572).
  5217. async with async_session() as db:
  5218. service = ArchiveService(db)
  5219. archive = await service.get_archive(archive_id)
  5220. if not archive:
  5221. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5222. return
  5223. if archive.timelapse_path:
  5224. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5225. return
  5226. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5227. printer = result.scalar_one_or_none()
  5228. if not printer:
  5229. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5230. return
  5231. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5232. # I/O phase (no DB connection held): FTP list + download.
  5233. video_files, found_path = await _list_timelapse_videos(printer)
  5234. # The poll can run for dozens of rounds, so only narrate a round
  5235. # that saw something change. Repeating the whole listing every 30 s
  5236. # would bury the one interesting line in the support bundle.
  5237. names_now = {f.get("name", "") for f in video_files}
  5238. changed = attempt == 1 or names_now != seen_names
  5239. seen_names = names_now
  5240. speak = logger.info if changed else logger.debug
  5241. if video_files:
  5242. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5243. if changed:
  5244. for f in video_files[:5]:
  5245. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5246. attached = await _attach_first_unclaimed_timelapse(
  5247. archive_id,
  5248. printer,
  5249. video_files,
  5250. baseline_names,
  5251. claimed,
  5252. attempt,
  5253. logger,
  5254. quiet=not changed,
  5255. require_unambiguous=not baseline_trusted,
  5256. )
  5257. if attached:
  5258. return
  5259. else:
  5260. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5261. except Exception as e:
  5262. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5263. if attempt >= max_attempts or time.monotonic() >= deadline:
  5264. break
  5265. # No name-match fallback: it compared the print name against the filename,
  5266. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5267. # bundles it fired 159 times and matched zero times, so all it added was a
  5268. # misleading log line before giving up.
  5269. logger.warning(
  5270. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5271. archive_id,
  5272. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5273. )
  5274. async def _attach_first_unclaimed_timelapse(
  5275. archive_id: int,
  5276. printer,
  5277. video_files: list[dict],
  5278. baseline_names: set[str],
  5279. claimed: set[str],
  5280. attempt: int,
  5281. logger: logging.Logger,
  5282. *,
  5283. quiet: bool = False,
  5284. require_unambiguous: bool = False,
  5285. ) -> bool:
  5286. """Download and attach the one video that belongs to this print.
  5287. A candidate is any file absent from the print-start baseline. More than one
  5288. can qualify when a previous print's video landed late, after this print's
  5289. baseline was taken — those are filtered out by name, because they are
  5290. already attached to another archive. Sorting the candidates instead would
  5291. mean sorting on mtime or on the filename timestamp, both of which come from
  5292. the printer's unsynced clock.
  5293. Returns True once a video is attached. The printer's copy is deleted only
  5294. after the attach succeeds on bytes whose length matched the listing.
  5295. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5296. already seen this exact listing — the poll runs for many rounds and only the
  5297. rounds where something changed are worth an INFO line.
  5298. """
  5299. from backend.app.services.bambu_ftp import (
  5300. delete_archived_timelapse,
  5301. download_file_bytes_async,
  5302. remote_file_settled,
  5303. )
  5304. speak = logger.debug if quiet else logger.info
  5305. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5306. if not new_files:
  5307. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5308. return False
  5309. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5310. if not candidates:
  5311. speak(
  5312. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5313. attempt,
  5314. len(new_files),
  5315. )
  5316. return False
  5317. if len(candidates) > 1:
  5318. if require_unambiguous:
  5319. # The baseline is not evidence -- it was taken off a card that could
  5320. # not be read -- so "new since the baseline" does not narrow these
  5321. # down at all. Taking the first would attach an arbitrary video to
  5322. # this print and then delete it from the printer.
  5323. logger.warning(
  5324. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5325. "leaving all of them on the printer for manual selection",
  5326. attempt,
  5327. len(candidates),
  5328. ", ".join(str(f.get("name")) for f in candidates),
  5329. )
  5330. return False
  5331. logger.warning(
  5332. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5333. "the rest stay on the printer for manual selection",
  5334. attempt,
  5335. len(candidates),
  5336. ", ".join(str(f.get("name")) for f in candidates),
  5337. )
  5338. target = candidates[0]
  5339. file_name = target.get("name")
  5340. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5341. logger.info(
  5342. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5343. attempt,
  5344. file_name,
  5345. archive_id,
  5346. )
  5347. # The listing always carries a size (`list_files` skips entries it can't
  5348. # parse), but read it explicitly: the delete below is destructive and must
  5349. # depend on a size we actually had, not on one we hoped was there.
  5350. expected_size = target.get("size")
  5351. timelapse_data = await download_file_bytes_async(
  5352. printer.ip_address,
  5353. printer.access_code,
  5354. remote_path,
  5355. printer_model=printer.model,
  5356. expected_size=expected_size,
  5357. )
  5358. if not timelapse_data:
  5359. # Short or failed transfer. The printer keeps its copy, so the next
  5360. # round can try again — which is exactly why the delete below is
  5361. # gated on a verified download.
  5362. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5363. return False
  5364. # The length check above proves we got what the listing said, not that the
  5365. # printer had finished writing. A video still being written can be listed
  5366. # short, served short, and pass — so confirm it has stopped growing before
  5367. # committing to it and deleting the original (#2704).
  5368. if not await remote_file_settled(
  5369. printer.ip_address,
  5370. printer.access_code,
  5371. remote_path,
  5372. len(timelapse_data),
  5373. printer_model=printer.model,
  5374. ):
  5375. return False
  5376. # Write phase: attach in a fresh short-lived session.
  5377. async with async_session() as db:
  5378. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  5379. if not success:
  5380. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5381. return False
  5382. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5383. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5384. await delete_archived_timelapse(
  5385. printer.ip_address,
  5386. printer.access_code,
  5387. remote_path,
  5388. verified=expected_size is not None,
  5389. printer_model=printer.model,
  5390. printer_name=printer.name,
  5391. )
  5392. return True
  5393. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5394. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5395. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5396. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5397. # How long the *background* upgrade keeps waiting after the notification has
  5398. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5399. # printer can't hold up the print-complete notification; this one exists so the
  5400. # archive still ends up with the better frame afterwards.
  5401. #
  5402. # Measured across 261 attaches in the support bundles, the video lands a median
  5403. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5404. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5405. # was 546s. Every other model was inside 26s. The long budget is therefore
  5406. # almost entirely for P1-series users; on everything else the short wait already
  5407. # wins and this task never runs.
  5408. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5409. async def _capture_finish_photo_from_timelapse(
  5410. archive_id: int,
  5411. archive_dir: Path,
  5412. timeout: float | None = None,
  5413. rotation: int = 0,
  5414. ) -> tuple[str | None, bool]:
  5415. """Wait for the per-print timelapse to land on the archive and extract its
  5416. last frame as the finish photo (#1397).
  5417. Bambu firmware stops timelapse recording after the toolhead parks but
  5418. before the bed-drop end-gcode runs, so the last frame frames the finished
  5419. print correctly. A live camera grab at gcode_state=FINISH captures the
  5420. bed already lowered.
  5421. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5422. ``archive.timelapse_path`` when the file lands. This function polls for
  5423. that field.
  5424. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5425. the wait ran out with no video on the archive yet — i.e. the video may
  5426. still be coming and a later attempt could succeed. It is False when the
  5427. video landed (whether or not extraction worked), because in that case
  5428. waiting longer changes nothing. The caller uses that to decide between
  5429. falling back permanently and scheduling a background upgrade.
  5430. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5431. still (#2708) so this source agrees with every other finish-photo source.
  5432. The archived video itself is the printer's own file and is left alone —
  5433. rotating it would mean re-encoding it.
  5434. """
  5435. import uuid
  5436. from backend.app.models.archive import PrintArchive
  5437. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5438. logger = logging.getLogger(__name__)
  5439. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5440. deadline = asyncio.get_event_loop().time() + budget
  5441. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5442. while True:
  5443. async with async_session() as db:
  5444. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5445. archive = result.scalar_one_or_none()
  5446. timelapse_relpath = archive.timelapse_path if archive else None
  5447. if timelapse_relpath:
  5448. video_path = app_settings.base_dir / timelapse_relpath
  5449. if video_path.exists() and video_path.stat().st_size > 0:
  5450. photos_dir = archive_dir / "photos"
  5451. photos_dir.mkdir(parents=True, exist_ok=True)
  5452. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5453. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5454. output_path = photos_dir / filename
  5455. if await extract_video_last_frame(video_path, output_path):
  5456. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5457. logger.info(
  5458. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5459. video_path.name,
  5460. archive_id,
  5461. )
  5462. return filename, False
  5463. logger.warning(
  5464. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5465. video_path.name,
  5466. archive_id,
  5467. )
  5468. return None, False
  5469. if asyncio.get_event_loop().time() >= deadline:
  5470. logger.info(
  5471. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5472. archive_id,
  5473. budget,
  5474. )
  5475. return None, True
  5476. await asyncio.sleep(poll_interval)
  5477. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5478. """Add the timelapse's last frame to an archive after the fact (#2704).
  5479. The print-complete notification waits only ~60s for the video, because
  5480. holding a notification for minutes is worse than sending it with a live
  5481. camera grab. On a P1-series printer the video often lands well after that,
  5482. so the archive used to be stuck with the live grab — which is taken at
  5483. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5484. the worse photo of the two.
  5485. This keeps waiting in the background and, when the video arrives, extracts
  5486. the frame and puts it *first* in the archive's photo list, so opening the
  5487. gallery shows it. The live grab is deliberately kept: the notification that
  5488. already went out links to that exact file, and deleting it would leave a
  5489. broken image in Discord or Telegram.
  5490. """
  5491. logger = logging.getLogger(__name__)
  5492. filename, _ = await _capture_finish_photo_from_timelapse(
  5493. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5494. )
  5495. if not filename:
  5496. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5497. return
  5498. try:
  5499. async with async_session() as db:
  5500. from backend.app.models.archive import PrintArchive
  5501. archive = await db.get(PrintArchive, archive_id)
  5502. if archive is None:
  5503. return
  5504. photos = list(archive.photos or [])
  5505. if filename in photos:
  5506. return
  5507. # Front of the list: PhotoGalleryModal opens at index 0.
  5508. archive.photos = [filename, *photos]
  5509. await db.commit()
  5510. except Exception as e:
  5511. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5512. return
  5513. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5514. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5515. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5516. """Put the filament-attribution context back after a restart mid-print.
  5517. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5518. both die with the process. The print keeps running, so at completion the
  5519. tracker would fall back to whatever the printer reports *now* — and AMS
  5520. filament backup makes "now" the substitute tray, charging the whole print
  5521. to the spool that only finished it.
  5522. The persisted row is only trusted when its print name still matches what
  5523. the printer says it is running: a row left behind by a completion we never
  5524. saw must not attach itself to the next print.
  5525. """
  5526. try:
  5527. from backend.app.api.routes.settings import get_setting
  5528. from backend.app.services.usage_tracker import (
  5529. clear_persisted_session,
  5530. get_persisted_print_name,
  5531. restore_session,
  5532. )
  5533. persisted_name = await get_persisted_print_name(db, printer_id)
  5534. current_name = (state.subtask_name or "").strip()
  5535. if persisted_name and current_name and persisted_name.strip() != current_name:
  5536. logger.info(
  5537. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5538. printer_id,
  5539. persisted_name,
  5540. current_name,
  5541. )
  5542. await clear_persisted_session(db, printer_id)
  5543. # Fall through to seeding: the print on the printer is real, it just
  5544. # isn't the one the row described.
  5545. persisted_log = None
  5546. else:
  5547. # Spoolman users get the tray-change log back but no in-memory
  5548. # session — see ``on_print_start`` on why that dict is load-bearing
  5549. # for the remain%-sync guard.
  5550. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5551. persisted_log = await restore_session(
  5552. db,
  5553. printer_id,
  5554. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5555. )
  5556. if persisted_log:
  5557. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5558. # Anything this process already observed goes after the persisted
  5559. # history — the log is ordered by layer, and a fresh process can
  5560. # only have seen changes from later in the print.
  5561. for entry in state.tray_change_log or []:
  5562. if tuple(entry) not in restored:
  5563. restored.append(tuple(entry))
  5564. state.tray_change_log = restored
  5565. tray_now = state.tray_now
  5566. if 0 <= tray_now <= 254:
  5567. if not state.tray_change_log:
  5568. # No persisted history — a print that started before this build,
  5569. # or before the row existed. Seed with the tray feeding right
  5570. # now so the remainder of the print is at least attributable to
  5571. # the right spool.
  5572. state.tray_change_log = [(tray_now, state.layer_num)]
  5573. logger.info(
  5574. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5575. printer_id,
  5576. tray_now,
  5577. state.layer_num,
  5578. )
  5579. # The tray handler updates ``last_loaded_tray`` on every push
  5580. # regardless of whether it logged a change, so re-align it to avoid
  5581. # a duplicate entry on the next push. Only ever with a real tray:
  5582. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5583. # 255" fallback, and writing 255 into it would defeat that.
  5584. state.last_loaded_tray = tray_now
  5585. except Exception:
  5586. # Never let attribution recovery cost the caller its timelapse
  5587. # baseline — that capture has to happen before the printer uploads
  5588. # the in-flight MP4 and there is no second chance at it.
  5589. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5590. async def on_print_running_observed(printer_id: int, data: dict):
  5591. """Restart-recovery for a print that started before Bambuddy came up.
  5592. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5593. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5594. creation). This hook restores the persisted archive into ``_active_prints``
  5595. and captures the timelapse baseline that normally hangs off print start.
  5596. Fires once per session, in lieu of on_print_start when restart-recovery
  5597. kicks in. The printer doesn't upload the timelapse until after PRINT
  5598. COMPLETE, so a baseline captured any time during the print is still
  5599. pre-upload.
  5600. """
  5601. logger = logging.getLogger(__name__)
  5602. async with async_session() as db:
  5603. from backend.app.models.printer import Printer
  5604. state = printer_manager.get_status(printer_id)
  5605. if state is not None:
  5606. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5607. if authorization is True:
  5608. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5609. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5610. await _restore_printable_objects(printer_id, state, db, logger)
  5611. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5612. printer = result.scalar_one_or_none()
  5613. if not printer:
  5614. logger.warning(
  5615. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5616. printer_id,
  5617. )
  5618. return
  5619. # Avoid double-capture: ownership reconciliation above must still run when
  5620. # a baseline already exists, but the camera work itself is one-shot.
  5621. if printer_id in _timelapse_baselines:
  5622. logger.debug(
  5623. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5624. printer_id,
  5625. )
  5626. return
  5627. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5628. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5629. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5630. against the printer's current MQTT state.
  5631. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5632. COMPLETE events, typically a print finishing during an MQTT disconnect
  5633. window followed by a smart-plug power cycle):
  5634. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5635. provably not running anymore — only branch that should fire under
  5636. normal disconnect-then-reconnect timing.
  5637. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5638. firmware mints a fresh ``subtask_id`` for each print, including the
  5639. ghost replay it runs after a power cycle from a leftover SD file —
  5640. so a mismatch unambiguously means the in-DB archive is no longer
  5641. the print on the printer.
  5642. 3. Printer is running but ``subtask_name`` is empty. The printer
  5643. doesn't know what it's running; the archive's reference to it is
  5644. already broken.
  5645. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5646. with matching subtask_id+subtask_name is left alone. The cost of a false
  5647. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5648. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5649. clears on synthesis, so the real completion creates a fresh row instead
  5650. of overwriting the synthesised one (#1679). The cost of a false negative
  5651. is the ghost-print loop in #1542.
  5652. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5653. MQTT has connected but the first ``push_status`` response hasn't been
  5654. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5655. The reconcile caller in ``on_printer_status_change`` is already gated
  5656. on a real ``state.state``, so in normal operation this branch is
  5657. unreachable; it's kept as belt-and-braces for future callers and for
  5658. the narrow window where a partial state update could arrive
  5659. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5660. ``not stale`` on degenerate input is strictly conservative: a real
  5661. stale archive will still be caught by the next push_status arriving
  5662. with terminal state.
  5663. """
  5664. current_state = (state.state or "").upper()
  5665. if current_state in ("", "UNKNOWN"):
  5666. # No real push_status yet — PrinterState defaults are not evidence.
  5667. return False, ""
  5668. if current_state in ("IDLE", "FINISH", "FAILED"):
  5669. return True, f"printer state {current_state}"
  5670. # Below here the printer is in a running / pre-running state (RUNNING /
  5671. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5672. current_subtask_id = (state.subtask_id or "").strip()
  5673. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5674. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5675. current_subtask_name = (state.subtask_name or "").strip()
  5676. if not current_subtask_name:
  5677. return True, "printer subtask_name empty"
  5678. return False, ""
  5679. async def prime_kprofile_table(printer_id: int) -> int:
  5680. """Read the printer's calibration table once per connection.
  5681. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5682. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5683. report ``cali_idx`` and nothing else -- that number can only come from
  5684. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5685. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5686. backup, or the printer answering a query BambuStudio made on the report
  5687. topic we share. A Bambuddy that nobody visited showed a card with no K
  5688. values at all.
  5689. Only the diameters actually fitted are asked for, which is one request on a
  5690. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5691. what the backup does, and it is both wasteful and the thing that used to
  5692. blank the table.
  5693. Returns the number of nozzles whose table was read.
  5694. """
  5695. client = printer_manager.get_client(printer_id)
  5696. state = printer_manager.get_status(printer_id)
  5697. if client is None or state is None or not state.connected:
  5698. return 0
  5699. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5700. # ask once, and both entries are empty until the first push_status lands.
  5701. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5702. if not diameters:
  5703. logging.getLogger(__name__).debug(
  5704. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5705. printer_id,
  5706. )
  5707. return 0
  5708. primed = 0
  5709. for diameter in diameters:
  5710. try:
  5711. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5712. except Exception as exc: # noqa: BLE001
  5713. # A printer that won't answer costs the card its K values, nothing
  5714. # more — never the connection this runs on the back of.
  5715. logging.getLogger(__name__).warning(
  5716. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5717. )
  5718. continue
  5719. primed += 1
  5720. logging.getLogger(__name__).info(
  5721. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5722. )
  5723. return primed
  5724. def _sd_files_in_use(state) -> set[str]:
  5725. """Names of the SD-card files the printer may be printing right now (#3009).
  5726. The post-print cleanup works out what to delete from the finished archive,
  5727. not from the printer. When reconciliation closes an old archive because the
  5728. printer has moved on to a new job, and that job is the same file reprinted
  5729. from the printer's screen, the cleanup would delete the file mid-print.
  5730. Empty unless the printer is busy: on an ordinary completion the state is
  5731. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  5732. name, a path or a URL depending on firmware, and some report only the
  5733. plate's G-code, so the job name is matched as well, in the same spellings
  5734. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  5735. ignores case.
  5736. """
  5737. def _text(value) -> str:
  5738. return value.strip() if isinstance(value, str) else ""
  5739. if state is None:
  5740. return set()
  5741. current_state = _text(getattr(state, "state", None)).upper()
  5742. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  5743. return set()
  5744. in_use: set[str] = set()
  5745. gcode_file = _text(getattr(state, "gcode_file", None))
  5746. if gcode_file:
  5747. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  5748. # both legal in a file name, and raises on some inputs.
  5749. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  5750. if name:
  5751. in_use.add(name.lower())
  5752. subtask_name = _text(getattr(state, "subtask_name", None))
  5753. if subtask_name:
  5754. for name in (subtask_name, subtask_name.replace(" ", "_")):
  5755. for ext in (".3mf", ".gcode"):
  5756. in_use.add(f"{name}{ext}".lower())
  5757. return in_use
  5758. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5759. """Synthesise ``on_print_complete`` for archives whose print can't be
  5760. running on the printer anymore.
  5761. Called once per MQTT (re)connection (from on_printer_status_change when
  5762. the connected edge flips False → True) and at Bambuddy startup (from
  5763. the FastAPI lifespan). Without this, a print that completes during a
  5764. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5765. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5766. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5767. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5768. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5769. closes the loop by faking the missed PRINT COMPLETE — the existing
  5770. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5771. and notifications.
  5772. Synthesised ``status="aborted"`` is the conservative label: we have no
  5773. proof the print finished successfully (and no progress evidence to
  5774. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5775. fires later, overwrites the status with the correct value.
  5776. Returns the number of archives reconciled.
  5777. """
  5778. state = printer_manager.get_status(printer_id)
  5779. if not state:
  5780. return 0
  5781. # Don't reconcile while disconnected — we'd be making a decision against
  5782. # stale cached state. The connected → reconcile edge handles this.
  5783. if not state.connected:
  5784. return 0
  5785. from backend.app.models.archive import PrintArchive
  5786. reconciled = 0
  5787. async with async_session() as db:
  5788. result = await db.execute(
  5789. select(PrintArchive).where(
  5790. PrintArchive.printer_id == printer_id,
  5791. PrintArchive.status == "printing",
  5792. )
  5793. )
  5794. active = list(result.scalars().all())
  5795. if not active:
  5796. return 0
  5797. logger = logging.getLogger(__name__)
  5798. for archive in active:
  5799. is_stale, reason = _is_active_archive_stale(archive, state)
  5800. if not is_stale:
  5801. continue
  5802. logger.info(
  5803. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5804. printer_id,
  5805. archive.id,
  5806. archive.filename,
  5807. reason,
  5808. )
  5809. # Synthesised payload: minimal fields the on_print_complete chain
  5810. # needs. `_reconciled` marker lets downstream code distinguish this
  5811. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5812. # metrics / debug logging). raw_data is the live printer state so
  5813. # the usage tracker can compare end-of-print remain% against the
  5814. # captured start values.
  5815. try:
  5816. await on_print_complete(
  5817. printer_id,
  5818. {
  5819. "status": "aborted",
  5820. "filename": archive.filename,
  5821. "subtask_name": archive.print_name or "",
  5822. "subtask_id": archive.subtask_id or "",
  5823. "raw_data": state.raw_data or {},
  5824. "_reconciled": True,
  5825. },
  5826. )
  5827. reconciled += 1
  5828. except Exception as e:
  5829. # Catch-all: a reconciliation failure must not block the
  5830. # printer's normal status flow. The archive stays in
  5831. # ``status="printing"`` and the next reconnect retries.
  5832. logger.warning(
  5833. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5834. archive.id,
  5835. e,
  5836. )
  5837. return reconciled
  5838. # #2547: clearance left between the nozzle and the top of the print when the
  5839. # plate is commanded back into camera framing. The nozzle is parked away from
  5840. # the part by then, so this is belt-and-braces against a max_z_height that
  5841. # under-reports (e.g. a slicer that excludes a final Z hop).
  5842. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5843. # How far below the restored position to drop the plate again afterwards, so
  5844. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5845. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5846. # on machines with less headroom.
  5847. _PLATE_PARK_DROP_MM = 100.0
  5848. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5849. # this axis, so it is a proven-safe speed for the full travel.
  5850. _PLATE_RESTORE_FEEDRATE = 600
  5851. # Time allowed for the plate to reach the restored position before the camera
  5852. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5853. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5854. # How long `_background_finish_photo` waits for this producer. Must cover the
  5855. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5856. # notification path's own photo wait so a slow producer degrades to a
  5857. # photo-less notification rather than a missed one. The chamber light's
  5858. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  5859. # camera_light.MAX_DELAY_SECONDS stays below it.
  5860. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5861. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  5862. """The ``_active_prints`` keys a finished print may be registered under.
  5863. Matching how they were registered in on_print_start. Shared by
  5864. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  5865. to find the same binding.
  5866. """
  5867. possible_keys = []
  5868. # Try subtask_name variations first (most reliable for matching)
  5869. if subtask_name:
  5870. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5871. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5872. possible_keys.append((printer_id, subtask_name))
  5873. # Try filename variations
  5874. if filename:
  5875. # Extract just the filename if it's a path
  5876. fname = filename.split("/")[-1] if "/" in filename else filename
  5877. if fname.endswith(".3mf"):
  5878. possible_keys.append((printer_id, fname))
  5879. elif fname.endswith(".gcode"):
  5880. base_name = fname.rsplit(".", 1)[0]
  5881. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5882. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5883. possible_keys.append((printer_id, fname))
  5884. else:
  5885. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5886. possible_keys.append((printer_id, f"{fname}.3mf"))
  5887. possible_keys.append((printer_id, fname))
  5888. # Also try full path versions
  5889. if filename.endswith(".3mf"):
  5890. possible_keys.append((printer_id, filename))
  5891. elif filename.endswith(".gcode"):
  5892. base_name = filename.rsplit(".", 1)[0]
  5893. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5894. possible_keys.append((printer_id, filename))
  5895. else:
  5896. possible_keys.append((printer_id, f"{filename}.3mf"))
  5897. possible_keys.append((printer_id, filename))
  5898. return possible_keys
  5899. def _archive_name_forms(archive) -> set[str]:
  5900. """The names an archive could be echoed back as, in normalised form (#3240).
  5901. Its print name, and its filename with and without the 3MF extension.
  5902. """
  5903. forms = set()
  5904. if archive.print_name:
  5905. forms.add(_normalise_subtask_name(archive.print_name))
  5906. if archive.filename:
  5907. forms.add(_normalise_subtask_name(archive.filename))
  5908. for suffix in (".gcode.3mf", ".3mf"):
  5909. if archive.filename.lower().endswith(suffix):
  5910. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  5911. forms.discard("")
  5912. return forms
  5913. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  5914. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  5915. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  5916. from the plate recorded when the job was dispatched. Neither is touched:
  5917. ``on_print_complete`` pops both, which is why the finish-photo producer
  5918. calls this before its first await, while they are still there.
  5919. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  5920. archive, or that it only knows by a name -- and on any error: the producer
  5921. calls this before the ``try`` that always releases the photo consumer, so
  5922. it must not raise.
  5923. """
  5924. try:
  5925. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  5926. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  5927. if archive_id is None:
  5928. return None, None
  5929. return archive_id, _print_plate_ids.get(archive_id)
  5930. except Exception:
  5931. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  5932. return None, None
  5933. async def _max_z_for_current_print(
  5934. printer_id: int,
  5935. data: dict,
  5936. logger,
  5937. archive_id: int | None,
  5938. plate_id: int | None = None,
  5939. ) -> float | None:
  5940. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5941. This number becomes the target of a real Z move, so every step here refuses
  5942. rather than guesses. A height belonging to some *other* print is the one
  5943. failure that could drive the nozzle into the model: 20 mm carried onto a
  5944. 200 mm print would command the plate up through the part.
  5945. Three independent things therefore have to agree before a height is
  5946. returned:
  5947. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  5948. when it started (see ``_bound_print``), never one found by name. A name
  5949. is not an identity: every plate of a multi-plate file shares one, and a
  5950. reprint reuses its archive row, so the newest archive with the right
  5951. name can be another plate of the same file. Support bundles show the
  5952. old name lookup doing exactly that (archive 288 for a print bound to
  5953. 169, 313 layers against 125), stopped only by the layer check below.
  5954. No binding, no move.
  5955. 2. **Identity.** The bound archive's name still has to be the finished
  5956. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  5957. because the printer echoes spaces as underscores (#3240). Exact: not a
  5958. substring, and not the completion check's tolerance for a truncated
  5959. echo.
  5960. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5961. match the layer count the printer itself reported over MQTT for the print
  5962. that just ended. These come from genuinely different sources, so a
  5963. mismatch means the row is not this print, whatever its name says.
  5964. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  5965. plate of a multi-plate file reuses the archive row without updating its
  5966. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  5967. ``on_print_complete`` may already have flipped the status by the time we
  5968. run.
  5969. """
  5970. subtask_name = (data.get("subtask_name") or "").strip()
  5971. if not subtask_name:
  5972. # Nothing to identify the print by — refuse rather than fall back to
  5973. # "whatever ran last on this printer".
  5974. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5975. return None
  5976. if archive_id is None:
  5977. logger.info(
  5978. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  5979. printer_id,
  5980. subtask_name,
  5981. )
  5982. return None
  5983. try:
  5984. from backend.app.models.archive import PrintArchive
  5985. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5986. async with async_session() as db:
  5987. result = await db.execute(
  5988. select(PrintArchive).where(
  5989. PrintArchive.id == archive_id,
  5990. PrintArchive.printer_id == printer_id,
  5991. PrintArchive.status.in_(("printing", "completed")),
  5992. PrintArchive.deleted_at.is_(None),
  5993. )
  5994. )
  5995. archive = result.scalar_one_or_none()
  5996. if archive is None or not archive.file_path:
  5997. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  5998. return None
  5999. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6000. logger.warning(
  6001. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6002. printer_id,
  6003. archive_id,
  6004. subtask_name,
  6005. )
  6006. return None
  6007. client = printer_manager.get_client(printer_id)
  6008. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6009. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6010. logger.warning(
  6011. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6012. "— refusing to move the plate on a height that may not be this print's",
  6013. printer_id,
  6014. archive.id,
  6015. archive.total_layers,
  6016. reported_layers,
  6017. )
  6018. return None
  6019. # Stored relative to the data directory, like every other archive path
  6020. # (#3240: this read a `data_dir` setting that does not exist).
  6021. path = app_settings.base_dir / archive.file_path
  6022. plate = plate_id or archive.plate_id or 1
  6023. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6024. except Exception as e:
  6025. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6026. return None
  6027. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6028. """Raise the plate back into camera framing before the finish photo (#2547).
  6029. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6030. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6031. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6032. This commands an absolute ``G1 Z`` back to just above the last printed
  6033. layer.
  6034. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6035. clearance`` is a height the toolhead was physically at seconds earlier, so
  6036. it is inside the travel limits by construction and leaves the nozzle above
  6037. the part. It is also unambiguous across model families: Z is the
  6038. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6039. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6040. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6041. (#2579).
  6042. Returns True if the move was sent and waited out, False if it was skipped.
  6043. """
  6044. client = printer_manager.get_client(printer_id)
  6045. if client is None:
  6046. return False
  6047. # Re-read state immediately before commanding motion. If the queue has
  6048. # already started the next print, the printer is no longer ours to move.
  6049. state = getattr(client, "state", None)
  6050. if state is None or state.state != "FINISH":
  6051. logger.info(
  6052. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6053. printer_id,
  6054. getattr(state, "state", "unknown"),
  6055. )
  6056. return False
  6057. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6058. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6059. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6060. return False
  6061. logger.info(
  6062. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6063. printer_id,
  6064. target_z,
  6065. max_z_height,
  6066. _PLATE_RESTORE_CLEARANCE_MM,
  6067. _PLATE_RESTORE_SETTLE_SECONDS,
  6068. )
  6069. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6070. return True
  6071. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6072. """Drop the plate again after the finish photo (#2547).
  6073. Without this the user walks up to a finished print sitting just under the
  6074. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6075. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6076. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6077. print homes anyway.
  6078. """
  6079. client = printer_manager.get_client(printer_id)
  6080. state = getattr(client, "state", None) if client else None
  6081. if client is None or state is None or state.state != "FINISH":
  6082. return
  6083. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6084. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6085. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6086. """True if a queue item is about to take this printer (#2547).
  6087. The scheduler dispatches the next job the moment a print completes, and a
  6088. plate move interleaved with a print start is not a race worth having. The
  6089. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6090. this window; this closes the head of it.
  6091. """
  6092. try:
  6093. from backend.app.models.print_queue import PrintQueueItem
  6094. async with async_session() as db:
  6095. result = await db.execute(
  6096. select(PrintQueueItem.id)
  6097. .where(
  6098. PrintQueueItem.printer_id == printer_id,
  6099. PrintQueueItem.status.in_(("pending", "printing")),
  6100. )
  6101. .limit(1)
  6102. )
  6103. return result.scalar_one_or_none() is not None
  6104. except Exception as e:
  6105. # Fail closed: if we can't tell, don't move the plate.
  6106. logging.getLogger(__name__).debug(
  6107. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6108. )
  6109. return True
  6110. async def on_finish_photo_moment(printer_id: int, data: dict):
  6111. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6112. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6113. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6114. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6115. HMS halt, firmware variants). Grabs one frame via the same
  6116. external-camera / RTSP path the post-completion fallback uses, stores
  6117. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6118. ``_background_finish_photo`` consume the cached bytes when it runs.
  6119. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6120. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6121. set to Smooth (#1721). No force-on now means the user's explicit
  6122. timelapse=off in the slicer send dialog is respected.
  6123. """
  6124. logger = logging.getLogger(__name__)
  6125. trigger = data.get("trigger", "unknown")
  6126. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6127. logger.info(
  6128. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6129. printer_id,
  6130. trigger,
  6131. timelapse_was_active,
  6132. )
  6133. # If a timelapse is actively recording, skip the pre-capture — the
  6134. # post-completion path will extract the last frame from the recorded
  6135. # video, which still provides the best framing (toolhead parked,
  6136. # before bed drop) without the per-layer parking side effects.
  6137. if timelapse_was_active:
  6138. logger.info(
  6139. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6140. printer_id,
  6141. )
  6142. return
  6143. # #1790: register the producer-done event BEFORE the first await so the
  6144. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6145. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6146. # The `finally` below guarantees `set()` runs on every exit, including
  6147. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6148. producer_done = asyncio.Event()
  6149. _stage22_finish_in_flight[printer_id] = producer_done
  6150. # #3240: also before the first await. On the FINISH-state path
  6151. # `on_print_complete` is dispatched right behind us and pops both the
  6152. # print's archive binding and its plate; read here, they are still there.
  6153. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6154. # #2547: set once the plate has actually been raised, and read by the
  6155. # `finally` below. Declared out here so a failure anywhere after the move —
  6156. # a camera timeout, a DB error — still lowers the plate again.
  6157. restore_max_z: float | None = None
  6158. try:
  6159. async with async_session() as db:
  6160. from backend.app.api.routes.settings import get_setting
  6161. from backend.app.models.printer import Printer
  6162. capture_setting = await get_setting(db, "capture_finish_photo")
  6163. if capture_setting is not None and capture_setting.lower() != "true":
  6164. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6165. return
  6166. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6167. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6168. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6169. printer = result.scalar_one_or_none()
  6170. if printer is None:
  6171. logger.warning(
  6172. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6173. printer_id,
  6174. )
  6175. return
  6176. frame_bytes: bytes | None = None
  6177. # #2708: the banked frame arrives already rotated — it comes from
  6178. # `_capture_snapshot_for_notification`, which rotates before returning.
  6179. # Every other source below is a raw grab. Tracking which lets us store
  6180. # exactly one rotation in `_stage22_finish_frames` either way.
  6181. frame_already_rotated = False
  6182. # On the FINISH-state path the End G-code has already run, and two very
  6183. # different situations arrive here needing opposite answers.
  6184. #
  6185. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6186. # snippet may have ejected the plate — the scene in front of the camera
  6187. # is no longer the finished print, and no amount of moving the plate
  6188. # brings it back. Use the banked in-print frame instead.
  6189. #
  6190. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6191. # than the camera frames well, and the toolhead is parked out of the
  6192. # way. That is the *best* moment available on firmware that never emits
  6193. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6194. # back. Preferring the bank here unconditionally, as this code used to,
  6195. # is what shipped a mid-print photo with the toolhead over the part.
  6196. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6197. banked = _inprint_frame_bank.get(printer_id)
  6198. if banked:
  6199. frame_bytes = banked
  6200. frame_already_rotated = True
  6201. logger.info(
  6202. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6203. "frame (%d bytes) instead of a post-swap live grab",
  6204. len(banked),
  6205. )
  6206. else:
  6207. logger.warning(
  6208. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6209. "in-print bank is empty — falling back to a live grab, which may show a "
  6210. "swapped or empty plate",
  6211. printer_id,
  6212. )
  6213. # `restore_max_z` is set only once the plate is actually up, because the
  6214. # `finally` reads it to decide whether it owes a move back down.
  6215. #
  6216. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6217. # came up empty above: that machine may have just ejected its plate, and
  6218. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6219. # taking for a photo of a bed we already know may be bare.
  6220. if (
  6221. frame_bytes is None
  6222. and trigger == "finish_state"
  6223. and restore_plate_enabled
  6224. and not print_dispatch_context.end_gcode_injected(printer_id)
  6225. ):
  6226. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6227. if wants_restore is None:
  6228. logger.info(
  6229. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6230. printer_id,
  6231. )
  6232. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6233. logger.info(
  6234. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6235. printer_id,
  6236. )
  6237. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6238. restore_max_z = wants_restore
  6239. # Chamber light for the live capture below (#1655). The banked frame
  6240. # above was taken without it, like every in-print bank.
  6241. async with camera_light(printer if frame_bytes is None else None):
  6242. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6243. from backend.app.api.routes.camera import live_frame_for_capture
  6244. from backend.app.services.external_camera import capture_frame
  6245. # #2707: this used to collide with the live view and fail, which is
  6246. # how finish-photo notifications went out with no image attached.
  6247. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6248. defer, buffered = live_frame_for_capture(printer_id)
  6249. if defer:
  6250. frame_bytes = buffered
  6251. else:
  6252. frame_bytes = await capture_frame(
  6253. printer.external_camera_url,
  6254. printer.external_camera_type or "mjpeg",
  6255. snapshot_url=printer.external_camera_snapshot_url,
  6256. )
  6257. if frame_bytes:
  6258. logger.info(
  6259. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6260. len(frame_bytes),
  6261. )
  6262. elif frame_bytes is None:
  6263. from backend.app.api.routes.camera import get_buffered_frame
  6264. buffered = get_buffered_frame(printer_id)
  6265. if buffered:
  6266. frame_bytes = buffered
  6267. logger.info(
  6268. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6269. len(frame_bytes),
  6270. )
  6271. else:
  6272. from backend.app.services.camera import capture_camera_frame_bytes
  6273. frame_bytes = await capture_camera_frame_bytes(
  6274. ip_address=printer.ip_address,
  6275. access_code=printer.access_code,
  6276. model=printer.model,
  6277. timeout=15,
  6278. )
  6279. if frame_bytes:
  6280. logger.info(
  6281. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6282. len(frame_bytes),
  6283. )
  6284. if frame_bytes:
  6285. if not frame_already_rotated:
  6286. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6287. _stage22_finish_frames[printer_id] = frame_bytes
  6288. else:
  6289. logger.warning(
  6290. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6291. printer_id,
  6292. )
  6293. except Exception as e:
  6294. logger.warning(
  6295. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6296. printer_id,
  6297. e,
  6298. )
  6299. finally:
  6300. # #2547: we raised the plate, so we own lowering it — including when the
  6301. # capture above failed or threw partway through.
  6302. if restore_max_z is not None:
  6303. try:
  6304. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6305. except Exception as e:
  6306. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6307. # #1790: always unblock the consumer's bounded wait — whether we stored
  6308. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6309. # dict entry by the consumer doesn't affect signalling.
  6310. producer_done.set()
  6311. def _subtask_name_from_filename(filename: str) -> str:
  6312. """Recover the subtask name a print command would have carried for *filename*.
  6313. The dispatcher derives the printer-facing subtask name from the archive's
  6314. file name, so stripping the extensions back off gives the value MQTT echoes
  6315. on completion. Only the two extensions Bambuddy actually stores are removed,
  6316. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6317. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6318. """
  6319. name = PurePosixPath(filename).name
  6320. for suffix in (".3mf", ".gcode"):
  6321. if name.lower().endswith(suffix):
  6322. name = name[: -len(suffix)]
  6323. return name
  6324. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6325. """Whether the subtask name is the printed 3MF's own file name.
  6326. A print started from the printer's screen reports the same full name, with
  6327. its extension, as both subtask and file (#3009). A dispatched print reports
  6328. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6329. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6330. """
  6331. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6332. return False
  6333. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6334. # How the printer marks a subtask name it had to cut short. Observed on real
  6335. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6336. # (a name with multibyte characters came back at 98), so match the marker
  6337. # rather than a length.
  6338. _SUBTASK_TRUNCATION_MARKER = "..."
  6339. def _normalise_subtask_name(name: str) -> str:
  6340. """Canonical form for comparing a dispatched name against MQTT's echo.
  6341. The printer does not echo the name back verbatim: it substitutes
  6342. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6343. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6344. The 3MF lookup in this module has always known that -- it builds
  6345. space-to-underscore variants of every candidate filename, and its
  6346. directory search normalises both sides before comparing. This exists so
  6347. the completion check reads the same rule from the same place instead of
  6348. growing its own, which is exactly how it came to disagree (#2829).
  6349. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6350. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6351. are dropped after the substitution so both sides agree (#3241).
  6352. """
  6353. return name.strip().replace(" ", "_").strip("_").casefold()
  6354. def _subtask_names_match(expected: str, observed: str) -> bool:
  6355. """Whether two subtask names describe the same print.
  6356. Beyond the space/underscore substitution, the printer truncates long names
  6357. and marks the cut with ``...``. A truncated echo has to count as a match or
  6358. every print with a long name strands its queue item the same way.
  6359. """
  6360. expected_n = _normalise_subtask_name(expected)
  6361. observed_n = _normalise_subtask_name(observed)
  6362. if expected_n == observed_n:
  6363. return True
  6364. # Either side can be the truncated one: the printer truncates what it
  6365. # echoes, and an archive whose own filename was recorded from a previous
  6366. # truncated echo carries the marker too.
  6367. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6368. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6369. continue
  6370. # The full side has lost its edge underscores; a cut that lands right
  6371. # after one keeps it, so drop it here too (#3241). Nothing left before
  6372. # the marker is no evidence of anything, and must not match every name.
  6373. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6374. if kept and full.startswith(kept):
  6375. return True
  6376. return False
  6377. async def _queue_item_dispatched_name(db, item) -> str:
  6378. """The subtask name *item* was dispatched under, or "" when unknowable.
  6379. A row with no archive, or an archive with no file name, is unverifiable
  6380. rather than wrong; every caller answers that with its permissive branch.
  6381. """
  6382. if item.archive_id is None:
  6383. return ""
  6384. from backend.app.models.archive import PrintArchive
  6385. archive = await db.get(PrintArchive, item.archive_id)
  6386. if archive is None or not archive.filename:
  6387. return ""
  6388. return _subtask_name_from_filename(archive.filename)
  6389. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6390. """Whether this completion event is plausibly about *item*'s print.
  6391. The caller finds its queue row by printer and ``status='printing'`` alone,
  6392. which is all a completion event gives it -- there is no run identifier in
  6393. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6394. completion delivered for this printer closes whichever row happens to be
  6395. printing, however unrelated. Comparing the subtask name against the archive
  6396. the row was dispatched with costs one primary-key load and rules that out.
  6397. Deliberately permissive: it answers False only on a positive disagreement
  6398. between two names we actually have. A row with no archive, an archive with
  6399. no file name, or an event with no subtask name is unverifiable rather than
  6400. wrong, and refusing those would strand the item in ``printing`` and wedge
  6401. the printer's queue -- a worse failure than the one being prevented.
  6402. """
  6403. observed = (data.get("subtask_name") or "").strip()
  6404. if not observed or item.archive_id is None:
  6405. return True
  6406. from backend.app.models.archive import PrintArchive
  6407. archive = await db.get(PrintArchive, item.archive_id)
  6408. if archive is None or not archive.filename:
  6409. return True
  6410. expected = _subtask_name_from_filename(archive.filename)
  6411. if not expected or _subtask_names_match(expected, observed):
  6412. return True
  6413. logging.getLogger(__name__).warning(
  6414. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6415. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6416. "printing rather than closing a run this event is not about.",
  6417. item.id,
  6418. expected,
  6419. archive.id,
  6420. archive.filename,
  6421. observed,
  6422. )
  6423. return False
  6424. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6425. """Spend the 3MF download cache on a still-empty fallback archive.
  6426. ``on_print_complete`` drops the cache as its first act, which deletes the
  6427. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6428. print ran and the archive never got one, this is the last moment those bytes
  6429. exist (#2957).
  6430. """
  6431. logger = logging.getLogger(__name__)
  6432. names = [
  6433. n
  6434. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6435. if n
  6436. ]
  6437. for name in names:
  6438. try:
  6439. cached = get_cached_3mf(printer_id, name)
  6440. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6441. return
  6442. except Exception as e:
  6443. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6444. async def _cleanup_sd_card_after_print(
  6445. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6446. ) -> None:
  6447. """Delete a finished print's file from the printer's SD card."""
  6448. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6449. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6450. # auto-start files found in root on power cycle, causing ghost prints.
  6451. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6452. try:
  6453. if subtask_name:
  6454. archive_filename: str | None = None
  6455. async with async_session() as db:
  6456. from backend.app.models.archive import PrintArchive
  6457. from backend.app.models.printer import Printer
  6458. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6459. printer = result.scalar_one_or_none()
  6460. if archive_id:
  6461. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6462. archive_filename = archive_row.scalar_one_or_none()
  6463. if printer:
  6464. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6465. from backend.app.utils.filename import derive_remote_filename
  6466. # Primary candidate: the exact path the dispatcher uploaded to
  6467. # (derived from archive.filename via the same rule as upload).
  6468. # Without it, a library row that ended up with a doubled
  6469. # .gcode.3mf (#1542) leaves the real file behind because the
  6470. # subtask_name + ext fallbacks below don't match what's on the
  6471. # SD card. Fallbacks remain for archive-less prints (subtask
  6472. # never resolved to an archive) and for older naming variants.
  6473. candidate_paths: list[str] = []
  6474. if archive_filename:
  6475. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6476. for ext in (".3mf", ".gcode"):
  6477. fallback = f"/{subtask_name}{ext}"
  6478. if fallback not in candidate_paths:
  6479. candidate_paths.append(fallback)
  6480. # Three outcomes track across all candidates so the final log
  6481. # line reflects what actually happened. The A1 in #1721 always
  6482. # ends here with ``any_not_found=True`` and the others False
  6483. # — its firmware auto-cleans the SD card before our cleanup
  6484. # runs, every candidate FTP-DELE returns 550, and the old
  6485. # code burned 3 retries × 2 s × 3 candidates per print
  6486. # logging a misleading "may linger" WARNING on a successful
  6487. # print.
  6488. any_deleted = False
  6489. any_real_failure = False
  6490. any_not_found = False
  6491. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6492. for remote_path in candidate_paths:
  6493. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6494. logger.info(
  6495. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6496. remote_path,
  6497. printer.name,
  6498. )
  6499. continue
  6500. # Retry only the FAILED case — 550 NOT_FOUND will never
  6501. # recover by waiting, so a "file isn't here" answer
  6502. # advances immediately to the next candidate without
  6503. # consuming the retry budget.
  6504. for attempt in range(1, 4):
  6505. try:
  6506. delete_result = await delete_file_async(
  6507. printer.ip_address,
  6508. printer.access_code,
  6509. remote_path,
  6510. printer_model=printer.model,
  6511. )
  6512. except Exception as e:
  6513. delete_result = DeleteResult.FAILED
  6514. logger.warning(
  6515. "SD card cleanup attempt %d/3 raised for %s: %s",
  6516. attempt,
  6517. remote_path,
  6518. e,
  6519. )
  6520. if delete_result == DeleteResult.DELETED:
  6521. any_deleted = True
  6522. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6523. break
  6524. if delete_result == DeleteResult.NOT_FOUND:
  6525. any_not_found = True
  6526. break # 550 will not recover; try next candidate
  6527. # FAILED: real error — retry with backoff, then give up
  6528. if attempt < 3:
  6529. await asyncio.sleep(2)
  6530. else:
  6531. any_real_failure = True
  6532. logger.warning(
  6533. "SD card cleanup failed after 3 attempts for %s "
  6534. "(network/auth/transient error — file may linger on SD card)",
  6535. remote_path,
  6536. )
  6537. if not any_deleted and not any_real_failure and any_not_found:
  6538. # Every candidate said "not here." Either the printer
  6539. # firmware swept the SD card itself (common on A1) or the
  6540. # dispatcher's upload path doesn't match our candidate
  6541. # rule. Either way: nothing to clean up, no warning.
  6542. logger.debug(
  6543. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6544. "(printer likely self-cleaned)",
  6545. printer.name,
  6546. )
  6547. except Exception as e:
  6548. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6549. async def on_print_complete(printer_id: int, data: dict):
  6550. """Handle print completion - update the archive status."""
  6551. import time
  6552. logger = logging.getLogger(__name__)
  6553. start_time = time.time()
  6554. def log_timing(section: str):
  6555. elapsed = time.time() - start_time
  6556. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6557. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6558. # A kill-switch stop sends its provider notification immediately. Keep the
  6559. # task so the later notification path can await it and avoid a duplicate;
  6560. # if that immediate attempt failed, the regular completion path retries.
  6561. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6562. # Last chance before the bytes go: if this print's archive is still an empty
  6563. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6564. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6565. # below deletes the file (#2957).
  6566. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6567. # A pending cool-off retry has nothing left to recover for — the cache is
  6568. # about to be dropped and the print is over.
  6569. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6570. if retry_task and not retry_task.done():
  6571. retry_task.cancel()
  6572. # Drop the 3MF download cache for this printer (#972). The print is over,
  6573. # nothing else legitimately needs the bytes; keeping them would only risk
  6574. # handing a stale file to the next print if it reuses the same name.
  6575. clear_3mf_cache(printer_id)
  6576. try:
  6577. ws_data = {
  6578. "status": data.get("status"),
  6579. "filename": data.get("filename"),
  6580. "subtask_name": data.get("subtask_name"),
  6581. "timelapse_was_active": data.get("timelapse_was_active"),
  6582. }
  6583. await ws_manager.send_print_complete(printer_id, ws_data)
  6584. log_timing("WebSocket send_print_complete")
  6585. except Exception as e:
  6586. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6587. # Capture user info before clearing (needed for print log entry)
  6588. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6589. # Clear current print user tracking (Issue #206)
  6590. printer_manager.clear_current_print_user(printer_id)
  6591. # If the user explicitly stopped this print from the queue UI the printer will
  6592. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6593. # correct "print stopped" notification/email is sent instead of a failure alert.
  6594. _raw_status = data.get("status", "completed")
  6595. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6596. logger.info(
  6597. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6598. _raw_status,
  6599. printer_id,
  6600. )
  6601. data = {**data, "status": "cancelled"}
  6602. _user_stopped_printers.discard(printer_id)
  6603. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6604. # may have left material on the bed: a user can cancel ten hours into a
  6605. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6606. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6607. # `_user_stopped_printers` is only populated when the user stops via the
  6608. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6609. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6610. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6611. # Auto Off power cycles and Bambuddy restarts.
  6612. _final_status = data.get("status", "completed")
  6613. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6614. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6615. # MQTT relay - publish print complete
  6616. try:
  6617. printer_info = printer_manager.get_printer(printer_id)
  6618. if printer_info:
  6619. await mqtt_relay.on_print_complete(
  6620. printer_id,
  6621. printer_info.name,
  6622. printer_info.serial_number,
  6623. data.get("filename", ""),
  6624. data.get("subtask_name", ""),
  6625. data.get("status", "completed"),
  6626. )
  6627. except Exception:
  6628. pass # Don't fail print complete callback if MQTT fails
  6629. filename = data.get("filename", "")
  6630. subtask_name = data.get("subtask_name", "")
  6631. if not filename and not subtask_name:
  6632. logger.warning("Print complete without filename or subtask_name")
  6633. return
  6634. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6635. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6636. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6637. # Find the archive for this print
  6638. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6639. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6640. archive_id = None
  6641. for key in possible_keys:
  6642. archive_id = _active_prints.pop(key, None)
  6643. if archive_id:
  6644. logger.info("Found archive %s with key %s", archive_id, key)
  6645. # Also clean up any other keys pointing to this archive
  6646. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6647. for k in keys_to_remove:
  6648. _active_prints.pop(k, None)
  6649. break
  6650. # The archive bound when the print started, before the name search below.
  6651. # Only this one may give the finish-photo plate restore a height (#3240):
  6652. # the search matches names by substring.
  6653. bound_archive_id = archive_id
  6654. if not archive_id:
  6655. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6656. async with async_session() as db:
  6657. from backend.app.models.archive import PrintArchive
  6658. # Try matching by subtask_name (stored as print_name) first
  6659. if subtask_name:
  6660. result = await db.execute(
  6661. select(PrintArchive)
  6662. .where(PrintArchive.printer_id == printer_id)
  6663. .where(PrintArchive.status == "printing")
  6664. .where(
  6665. or_(
  6666. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6667. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6668. )
  6669. )
  6670. .order_by(PrintArchive.created_at.desc())
  6671. .limit(1)
  6672. )
  6673. archive = result.scalar_one_or_none()
  6674. if archive:
  6675. archive_id = archive.id
  6676. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6677. # Also try by filename
  6678. if not archive_id and filename:
  6679. result = await db.execute(
  6680. select(PrintArchive)
  6681. .where(PrintArchive.printer_id == printer_id)
  6682. .where(PrintArchive.filename == filename)
  6683. .where(PrintArchive.status == "printing")
  6684. .order_by(PrintArchive.created_at.desc())
  6685. .limit(1)
  6686. )
  6687. archive = result.scalar_one_or_none()
  6688. if archive:
  6689. archive_id = archive.id
  6690. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  6691. log_timing("SD card cleanup")
  6692. # Update queue item status early — must run before the archive_id early-return
  6693. # so queue items don't get stuck in "printing" when archive lookup fails.
  6694. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6695. queue_item_id = None
  6696. billing_run_id: str | None = None
  6697. billing_user_id: int | None = None
  6698. billing_cost_center_id: int | None = None
  6699. billing_plate_id: int | None = None
  6700. queue_status = None
  6701. queue_auto_off = False
  6702. try:
  6703. from backend.app.core.database import run_with_retry
  6704. from backend.app.models.print_queue import PrintQueueItem
  6705. async def _update_queue_status(db):
  6706. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6707. nonlocal queue_item_id, queue_status, queue_auto_off
  6708. result = await db.execute(
  6709. select(PrintQueueItem)
  6710. .where(PrintQueueItem.printer_id == printer_id)
  6711. .where(PrintQueueItem.status == "printing")
  6712. )
  6713. printing_items = list(result.scalars().all())
  6714. if len(printing_items) > 1:
  6715. logger.warning(
  6716. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6717. printer_id,
  6718. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6719. )
  6720. item = printing_items[0] if printing_items else None
  6721. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6722. return
  6723. if item:
  6724. queue_status = data.get("status", "completed")
  6725. # MQTT sends "aborted" for cancelled prints; normalise to
  6726. # "cancelled" so it matches the queue schema Literal.
  6727. if queue_status == "aborted":
  6728. queue_status = "cancelled"
  6729. item.status = queue_status
  6730. item.completed_at = datetime.now(timezone.utc)
  6731. if queue_status == "failed" and not item.error_message:
  6732. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6733. # Bump usage counters on the source library file so admins can
  6734. # sort by "last printed" and (eventually) auto-purge stale
  6735. # files — #1008.
  6736. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6737. await db.commit()
  6738. queue_item_id = item.id
  6739. billing_run_id = item.billing_run_id
  6740. billing_user_id = item.created_by_id
  6741. billing_cost_center_id = item.cost_center_id
  6742. billing_plate_id = item.plate_id
  6743. queue_auto_off = item.auto_off_after
  6744. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6745. await run_with_retry(_update_queue_status, label="queue status update")
  6746. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6747. # their own sessions and have their own error handling — no retry needed.
  6748. if queue_item_id is not None:
  6749. # Batch orders (#342): this run may have been the last one an order
  6750. # owed. Re-evaluate here rather than lazily on read, so a finished
  6751. # order reports itself complete without someone opening the page.
  6752. try:
  6753. from backend.app.services.print_batch import refresh_batch_status_for_item
  6754. async with async_session() as db:
  6755. await refresh_batch_status_for_item(db, queue_item_id)
  6756. await db.commit()
  6757. except Exception as e:
  6758. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6759. # MQTT relay - publish queue job completed
  6760. try:
  6761. printer_info = printer_manager.get_printer(printer_id)
  6762. await mqtt_relay.on_queue_job_completed(
  6763. job_id=queue_item_id,
  6764. filename=filename or subtask_name,
  6765. printer_id=printer_id,
  6766. printer_name=printer_info.name if printer_info else "Unknown",
  6767. status=queue_status,
  6768. )
  6769. except Exception:
  6770. pass # Don't fail if MQTT fails
  6771. # Check if queue is now empty and send notification
  6772. try:
  6773. from sqlalchemy import func as sa_func
  6774. async with async_session() as db:
  6775. count_result = await db.execute(
  6776. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6777. )
  6778. pending_count = count_result.scalar() or 0
  6779. if pending_count == 0:
  6780. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6781. completed_result = await db.execute(
  6782. select(sa_func.count(PrintQueueItem.id)).where(
  6783. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6784. PrintQueueItem.completed_at >= today_start,
  6785. )
  6786. )
  6787. completed_count = completed_result.scalar() or 1
  6788. await notification_service.on_queue_completed(
  6789. completed_count=completed_count,
  6790. db=db,
  6791. )
  6792. except Exception:
  6793. pass # Don't fail if notification fails
  6794. # Handle auto_off_after - power off printer if the queue item opted
  6795. # in. Delegates to the smart-plug manager so the off honours each
  6796. # plug's configured strategy (time delay or temperature threshold),
  6797. # is cancelled if the printer starts printing again, and never cuts
  6798. # power on a loaded print (#1890). Previously an inline block here
  6799. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6800. # timeout regardless of print state — cutting a touchscreen reprint.
  6801. if queue_auto_off:
  6802. try:
  6803. async with async_session() as db:
  6804. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6805. except Exception as e:
  6806. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6807. except Exception as e:
  6808. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6809. log_timing("Queue item update")
  6810. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6811. # Must run before archive_id early-return so it fires for all prints (including
  6812. # prints started from BambuStudio/touchscreen that have no archive).
  6813. if data.get("status") == "completed":
  6814. try:
  6815. from backend.app.api.routes.settings import get_setting
  6816. async with async_session() as db:
  6817. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6818. threshold = float(threshold_str) if threshold_str else 35.0
  6819. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6820. async with async_session() as db:
  6821. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6822. if providers:
  6823. _bed_cool_waiters[printer_id] = {
  6824. "threshold": threshold,
  6825. "filename": filename or subtask_name or "",
  6826. "registered_at": time.time(),
  6827. }
  6828. logger.info(
  6829. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6830. printer_id,
  6831. threshold,
  6832. )
  6833. else:
  6834. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6835. except Exception as e:
  6836. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6837. # Capture the slicer estimate before usage tracking runs. The tracker may
  6838. # update archive.cost with this run's measured cost; billing partial runs
  6839. # against that already-partial value would discount the charge twice.
  6840. billing_planned_grams: float | None = None
  6841. billing_base_cost: float | None = None
  6842. if archive_id:
  6843. try:
  6844. async with async_session() as db:
  6845. from backend.app.models.archive import PrintArchive
  6846. billing_archive = await db.get(PrintArchive, archive_id)
  6847. if billing_archive:
  6848. billing_path = (
  6849. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6850. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6851. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6852. billing_archive,
  6853. billing_path,
  6854. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6855. )
  6856. except Exception as e:
  6857. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6858. # --- Track filament consumption (must run before archive_id early-return so usage
  6859. # is recorded even when auto-archive is disabled) ---
  6860. usage_results: list[dict] = []
  6861. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6862. stored_ams_mapping = data.get("ams_mapping")
  6863. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6864. if not stored_ams_mapping and archive_id:
  6865. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6866. # Always drain the plate_id register on completion — the session already
  6867. # consumed it at print-start injection; leaving it would leak into the next
  6868. # print on the same archive_id (rare but possible with reprints) (#1697).
  6869. # Capture the popped value so the completion notification can scope the
  6870. # archive-level (summed-across-plates per #1593) filament + time totals
  6871. # down to the single plate that was actually printed (#1785).
  6872. notify_plate_id: int | None = None
  6873. if archive_id:
  6874. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6875. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6876. try:
  6877. async with async_session() as db:
  6878. from backend.app.api.routes.settings import get_setting
  6879. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6880. if not _spoolman_on or _spoolman_on.lower() != "true":
  6881. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6882. async with async_session() as db:
  6883. usage_results = await usage_on_print_complete(
  6884. printer_id,
  6885. data,
  6886. printer_manager,
  6887. db,
  6888. archive_id=archive_id,
  6889. ams_mapping=stored_ams_mapping,
  6890. )
  6891. if usage_results:
  6892. await ws_manager.broadcast(
  6893. {
  6894. "type": "spool_usage_logged",
  6895. "printer_id": printer_id,
  6896. "usage": usage_results,
  6897. }
  6898. )
  6899. log_timing("Usage tracker")
  6900. except Exception as e:
  6901. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6902. # Drop the print-start context unconditionally — the Spoolman branch above
  6903. # skips the internal tracker entirely, so nothing else would clear what
  6904. # print start captured, and a row surviving its print would be restored
  6905. # onto the next one after a restart.
  6906. try:
  6907. from backend.app.services.usage_tracker import discard_session
  6908. async with async_session() as db:
  6909. await discard_session(db, printer_id)
  6910. except Exception as e:
  6911. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6912. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6913. if archive_id:
  6914. if data.get("status") == "completed":
  6915. try:
  6916. await _report_spoolman_usage(printer_id, archive_id)
  6917. log_timing("Spoolman usage report")
  6918. except Exception as e:
  6919. logger.warning("Spoolman usage reporting failed: %s", e)
  6920. else:
  6921. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6922. try:
  6923. async with async_session() as db:
  6924. await _cleanup_spoolman_tracking(
  6925. printer_id,
  6926. archive_id,
  6927. db,
  6928. last_layer_num=data.get("last_layer_num"),
  6929. last_progress=data.get("last_progress"),
  6930. )
  6931. except Exception as e:
  6932. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6933. log_timing("Filament usage tracking")
  6934. if not archive_id:
  6935. # The printer's own calibration run has no archive by design, so this
  6936. # arrives here every time one finishes. Returning before the no-archive
  6937. # notification is not just noise control: that path attributes an
  6938. # unmatched completion to any queue item this printer finished in the
  6939. # last five minutes, which for a calibration that runs alongside a real
  6940. # print means emailing its owner that their print is done, twice and
  6941. # early. Everything above this point has already run — the plate-clear
  6942. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6943. # notification is skipped.
  6944. if is_internal_printer_job(filename, subtask_name):
  6945. logger.info(
  6946. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6947. filename,
  6948. subtask_name,
  6949. )
  6950. return
  6951. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6952. # Still send print-complete/failed/stopped notifications even without an archive.
  6953. # Try to enrich with queue/library-file data so user-specific emails work too.
  6954. async def _notify_no_archive():
  6955. try:
  6956. async with async_session() as db:
  6957. from backend.app.models.library import LibraryFile
  6958. from backend.app.models.print_queue import PrintQueueItem
  6959. from backend.app.models.printer import Printer
  6960. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6961. printer_obj = result.scalar_one_or_none()
  6962. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  6963. # Try to find the most-recent queue item for this printer so we can
  6964. # recover created_by_id and estimated print time.
  6965. # NOTE: By the time this task runs the queue item status has already
  6966. # been updated to a terminal state (completed/failed/cancelled), so
  6967. # we look for recently-completed items (within the last 5 minutes).
  6968. no_archive_data: dict | None = None
  6969. try:
  6970. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  6971. q_result = await db.execute(
  6972. select(PrintQueueItem)
  6973. .where(PrintQueueItem.printer_id == printer_id)
  6974. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  6975. .where(PrintQueueItem.completed_at >= cutoff)
  6976. .order_by(PrintQueueItem.completed_at.desc())
  6977. .limit(1)
  6978. )
  6979. queue_item = q_result.scalar_one_or_none()
  6980. if queue_item:
  6981. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6982. # Pull estimated time from library file when available
  6983. if queue_item.library_file_id:
  6984. lib_result = await db.execute(
  6985. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6986. )
  6987. lib_file = lib_result.scalar_one_or_none()
  6988. if lib_file and lib_file.print_time_seconds:
  6989. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6990. except Exception as lookup_err:
  6991. logger.debug(
  6992. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6993. )
  6994. # Enrich with usage tracker results (captured in enclosing scope)
  6995. if usage_results:
  6996. if no_archive_data is None:
  6997. no_archive_data = {}
  6998. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6999. if total_from_usage > 0:
  7000. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7001. no_archive_data["usage_results"] = usage_results
  7002. # Try MQTT remaining_time for print duration when no queue/library data
  7003. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7004. mqtt_remaining = data.get("remaining_time")
  7005. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7006. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7007. ps = data.get("status", "completed")
  7008. logger.info(
  7009. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7010. )
  7011. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7012. await notification_service.on_print_complete(
  7013. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7014. )
  7015. else:
  7016. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7017. # Send user-specific email if we have a created_by_id
  7018. if no_archive_data and no_archive_data.get("created_by_id"):
  7019. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7020. await _dispatch_user_print_email(
  7021. ps,
  7022. no_archive_data["created_by_id"],
  7023. p_name,
  7024. raw_filename,
  7025. db,
  7026. )
  7027. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7028. except Exception as e:
  7029. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7030. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7031. return
  7032. log_timing("Archive lookup")
  7033. # Update archive status
  7034. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7035. try:
  7036. async with async_session() as db:
  7037. service = ArchiveService(db)
  7038. status = data.get("status", "completed")
  7039. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7040. if hms_errors:
  7041. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7042. failure_reason = derive_failure_reason(status, hms_errors)
  7043. if data.get("_reconciled"):
  7044. # A reconciled completion closes out a stale archive at
  7045. # reconnect — it is not a user action, so don't mislabel it
  7046. # "userCancelled". It shares the stale-cleanup path's key
  7047. # (issue #2974) and records that the real end time is unknown,
  7048. # which is also why its logged duration is 0 (#2592).
  7049. failure_reason = "noStatusUpdate"
  7050. if failure_reason:
  7051. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7052. elif status == "failed" and hms_errors:
  7053. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7054. await service.update_archive_status(
  7055. archive_id,
  7056. status=status,
  7057. completed_at=(
  7058. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7059. ),
  7060. failure_reason=failure_reason,
  7061. )
  7062. logger.info(
  7063. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7064. )
  7065. await ws_manager.send_archive_updated(
  7066. {
  7067. "id": archive_id,
  7068. "status": status,
  7069. }
  7070. )
  7071. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7072. # MQTT relay - publish archive updated
  7073. try:
  7074. await mqtt_relay.on_archive_updated(
  7075. archive_id=archive_id,
  7076. print_name=filename or subtask_name,
  7077. status=status,
  7078. )
  7079. except Exception:
  7080. pass # Don't fail if MQTT fails
  7081. except Exception as e:
  7082. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7083. # Continue with other operations even if archive update fails
  7084. log_timing("Archive status update")
  7085. # Apply finance wallet charge or release reservations once. For all partial
  7086. # terminal states (failed, aborted at the printer display, or cancelled via
  7087. # Bambuddy) use this run's measured spool delta, falling back to the last
  7088. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7089. # estimate and therefore cannot represent an interrupted run.
  7090. try:
  7091. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7092. async with async_session() as db:
  7093. from backend.app.models.archive import PrintArchive
  7094. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7095. archive = await db.get(PrintArchive, archive_id)
  7096. if archive and billing_run_id is None:
  7097. billing_run_id = getattr(archive, "billing_run_id", None)
  7098. if archive and archive.created_by_id is None and _print_user_info:
  7099. archive.created_by_id = _print_user_info.get("user_id")
  7100. await db.flush()
  7101. run_status = data.get("status", "completed")
  7102. last_progress = data.get("last_progress")
  7103. if last_progress is None:
  7104. last_progress = data.get("progress")
  7105. actual_run_grams = _compute_run_filament_grams(
  7106. run_status,
  7107. billing_planned_grams,
  7108. last_progress,
  7109. usage_results,
  7110. )
  7111. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7112. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7113. charged = await apply_print_charge_for_archive(
  7114. db,
  7115. archive_id,
  7116. charged_user_id=billing_user_id,
  7117. cost_center_id=(
  7118. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7119. ),
  7120. print_queue_id=queue_item_id,
  7121. print_run_id=billing_run_id,
  7122. base_cost_override=billing_base_cost,
  7123. filament_usage=filament_usage,
  7124. )
  7125. await db.commit()
  7126. if charged:
  7127. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7128. except Exception as e:
  7129. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7130. printer_info = printer_manager.get_printer(printer_id)
  7131. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7132. billing_filename = filename or subtask_name or "Unknown"
  7133. billing_error = str(e)
  7134. try:
  7135. await ws_manager.broadcast(
  7136. {
  7137. "type": "billing_charge_failed",
  7138. "printer_id": printer_id,
  7139. "printer_name": billing_printer_name,
  7140. "filename": billing_filename,
  7141. "archive_id": archive_id,
  7142. }
  7143. )
  7144. except Exception as notification_error:
  7145. logger.error(
  7146. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7147. archive_id,
  7148. notification_error,
  7149. )
  7150. async def _notify_billing_charge_failed() -> None:
  7151. try:
  7152. async with async_session() as notification_db:
  7153. await notification_service.on_billing_charge_failed(
  7154. printer_id,
  7155. billing_printer_name,
  7156. billing_filename,
  7157. archive_id,
  7158. billing_error,
  7159. notification_db,
  7160. )
  7161. except Exception as provider_error:
  7162. logger.error(
  7163. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7164. archive_id,
  7165. provider_error,
  7166. exc_info=True,
  7167. )
  7168. spawn_background_task(
  7169. _notify_billing_charge_failed(),
  7170. name=f"billing-charge-failed-{archive_id}",
  7171. )
  7172. log_timing("Finance charge update")
  7173. # Write independent print log entry (separate table, never touches archives)
  7174. try:
  7175. async with async_session() as db:
  7176. from backend.app.models.archive import PrintArchive
  7177. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7178. archive = await db.get(PrintArchive, archive_id)
  7179. if archive:
  7180. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7181. # source archive row rather than creating a new one, so an
  7182. # archive that was auto-created from a printer-initiated
  7183. # print (created_by_id=NULL) would otherwise stay unattributed
  7184. # forever. When we have a print-session user AND the archive
  7185. # has no attribution yet, credit the current user. Never
  7186. # overwrite an existing attribution — the original uploader
  7187. # keeps ownership.
  7188. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  7189. if archive.created_by_id is None and _print_user_id is not None:
  7190. archive.created_by_id = _print_user_id
  7191. p_info = printer_manager.get_printer(printer_id)
  7192. # Per-run actuals — written to PrintLogEntry so stats reflect
  7193. # what THIS print actually used, not the source archive's
  7194. # first-run values (#1378). Helper handles the partial-print
  7195. # math (failed / cancelled / stopped get scaled to progress
  7196. # or to tracked spool deltas).
  7197. _run_status = data.get("status", "completed")
  7198. # #2614: scope the per-run estimate to the printed plate. For a
  7199. # multi-plate 3MF dispatched one plate at a time, the archive's
  7200. # filament/cost are the whole-file totals; the PrintLogEntry must
  7201. # reflect only this plate. No effect on single-plate archives (the
  7202. # plate estimate equals the whole-file value) or on the tracker
  7203. # path (measured spool deltas win in _compute_run_filament_grams).
  7204. _est_full_path = (
  7205. app_settings.base_dir / archive.file_path if archive.file_path else None
  7206. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7207. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  7208. _run_grams = _compute_run_filament_grams(
  7209. _run_status,
  7210. _est_grams,
  7211. data.get("last_progress", data.get("progress")),
  7212. usage_results,
  7213. )
  7214. # Per-run cost — prefer usage_results sum. For partial prints
  7215. # we deliberately skip the topup-to-estimate logic in
  7216. # usage_tracker (which assumes the print completed); the raw
  7217. # tracked-spool sum is closer to what THIS run actually cost.
  7218. _run_cost: float | None = None
  7219. if usage_results:
  7220. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7221. if _run_cost is None and _run_status == "completed":
  7222. _run_cost = _est_cost
  7223. from backend.app.models.printer import Printer as _Printer
  7224. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7225. run_entry = await write_log_entry(
  7226. db,
  7227. archive_id=archive.id,
  7228. # Captured by _update_queue_status above; None for
  7229. # printer-initiated prints with no queue row. Batch
  7230. # cost/energy roll-up joins on it (#342).
  7231. queue_item_id=queue_item_id,
  7232. status=_run_status,
  7233. print_name=archive.print_name,
  7234. printer_name=p_info.name if p_info else None,
  7235. printer_id=printer_id,
  7236. started_at=archive.started_at,
  7237. completed_at=archive.completed_at,
  7238. filament_type=archive.filament_type,
  7239. filament_color=archive.filament_color,
  7240. filament_used_grams=_run_grams,
  7241. cost=_run_cost,
  7242. wear_cost_per_hour=_wear_rate,
  7243. failure_reason=archive.failure_reason,
  7244. thumbnail_path=archive.thumbnail_path,
  7245. created_by_id=archive.created_by_id,
  7246. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7247. # Reconciled completions have an unknown real end time —
  7248. # log 0 duration instead of the whole disconnect gap (#2592).
  7249. reconciled=bool(data.get("_reconciled")),
  7250. )
  7251. await record_archive_wear(db, archive, run_entry)
  7252. await db.commit()
  7253. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7254. except Exception as e:
  7255. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7256. log_timing("Print log entry")
  7257. # Run slow operations as background tasks to avoid blocking the event loop
  7258. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7259. async def _background_energy_calculation():
  7260. """Calculate and save energy usage in background.
  7261. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7262. backend restart no longer loses per-print energy data).
  7263. """
  7264. try:
  7265. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7266. async with async_session() as db:
  7267. from backend.app.models.archive import PrintArchive
  7268. archive = await db.get(PrintArchive, archive_id)
  7269. if archive is None:
  7270. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7271. return
  7272. starting_kwh = archive.energy_start_kwh
  7273. if starting_kwh is None:
  7274. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7275. return
  7276. candidates = await energy_plug_candidates(db, printer_id)
  7277. if not candidates:
  7278. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7279. return
  7280. # Same ordering as the start reading, so the delta below is
  7281. # against the counter that produced `starting_kwh` (#2859).
  7282. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7283. if selected is None:
  7284. logger.warning(
  7285. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7286. printer_id,
  7287. ", ".join(plug.name for plug in candidates),
  7288. )
  7289. return
  7290. plug, energy = selected
  7291. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7292. energy_used = round(energy["total"] - starting_kwh, 4)
  7293. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7294. if energy_used < 0:
  7295. logger.warning(
  7296. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7297. archive_id,
  7298. starting_kwh,
  7299. energy["total"],
  7300. )
  7301. return
  7302. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7303. # Each hour of the print at the price of that hour (#1251). If
  7304. # that fails, the last price known, as before, rather than no
  7305. # energy at all. Read first: the session may be unusable after.
  7306. last_price = await stored_price(db)
  7307. try:
  7308. energy_cost_value = round(
  7309. await print_energy_cost(
  7310. db,
  7311. plug_id=archive.energy_start_plug_id,
  7312. start_at=archive.energy_start_at,
  7313. start_kwh=starting_kwh,
  7314. start_price=archive.energy_start_price,
  7315. end_kwh=energy["total"],
  7316. end_plug_id=plug.id,
  7317. price_now=await current_price(db),
  7318. ),
  7319. 3,
  7320. )
  7321. except Exception as e:
  7322. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7323. energy_cost_value = round(energy_used * last_price, 3)
  7324. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7325. # reprint doesn't visually clobber the source archive's energy data
  7326. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7327. from sqlalchemy import func
  7328. from backend.app.models.print_log import PrintLogEntry
  7329. existing_runs = await db.scalar(
  7330. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7331. )
  7332. if (existing_runs or 0) <= 1:
  7333. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7334. # we just wrote for THIS print. Either way it's the first run.
  7335. archive.energy_kwh = energy_used
  7336. archive.energy_cost = energy_cost_value
  7337. # Backfill the latest PrintLogEntry for this archive with energy
  7338. # (write_log_entry above ran before this background task completed,
  7339. # so energy fields are still NULL on that row).
  7340. latest_run = await db.execute(
  7341. select(PrintLogEntry)
  7342. .where(PrintLogEntry.archive_id == archive_id)
  7343. .order_by(PrintLogEntry.id.desc())
  7344. .limit(1)
  7345. )
  7346. run_row = latest_run.scalar_one_or_none()
  7347. if run_row is not None:
  7348. run_row.energy_kwh = energy_used
  7349. run_row.energy_cost = energy_cost_value
  7350. await db.commit()
  7351. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7352. except Exception as e:
  7353. logger.warning("[ENERGY-BG] Failed: %s", e)
  7354. async def _background_finish_photo() -> str | None:
  7355. """Capture finish photo in background. Returns photo filename if captured."""
  7356. # #2547: set once this function has raised the plate itself (the
  7357. # timelapse path, where the moment producer returned without doing it).
  7358. # Declared out here so the `finally` can lower it again no matter where
  7359. # the capture below fails.
  7360. plate_restored_z: float | None = None
  7361. try:
  7362. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7363. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7364. # Read phase: settings + printer + archive in a short session, released
  7365. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7366. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7367. # tens of seconds; holding this session across it pinned one pooled
  7368. # connection idle-in-transaction per finishing print (issue #2572).
  7369. async with async_session() as db:
  7370. from backend.app.api.routes.settings import get_setting
  7371. from backend.app.models.archive import PrintArchive
  7372. from backend.app.models.printer import Printer
  7373. capture_enabled = await get_setting(db, "capture_finish_photo")
  7374. if capture_enabled is not None and capture_enabled.lower() != "true":
  7375. return None
  7376. if not archive_id:
  7377. return None
  7378. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7379. archive = (
  7380. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7381. ).scalar_one_or_none()
  7382. if not printer or not archive:
  7383. return None
  7384. import uuid
  7385. from datetime import datetime
  7386. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7387. if not archive.file_path:
  7388. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7389. archive_dir = resolve_archive_dir(archive)
  7390. photo_filename = None
  7391. # Prefer the timelapse last-frame source when a timelapse was
  7392. # recording — it captures the moment after the toolhead parks
  7393. # but before the bed drops, which the live-camera grab below
  7394. # would miss (#1397). Skipped for external cameras (those have
  7395. # their own framing and don't see a Bambu timelapse). Only
  7396. # runs when the USER explicitly enabled timelapse for this
  7397. # print — #1721 removed Bambuddy's force-on at dispatch
  7398. # because it caused per-layer nozzle parking on Smooth-mode
  7399. # slicer profiles.
  7400. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7401. printer.external_camera_enabled and printer.external_camera_url
  7402. )
  7403. timelapse_still_pending = False
  7404. if prefer_timelapse_source:
  7405. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7406. archive_id=archive_id,
  7407. archive_dir=archive_dir,
  7408. rotation=getattr(printer, "camera_rotation", 0),
  7409. )
  7410. # #1721: replacement framing path — on_finish_photo_moment
  7411. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7412. # parked, bed not yet dropped) and cached the JPEG bytes in
  7413. # _stage22_finish_frames. Consume them now so the saved photo
  7414. # has the better framing instead of the post-bed-drop angle
  7415. # the live-camera fallback below would give.
  7416. if not photo_filename:
  7417. # #1790: on the FINISH-state fallback path the producer
  7418. # task is dispatched back-to-back with this consumer, so
  7419. # a bare pop would race past with an empty result and
  7420. # the RTSP fallback below would collide with the
  7421. # producer's still-in-flight grab (single-client RTSP
  7422. # on Bambu printers). Wait for the producer to finish
  7423. # or give up before touching the cache.
  7424. #
  7425. # #2547: 20s was enough when the producer only ever grabbed a
  7426. # frame. It now also raises the plate first, which costs the
  7427. # settle window before the grab even starts — so the budget has
  7428. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7429. # under the notification's own photo wait below.
  7430. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7431. if in_flight is not None:
  7432. try:
  7433. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7434. except asyncio.TimeoutError:
  7435. logger.warning(
  7436. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7437. printer_id,
  7438. )
  7439. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7440. if cached_frame:
  7441. # Already rotated by the producer (#2708) — rotating again
  7442. # here would undo the fix on the banked-frame path, whose
  7443. # bytes reach the cache having been rotated once already.
  7444. photos_dir = archive_dir / "photos"
  7445. photos_dir.mkdir(parents=True, exist_ok=True)
  7446. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7447. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7448. photo_path = photos_dir / photo_filename
  7449. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7450. logger.info(
  7451. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7452. photo_filename,
  7453. len(cached_frame),
  7454. )
  7455. # #2547: the timelapse path reaches the live grab below whenever the
  7456. # video hasn't landed in time — the documented usual outcome on
  7457. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7458. # returned early for those prints without raising the plate, so
  7459. # without this the photo that actually ships in the notification is
  7460. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7461. # asked us to fix. The archive still gets the better video frame
  7462. # later; this is about the image the user is sent.
  7463. #
  7464. # Gated on `timelapse_was_active` precisely because that is the
  7465. # condition under which the producer skipped. On every other path it
  7466. # has already raised and lowered the plate, and repeating that here
  7467. # would be a second pointless round trip.
  7468. if (
  7469. not photo_filename
  7470. and data.get("timelapse_was_active")
  7471. and not print_dispatch_context.end_gcode_injected(printer_id)
  7472. ):
  7473. try:
  7474. async with async_session() as db:
  7475. from backend.app.api.routes.settings import get_setting
  7476. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7477. if restore_setting is None or restore_setting.lower() == "true":
  7478. max_z = await _max_z_for_current_print(
  7479. printer_id, data, logger, bound_archive_id, notify_plate_id
  7480. )
  7481. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7482. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7483. plate_restored_z = max_z
  7484. except Exception as e:
  7485. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7486. # Fallback chain: external camera → buffered live frame →
  7487. # fresh RTSP capture. Only runs if the timelapse path above
  7488. # didn't already produce a photo.
  7489. # Chamber light for the live capture below (#1655).
  7490. async with camera_light(printer if not photo_filename else None):
  7491. if not photo_filename:
  7492. if printer.external_camera_enabled and printer.external_camera_url:
  7493. logger.info("[PHOTO-BG] Using external camera")
  7494. from backend.app.api.routes.camera import live_frame_for_capture
  7495. from backend.app.services.external_camera import capture_frame
  7496. # #2707: the second half of the finish-photo failure — the
  7497. # pre-capture and this fallback both collided with the live
  7498. # view. None here continues down the fallback chain.
  7499. defer, buffered = live_frame_for_capture(printer_id)
  7500. if defer:
  7501. frame_data = buffered
  7502. else:
  7503. frame_data = await capture_frame(
  7504. printer.external_camera_url,
  7505. printer.external_camera_type or "mjpeg",
  7506. snapshot_url=printer.external_camera_snapshot_url,
  7507. )
  7508. if frame_data:
  7509. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7510. photos_dir = archive_dir / "photos"
  7511. photos_dir.mkdir(parents=True, exist_ok=True)
  7512. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7513. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7514. photo_path = photos_dir / photo_filename
  7515. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7516. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7517. else:
  7518. # Check if camera stream is active - use buffered frame to avoid freeze
  7519. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7520. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7521. active_chamber_for_printer = [
  7522. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7523. ]
  7524. buffered_frame = get_buffered_frame(printer_id)
  7525. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7526. # Use frame from active stream
  7527. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7528. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7529. photos_dir = archive_dir / "photos"
  7530. photos_dir.mkdir(parents=True, exist_ok=True)
  7531. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7532. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7533. photo_path = photos_dir / photo_filename
  7534. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7535. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7536. else:
  7537. # No active stream - capture new frame
  7538. from backend.app.services.camera import capture_finish_photo
  7539. photo_filename = await capture_finish_photo(
  7540. printer_id=printer_id,
  7541. ip_address=printer.ip_address,
  7542. access_code=printer.access_code,
  7543. model=printer.model,
  7544. archive_dir=archive_dir,
  7545. rotation=getattr(printer, "camera_rotation", 0),
  7546. )
  7547. # Write phase: attach the photo in a fresh short-lived session.
  7548. if photo_filename:
  7549. async with async_session() as db:
  7550. from backend.app.models.archive import PrintArchive
  7551. arch = await db.get(PrintArchive, archive_id)
  7552. if arch is not None:
  7553. photos = arch.photos or []
  7554. photos.append(photo_filename)
  7555. arch.photos = photos
  7556. await db.commit()
  7557. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7558. # The short wait above is bounded so a slow printer can't hold up
  7559. # the print-complete notification, which is what the caller is
  7560. # blocking on. When it ran out with the video still on its way,
  7561. # keep waiting off to the side and add the better frame to the
  7562. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7563. # users, whose videos routinely take minutes to transfer, never get
  7564. # the pre-bed-drop framing this path exists to provide.
  7565. #
  7566. # Spawned here rather than at the point the wait gave up: both this
  7567. # function and the upgrade do a read-modify-write on `photos`, and
  7568. # the live-camera fallback above can take tens of seconds. Starting
  7569. # the upgrade before that write means the two can interleave and one
  7570. # silently drops the other's entry, leaving a JPEG on disk that the
  7571. # gallery never lists.
  7572. if timelapse_still_pending:
  7573. spawn_background_task(
  7574. _upgrade_finish_photo_from_timelapse(
  7575. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7576. ),
  7577. name=f"finish-photo-upgrade-{archive_id}",
  7578. )
  7579. return photo_filename
  7580. except Exception as e:
  7581. logger.warning("[PHOTO-BG] Failed: %s", e)
  7582. return None
  7583. finally:
  7584. # #2547: we raised the plate, so we owe the move back down — even if
  7585. # the capture in between threw. Otherwise the user finds the print
  7586. # pinned under the nozzle.
  7587. if plate_restored_z is not None:
  7588. try:
  7589. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7590. except Exception as e:
  7591. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7592. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7593. # Photo capture task - result will be used by notifications
  7594. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7595. log_timing("Background tasks scheduled (energy, photo)")
  7596. # Also run smart plug, notifications, and maintenance as background tasks
  7597. print_status = data.get("status", "completed")
  7598. async def _background_smart_plug():
  7599. """Handle smart plug automation in background."""
  7600. try:
  7601. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7602. async with async_session() as db:
  7603. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7604. logger.info("[AUTO-OFF-BG] Completed")
  7605. except Exception as e:
  7606. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7607. async def _background_notifications(finish_photo_filename: str | None = None):
  7608. """Send print complete notifications in background."""
  7609. try:
  7610. logger.info(
  7611. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7612. )
  7613. async with async_session() as db:
  7614. from backend.app.models.archive import PrintArchive
  7615. from backend.app.models.printer import Printer
  7616. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7617. printer = result.scalar_one_or_none()
  7618. printer_name = printer.name if printer else f"Printer {printer_id}"
  7619. archive_data = None
  7620. if archive_id:
  7621. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7622. archive = archive_result.scalar_one_or_none()
  7623. if archive:
  7624. # Actual elapsed time from started_at/completed_at when both are
  7625. # populated (every terminal status sets completed_at after #1198).
  7626. # Falls back to None so the notification path can decide whether to
  7627. # render the slicer estimate as a last resort.
  7628. actual_time_seconds = None
  7629. if archive.started_at and archive.completed_at:
  7630. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7631. if elapsed > 0:
  7632. actual_time_seconds = int(elapsed)
  7633. archive_data = {
  7634. "print_time_seconds": archive.print_time_seconds,
  7635. "actual_time_seconds": actual_time_seconds,
  7636. "actual_filament_grams": archive.filament_used_grams,
  7637. "failure_reason": archive.failure_reason,
  7638. "created_by_id": archive.created_by_id,
  7639. }
  7640. # Scale filament usage for partial prints
  7641. if print_status != "completed" and archive.filament_used_grams:
  7642. progress = data.get("progress") or 0
  7643. scale = _partial_progress_scale(progress)
  7644. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7645. archive_data["progress"] = progress
  7646. # Pass per-slot data from archive.extra_data
  7647. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7648. slots = archive.extra_data["filament_slots"]
  7649. if print_status != "completed":
  7650. scale = _partial_progress_scale(data.get("progress"))
  7651. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7652. archive_data["filament_slots"] = slots
  7653. # Scope project-summed totals down to the plate that was
  7654. # actually printed — see _scope_notification_archive_data_to_plate
  7655. # for the why (#1785).
  7656. archive_data = _scope_notification_archive_data_to_plate(
  7657. archive_data,
  7658. archive.file_path,
  7659. notify_plate_id,
  7660. print_status,
  7661. data.get("progress"),
  7662. app_settings.base_dir,
  7663. )
  7664. # Enrich filament_grams from usage_results when archive has no 3MF data
  7665. if not archive_data.get("actual_filament_grams") and usage_results:
  7666. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7667. if total_from_usage > 0:
  7668. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7669. # Pass usage tracker results for AMS slot info in notifications
  7670. if usage_results:
  7671. archive_data["usage_results"] = usage_results
  7672. # Add finish photo URL and image bytes if available
  7673. if finish_photo_filename:
  7674. photo_url, photo_bytes = await _finish_photo_for_notification(
  7675. db, archive, archive_id, finish_photo_filename
  7676. )
  7677. if photo_url:
  7678. archive_data["finish_photo_url"] = photo_url
  7679. if photo_bytes:
  7680. archive_data["image_data"] = photo_bytes
  7681. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7682. await notification_service.on_print_complete(
  7683. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7684. )
  7685. else:
  7686. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7687. # Post-print outcome confirmation (#1898). Runs in this
  7688. # background task so the finish photo fetched above rides
  7689. # along with the prompt.
  7690. if print_status == "completed" and archive_id:
  7691. await _dispatch_outcome_confirmation_safely(
  7692. db, printer_id, printer_name, data, archive_id, archive_data
  7693. )
  7694. # Send user-specific email notification
  7695. if archive_data:
  7696. created_by_id = archive_data.get("created_by_id")
  7697. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7698. await _dispatch_user_print_email(
  7699. print_status,
  7700. created_by_id,
  7701. printer_name,
  7702. raw_filename,
  7703. db,
  7704. image_data=archive_data.get("image_data"),
  7705. finish_photo_url=archive_data.get("finish_photo_url"),
  7706. )
  7707. logger.info("[NOTIFY-BG] Completed")
  7708. except Exception as e:
  7709. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7710. async def _background_maintenance_check():
  7711. """Check for maintenance due in background."""
  7712. if print_status != "completed":
  7713. return
  7714. try:
  7715. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7716. async with async_session() as db:
  7717. from backend.app.models.printer import Printer
  7718. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7719. printer = result.scalar_one_or_none()
  7720. printer_name = printer.name if printer else f"Printer {printer_id}"
  7721. await ensure_default_types(db)
  7722. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7723. items_needing_attention = [
  7724. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7725. for item in overview.maintenance_items
  7726. if item.enabled and (item.is_due or item.is_warning)
  7727. ]
  7728. if items_needing_attention:
  7729. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7730. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7731. # MQTT relay - publish maintenance alerts
  7732. for item in items_needing_attention:
  7733. try:
  7734. await mqtt_relay.on_maintenance_alert(
  7735. printer_id=printer_id,
  7736. printer_name=printer_name,
  7737. maintenance_type=item["name"],
  7738. current_value=0, # Not easily available here
  7739. threshold=0, # Not easily available here
  7740. )
  7741. except Exception:
  7742. pass # Don't fail if MQTT fails
  7743. else:
  7744. logger.info("[MAINT-BG] Completed (no items need attention)")
  7745. except Exception as e:
  7746. logger.warning("[MAINT-BG] Failed: %s", e)
  7747. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7748. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7749. # Notification task waits for photo capture to complete first (with timeout).
  7750. # When a timelapse was recording, photo sourcing polls the per-print
  7751. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7752. # carries the correct bed-up photo instead of falling through to the
  7753. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7754. #
  7755. # #2547: both budgets now have to cover a plate restore as well.
  7756. #
  7757. # Without timelapse, the wait is on the moment producer, which raises the
  7758. # plate before its grab — so this has to outlast that producer's own budget.
  7759. #
  7760. # With timelapse, the capture polls up to
  7761. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7762. # falls back to a live grab, which is the case that raises the plate. At the
  7763. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7764. # restore would have moved the plate for a photo nobody waited for.
  7765. photo_wait_timeout = (
  7766. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7767. if data.get("timelapse_was_active")
  7768. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7769. )
  7770. async def _photo_then_notify():
  7771. """Wait for photo capture, then send notification with photo URL."""
  7772. finish_photo = None
  7773. try:
  7774. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7775. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7776. except TimeoutError:
  7777. logger.warning(
  7778. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7779. photo_wait_timeout,
  7780. )
  7781. except Exception as e:
  7782. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7783. try:
  7784. await _background_notifications(finish_photo)
  7785. except Exception as e:
  7786. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7787. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7788. # Stitch external camera layer timelapse if session was active
  7789. print_status = data.get("status", "completed")
  7790. async def _background_layer_timelapse():
  7791. """Stitch layer timelapse and attach to archive."""
  7792. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7793. try:
  7794. if print_status == "completed":
  7795. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7796. timelapse_path = await tl_complete(printer_id)
  7797. if timelapse_path and archive_id:
  7798. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7799. async with async_session() as db:
  7800. service = ArchiveService(db)
  7801. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7802. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  7803. # Clean up the temp file
  7804. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7805. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7806. elif timelapse_path:
  7807. # Timelapse created but no archive - just clean up
  7808. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7809. else:
  7810. # Print failed or cancelled - cancel timelapse session
  7811. cancel_session(printer_id)
  7812. logger.info(
  7813. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7814. )
  7815. except Exception as e:
  7816. logger.warning("[LAYER-TL] Failed: %s", e)
  7817. # Try to cancel session on error
  7818. try:
  7819. cancel_session(printer_id)
  7820. except Exception:
  7821. pass # Best-effort timelapse session cancellation on error
  7822. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7823. log_timing("All background tasks scheduled")
  7824. # Auto-scan for timelapse if recording was active during the print
  7825. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7826. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7827. # Schedule timelapse scan as background task with retries
  7828. # The printer needs time to encode the video after print completion
  7829. baseline = _timelapse_baselines.pop(printer_id, None)
  7830. spawn_background_task(
  7831. _scan_for_timelapse_with_retries(archive_id, baseline),
  7832. name=f"scan-timelapse-{archive_id}",
  7833. )
  7834. log_timing("Timelapse scan scheduled")
  7835. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7836. # AMS sensor history recording
  7837. _ams_history_task: asyncio.Task | None = None
  7838. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7839. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7840. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7841. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7842. _ams_alarm_cooldown: dict[str, datetime] = {}
  7843. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7844. # (printer_id, ams_id) already reported as sending the drop index and no
  7845. # percentage. Logged once each so a supported printer that turns out to do this
  7846. # shows up in a support bundle rather than as a user wondering where the
  7847. # humidity reading went -- see the note at the read site below (#3140).
  7848. _ams_index_only_logged: set[tuple[int, int]] = set()
  7849. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7850. """Temperature at which the AMS alarm fires, falling back to the display band.
  7851. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7852. when a notification was sent as well, which is why a room above it made the
  7853. alarm fire once an hour for as long as the weather lasted -- and the only way
  7854. to stop that was to raise the display band and lose the colour that says the
  7855. unit is warm (#2905).
  7856. Unset resolves to the fair threshold, so an install that never sets one is
  7857. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7858. so that arrives here as a string and is handled by the same branch as any
  7859. other unparseable value -- there is no separate sentinel to keep in sync.
  7860. A non-positive value is refused rather than honoured: zero would alarm
  7861. permanently, and it is far more likely to be a cleared field than a
  7862. deliberate choice.
  7863. """
  7864. if raw_alarm_value is None:
  7865. return fair_threshold
  7866. try:
  7867. value = float(raw_alarm_value)
  7868. except (TypeError, ValueError):
  7869. return fair_threshold
  7870. if not math.isfinite(value) or value <= 0:
  7871. return fair_threshold
  7872. return value
  7873. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7874. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7875. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7876. # partway through a cool-down would otherwise resume alarming about heat the
  7877. # user asked for — the same internal-timestamp-row pattern as
  7878. # support.py's debug_logging_enabled_at.
  7879. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7880. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7881. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7882. # matters when it never does.
  7883. AMS_DRYING_GRACE_MINUTES = 120
  7884. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7885. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7886. Anything older than the grace cap would expire on its next visit anyway, so
  7887. discarding it here costs nothing and stops rows for deleted printers from
  7888. accumulating.
  7889. Stamps ahead of now get two defences, because a box whose clock jumps
  7890. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7891. ones are discarded outright, and the rest are clamped to now. Without the
  7892. clamp the cap would measure from a moment that has not happened yet and hold
  7893. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7894. after a clock jump is a far better failure than an alarm silently disabled
  7895. for hours.
  7896. """
  7897. from backend.app.models.settings import Settings
  7898. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7899. setting = result.scalar_one_or_none()
  7900. if not setting or not setting.value:
  7901. return {}
  7902. try:
  7903. raw = json.loads(setting.value)
  7904. except (ValueError, TypeError):
  7905. return {} # Corrupted row → no latch, alarms behave as they did before
  7906. if not isinstance(raw, dict):
  7907. return {}
  7908. now = datetime.now(timezone.utc)
  7909. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7910. latch: dict[str, datetime] = {}
  7911. for key, value in raw.items():
  7912. try:
  7913. stamp = datetime.fromisoformat(str(value))
  7914. except (ValueError, TypeError):
  7915. continue
  7916. if stamp.tzinfo is None:
  7917. stamp = stamp.replace(tzinfo=timezone.utc)
  7918. if not (now - window <= stamp <= now + window):
  7919. continue
  7920. # Nothing may sit in the future: suppression is measured as now minus
  7921. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7922. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7923. latch[str(key)] = min(stamp, now)
  7924. return latch
  7925. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7926. """Persist the latch, writing only when it actually changed.
  7927. Adds the session change but does not commit — the caller's own commit
  7928. carries it, so the latch lands in the same transaction as the sensor rows
  7929. that produced it.
  7930. """
  7931. from backend.app.models.settings import Settings
  7932. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7933. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7934. setting = result.scalar_one_or_none()
  7935. if setting is None:
  7936. # Don't create the row on installs that never dry anything.
  7937. if payload != "{}":
  7938. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7939. elif setting.value != payload:
  7940. setting.value = payload
  7941. def _ams_has_filament(ams_data: dict) -> bool:
  7942. """True if this AMS unit has at least one tray slot holding filament.
  7943. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7944. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7945. still report sensor readings, but those readings are ambient and not
  7946. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7947. humidity/temperature alarms on this check so empty units don't generate
  7948. hourly noise. Sensor history still records regardless so the UI charts
  7949. stay continuous.
  7950. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7951. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7952. """
  7953. bits = ams_data.get("tray_exist_bits")
  7954. if isinstance(bits, str) and bits.strip():
  7955. try:
  7956. return int(bits, 16) > 0
  7957. except ValueError:
  7958. pass
  7959. trays = ams_data.get("tray")
  7960. if isinstance(trays, list):
  7961. return any(
  7962. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  7963. )
  7964. return False
  7965. async def record_ams_history():
  7966. """Background task to record AMS humidity and temperature data."""
  7967. logger = logging.getLogger(__name__)
  7968. # Wait a short time for MQTT connections to establish on startup
  7969. await asyncio.sleep(10)
  7970. while True:
  7971. try:
  7972. from backend.app.models.ams_history import AMSSensorHistory
  7973. from backend.app.models.printer import Printer
  7974. from backend.app.models.settings import Settings
  7975. async with async_session() as db:
  7976. # Get all active printers
  7977. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7978. printers = result.scalars().all()
  7979. # Get alarm thresholds from settings
  7980. humidity_threshold = 60.0 # Default: fair threshold
  7981. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  7982. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  7983. setting = result.scalar_one_or_none()
  7984. if setting:
  7985. try:
  7986. humidity_threshold = float(setting.value)
  7987. except (ValueError, TypeError):
  7988. pass # Keep default threshold if stored value is invalid
  7989. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  7990. setting = result.scalar_one_or_none()
  7991. if setting:
  7992. try:
  7993. temp_fair_threshold = float(setting.value)
  7994. except (ValueError, TypeError):
  7995. pass # Keep default threshold if stored value is invalid
  7996. # The alarm gets its own threshold, seeded from the resolved fair
  7997. # value so an install that has never set one behaves exactly as
  7998. # it did before (#2905). ams_temp_fair decides when the card turns
  7999. # amber; 35 C is a reasonable place to change a colour and not a
  8000. # reasonable place to page someone. A room above it makes the
  8001. # alarm fire once an hour for as long as the weather lasts, and
  8002. # the only way to stop it was to raise the display band and lose
  8003. # the colour that says the unit is warm.
  8004. #
  8005. # An unset value is stored as the literal "None", which the except
  8006. # below swallows the same way it swallows garbage -- so the
  8007. # fallback costs nothing and needs no sentinel of its own.
  8008. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8009. setting = result.scalar_one_or_none()
  8010. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8011. temp_fair_threshold, setting.value if setting else None
  8012. )
  8013. # Per-filament humidity threshold overrides (#1605) — resolved
  8014. # per-AMS below from the loaded tray types. Reuses the same
  8015. # resolver as the auto-drying scheduler so behavior stays in
  8016. # lockstep across both consumers.
  8017. from backend.app.services.print_scheduler import PrintScheduler
  8018. per_type_humidity_thresholds: dict[str, int] = {}
  8019. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8020. setting = result.scalar_one_or_none()
  8021. if setting and setting.value:
  8022. try:
  8023. raw = json.loads(setting.value)
  8024. if isinstance(raw, dict):
  8025. for k, v in raw.items():
  8026. try:
  8027. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8028. v
  8029. )
  8030. except (TypeError, ValueError):
  8031. continue
  8032. except (ValueError, TypeError):
  8033. pass # Invalid JSON → no overrides, fall through to global threshold
  8034. # Per-AMS drying latch (#1802), loaded once per pass and written
  8035. # back below only if a unit changed it.
  8036. drying_latch = await _load_ams_drying_latch(db)
  8037. drying_latch_before = dict(drying_latch)
  8038. recorded_count = 0
  8039. for printer in printers:
  8040. # Get current state from printer manager
  8041. state = printer_manager.get_status(printer.id)
  8042. if not state or not state.connected or not state.raw_data:
  8043. continue # Skip disconnected printers - don't use stale data
  8044. raw_data = state.raw_data
  8045. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8046. continue
  8047. # Record data for each AMS unit
  8048. for ams_data in raw_data["ams"]:
  8049. ams_id = int(ams_data.get("id", 0))
  8050. # Percentage only. The 1-5 index is inverted, so
  8051. # charting it as a percentage drew the wettest units as
  8052. # the driest (#3140); a unit that reports no percentage
  8053. # leaves a gap in the chart instead. See
  8054. # utils/ams_humidity.
  8055. humidity = ams_humidity_percent(ams_data)
  8056. # No supported printer is known to send the index
  8057. # alone -- the report came from unsupported firmware,
  8058. # and no install has been seen using the old fallback.
  8059. # "Known" is doing work there, so say so once per unit:
  8060. # the alternative is a silent blank card.
  8061. if humidity is None and ams_data.get("humidity") is not None:
  8062. unit_key = (printer.id, ams_id)
  8063. if unit_key not in _ams_index_only_logged:
  8064. _ams_index_only_logged.add(unit_key)
  8065. logger.info(
  8066. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8067. "percentage. The index is inverted and is not shown as a percentage "
  8068. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8069. "Please report this with the printer and AMS firmware versions.",
  8070. printer.name,
  8071. ams_id,
  8072. )
  8073. # Get temperature
  8074. temperature = None
  8075. temp_str = ams_data.get("temp")
  8076. if temp_str is not None:
  8077. try:
  8078. temperature = float(temp_str)
  8079. except (ValueError, TypeError):
  8080. pass # Skip unparseable temperature value
  8081. # Skip if no data
  8082. if humidity is None and temperature is None:
  8083. continue
  8084. # Record the data point
  8085. history = AMSSensorHistory(
  8086. printer_id=printer.id,
  8087. ams_id=ams_id,
  8088. humidity=humidity,
  8089. # Both columns hold the same reading now that the
  8090. # index can no longer reach ``humidity``. Writing it
  8091. # through the same value also stops a genuine 0%
  8092. # from being stored as NULL, which the old truthiness
  8093. # test did.
  8094. humidity_raw=humidity,
  8095. temperature=temperature,
  8096. )
  8097. db.add(history)
  8098. recorded_count += 1
  8099. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8100. is_ams_ht = ams_id >= 128
  8101. if is_ams_ht:
  8102. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8103. else:
  8104. ams_label = f"AMS-{chr(65 + ams_id)}"
  8105. # Skip alarm dispatch for empty AMS units — humidity /
  8106. # temperature readings are ambient with no filament to
  8107. # protect, and the hourly notification just becomes
  8108. # noise. Sensor history was already recorded above so
  8109. # the UI charts stay continuous (#1619). Per-AMS check
  8110. # so a multi-AMS setup with one loaded + one empty
  8111. # still alarms on the loaded unit.
  8112. if not _ams_has_filament(ams_data):
  8113. continue
  8114. # Resolve per-filament humidity threshold for this AMS
  8115. # unit (#1605). Falls back to the global ams_humidity_fair
  8116. # when no per-type overrides are configured.
  8117. trays = ams_data.get("tray", []) or []
  8118. effective_humidity_threshold = float(
  8119. PrintScheduler.resolve_humidity_threshold(
  8120. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8121. )
  8122. )
  8123. # Check humidity alarm (only if above threshold)
  8124. if humidity is not None and humidity > effective_humidity_threshold:
  8125. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8126. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8127. now = datetime.now(timezone.utc)
  8128. if (
  8129. last_alarm is None
  8130. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8131. ):
  8132. _ams_alarm_cooldown[cooldown_key] = now
  8133. logger.info(
  8134. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8135. )
  8136. try:
  8137. # Call different notification method based on AMS type
  8138. if is_ams_ht:
  8139. await notification_service.on_ams_ht_humidity_high(
  8140. printer.id,
  8141. printer.name,
  8142. ams_label,
  8143. humidity,
  8144. effective_humidity_threshold,
  8145. db,
  8146. )
  8147. else:
  8148. await notification_service.on_ams_humidity_high(
  8149. printer.id,
  8150. printer.name,
  8151. ams_label,
  8152. humidity,
  8153. effective_humidity_threshold,
  8154. db,
  8155. )
  8156. except Exception as e:
  8157. logger.warning("Failed to send humidity alarm: %s", e)
  8158. # A drying cycle heats the unit far past ams_temp_fair on
  8159. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8160. # AMS-HT, against a 35 C default — so the alarm fired
  8161. # once an hour for the whole cycle and kept firing while
  8162. # the unit cooled back down (#1802). Latch on the
  8163. # firmware's own drying state and hold until the reading
  8164. # returns to normal. Humidity is deliberately left alone:
  8165. # it falls during drying, which is the whole point.
  8166. latch_key = f"{printer.id}:{ams_id}"
  8167. # The latch releases at `threshold`, so it takes the alarm
  8168. # number too. Handing it the display band would strand the
  8169. # latch on any unit that settles back above it -- a room
  8170. # where the AMS rests at 37.7 C never returns under a 35 C
  8171. # band, so the latch could only expire on the grace cap
  8172. # rather than releasing when the unit had actually cooled.
  8173. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8174. drying_active=is_drying_active(ams_data),
  8175. temperature=temperature,
  8176. threshold=temp_alarm_threshold,
  8177. latched_at=drying_latch.get(latch_key),
  8178. now=datetime.now(timezone.utc),
  8179. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8180. )
  8181. if new_latch is None:
  8182. drying_latch.pop(latch_key, None)
  8183. else:
  8184. drying_latch[latch_key] = new_latch
  8185. # Check temperature alarm (only if above threshold)
  8186. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8187. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8188. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8189. now = datetime.now(timezone.utc)
  8190. if (
  8191. last_alarm is None
  8192. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8193. ):
  8194. _ams_alarm_cooldown[cooldown_key] = now
  8195. logger.info(
  8196. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8197. f"{temperature}°C > {temp_alarm_threshold}°C"
  8198. )
  8199. try:
  8200. # Call different notification method based on AMS type
  8201. if is_ams_ht:
  8202. # The reported threshold has to be the one
  8203. # that fired, or the message says "> 35 °C"
  8204. # while firing at 45.
  8205. await notification_service.on_ams_ht_temperature_high(
  8206. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8207. )
  8208. else:
  8209. await notification_service.on_ams_temperature_high(
  8210. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8211. )
  8212. except Exception as e:
  8213. logger.warning("Failed to send temperature alarm: %s", e)
  8214. if drying_latch != drying_latch_before:
  8215. await _save_ams_drying_latch(db, drying_latch)
  8216. await db.commit()
  8217. if recorded_count > 0:
  8218. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8219. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8220. global _ams_cleanup_counter
  8221. _ams_cleanup_counter += 1
  8222. if _ams_cleanup_counter >= 288:
  8223. _ams_cleanup_counter = 0
  8224. # Get retention days from settings
  8225. from backend.app.models.settings import Settings
  8226. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8227. setting = result.scalar_one_or_none()
  8228. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8229. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8230. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8231. await db.commit()
  8232. if result.rowcount > 0:
  8233. logger.info(
  8234. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8235. )
  8236. # Wait until next recording interval
  8237. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8238. except asyncio.CancelledError:
  8239. break
  8240. except Exception as e:
  8241. logger.warning("AMS history recording failed: %s", e)
  8242. await asyncio.sleep(60) # Wait a bit before retrying
  8243. def start_ams_history_recording():
  8244. """Start the AMS history recording background task."""
  8245. global _ams_history_task
  8246. if _ams_history_task is None:
  8247. _ams_history_task = asyncio.create_task(record_ams_history())
  8248. logging.getLogger(__name__).info("AMS history recording started")
  8249. def stop_ams_history_recording():
  8250. """Stop the AMS history recording background task."""
  8251. global _ams_history_task
  8252. if _ams_history_task:
  8253. _ams_history_task.cancel()
  8254. _ams_history_task = None
  8255. logging.getLogger(__name__).info("AMS history recording stopped")
  8256. # Printer sensor history recording (nozzle / bed / chamber)
  8257. _printer_sensor_history_task: asyncio.Task | None = None
  8258. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8259. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8260. _printer_sensor_cleanup_counter = 0
  8261. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8262. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8263. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8264. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8265. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8266. _SENSOR_TARGET_KEYS = {
  8267. "nozzle": "nozzle_target",
  8268. "nozzle_2": "nozzle_2_target",
  8269. "bed": "bed_target",
  8270. "chamber": "chamber_target",
  8271. }
  8272. async def record_printer_sensor_history():
  8273. """Background task to record nozzle / bed / chamber readings.
  8274. Pulls from `state.temperatures` (already normalised across all printer
  8275. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8276. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8277. """
  8278. logger = logging.getLogger(__name__)
  8279. await asyncio.sleep(10)
  8280. while True:
  8281. try:
  8282. from backend.app.models.printer import Printer
  8283. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8284. from backend.app.models.settings import Settings
  8285. async with async_session() as db:
  8286. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8287. printers = result.scalars().all()
  8288. recorded_count = 0
  8289. for printer in printers:
  8290. state = printer_manager.get_status(printer.id)
  8291. if not state or not state.connected:
  8292. continue
  8293. temps = getattr(state, "temperatures", None) or {}
  8294. if not isinstance(temps, dict):
  8295. continue
  8296. for kind in _SENSOR_KINDS:
  8297. if kind not in temps:
  8298. continue
  8299. try:
  8300. value = float(temps[kind])
  8301. except (ValueError, TypeError):
  8302. continue
  8303. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8304. target_val: float | None = None
  8305. if target_raw is not None:
  8306. try:
  8307. target_val = float(target_raw)
  8308. except (ValueError, TypeError):
  8309. target_val = None
  8310. db.add(
  8311. PrinterSensorHistory(
  8312. printer_id=printer.id,
  8313. sensor_kind=kind,
  8314. value=value,
  8315. target=target_val,
  8316. )
  8317. )
  8318. recorded_count += 1
  8319. await db.commit()
  8320. if recorded_count > 0:
  8321. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8322. # Periodic cleanup — once every ~24h at this interval.
  8323. global _printer_sensor_cleanup_counter
  8324. _printer_sensor_cleanup_counter += 1
  8325. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8326. if _printer_sensor_cleanup_counter >= cleanup_every:
  8327. _printer_sensor_cleanup_counter = 0
  8328. result = await db.execute(
  8329. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8330. )
  8331. setting = result.scalar_one_or_none()
  8332. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8333. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8334. cleanup = await db.execute(
  8335. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8336. )
  8337. await db.commit()
  8338. if cleanup.rowcount > 0:
  8339. logger.info(
  8340. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8341. cleanup.rowcount,
  8342. retention_days,
  8343. )
  8344. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8345. except asyncio.CancelledError:
  8346. break
  8347. except Exception as e:
  8348. logger.warning("Printer sensor history recording failed: %s", e)
  8349. await asyncio.sleep(60)
  8350. def start_printer_sensor_history_recording():
  8351. global _printer_sensor_history_task
  8352. if _printer_sensor_history_task is None:
  8353. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8354. logging.getLogger(__name__).info("Printer sensor history recording started")
  8355. def stop_printer_sensor_history_recording():
  8356. global _printer_sensor_history_task
  8357. if _printer_sensor_history_task:
  8358. _printer_sensor_history_task.cancel()
  8359. _printer_sensor_history_task = None
  8360. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8361. # Printer runtime tracking
  8362. _runtime_tracking_task: asyncio.Task | None = None
  8363. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8364. async def track_printer_runtime():
  8365. """Background task to track printer active runtime (RUNNING state only).
  8366. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8367. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8368. which track mechanical wear. Pause time has no motion and no wear, so
  8369. counting it inflates maintenance warnings (#1521).
  8370. """
  8371. logger = logging.getLogger(__name__)
  8372. # Wait for MQTT connections to establish on startup
  8373. await asyncio.sleep(15)
  8374. while True:
  8375. try:
  8376. from backend.app.models.printer import Printer
  8377. # Fetch printer IDs in a short-lived read-only session
  8378. async with async_session() as db:
  8379. result = await db.execute(
  8380. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8381. Printer.is_active.is_(True)
  8382. )
  8383. )
  8384. printer_rows = result.all()
  8385. now = datetime.now(timezone.utc)
  8386. updated_count = 0
  8387. # Update each printer in its own short session to minimise write-lock
  8388. # hold time and avoid blocking critical commits like queue status
  8389. # updates (#897).
  8390. for pid, pname, runtime_secs, last_update in printer_rows:
  8391. state = printer_manager.get_status(pid)
  8392. if not state:
  8393. logger.debug("[%s] Runtime tracking: no state available", pname)
  8394. continue
  8395. if not state.connected:
  8396. logger.debug("[%s] Runtime tracking: not connected", pname)
  8397. continue
  8398. needs_commit = False
  8399. new_runtime = runtime_secs
  8400. new_last_update = last_update
  8401. if state.state == "RUNNING":
  8402. if last_update:
  8403. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8404. elapsed = (now - lu).total_seconds()
  8405. if elapsed > 0:
  8406. new_runtime = runtime_secs + int(elapsed)
  8407. updated_count += 1
  8408. needs_commit = True
  8409. logger.debug(
  8410. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8411. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8412. )
  8413. else:
  8414. needs_commit = True
  8415. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8416. new_last_update = now
  8417. else:
  8418. if last_update is not None:
  8419. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8420. new_last_update = None
  8421. needs_commit = True
  8422. if needs_commit:
  8423. try:
  8424. async with async_session() as db:
  8425. result = await db.execute(select(Printer).where(Printer.id == pid))
  8426. printer = result.scalar_one_or_none()
  8427. if printer:
  8428. printer.runtime_seconds = new_runtime
  8429. printer.last_runtime_update = new_last_update
  8430. await db.commit()
  8431. except Exception as e:
  8432. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8433. if updated_count > 0:
  8434. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8435. except asyncio.CancelledError:
  8436. logger.info("Runtime tracking cancelled")
  8437. break
  8438. except Exception as e:
  8439. logger.warning("Runtime tracking failed: %s", e)
  8440. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8441. def start_runtime_tracking():
  8442. """Start the printer runtime tracking background task."""
  8443. global _runtime_tracking_task
  8444. if _runtime_tracking_task is None:
  8445. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8446. logging.getLogger(__name__).info("Printer runtime tracking started")
  8447. def stop_runtime_tracking():
  8448. """Stop the printer runtime tracking background task."""
  8449. global _runtime_tracking_task
  8450. if _runtime_tracking_task:
  8451. _runtime_tracking_task.cancel()
  8452. _runtime_tracking_task = None
  8453. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8454. # SpoolBuddy device watchdog
  8455. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8456. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8457. async def _spoolbuddy_watchdog_loop():
  8458. """Periodic check for SpoolBuddy devices that have gone offline."""
  8459. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8460. while True:
  8461. try:
  8462. await spoolbuddy_watchdog()
  8463. except asyncio.CancelledError:
  8464. break
  8465. except Exception as e:
  8466. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8467. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8468. def start_spoolbuddy_watchdog():
  8469. global _spoolbuddy_watchdog_task
  8470. if _spoolbuddy_watchdog_task is None:
  8471. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8472. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8473. def stop_spoolbuddy_watchdog():
  8474. global _spoolbuddy_watchdog_task
  8475. if _spoolbuddy_watchdog_task:
  8476. _spoolbuddy_watchdog_task.cancel()
  8477. _spoolbuddy_watchdog_task = None
  8478. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8479. # Dead-MQTT-session recovery
  8480. #
  8481. # check_staleness() covers the "connected but silent" half-broken session. It
  8482. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8483. # is the only thing left watching at that point. When paho stops making
  8484. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8485. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8486. # offline with the UI open the whole time, recovered only when something
  8487. # happened to nudge it.
  8488. #
  8489. # This loop is that backstop. It only touches printers that had a working
  8490. # session and lost it, and only when the MQTT port still answers — a printer
  8491. # that is simply switched off is left to paho, since rebuilding a client
  8492. # against an unreachable host achieves nothing and would fill the log every
  8493. # night.
  8494. _connection_watchdog_task: asyncio.Task | None = None
  8495. CONNECTION_WATCHDOG_INTERVAL = 60
  8496. # How long a printer must have been silent before we stop trusting paho.
  8497. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8498. # so a session that is recovering on its own is never interrupted.
  8499. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8500. # Per-printer floor between rebuild attempts.
  8501. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8502. _connection_watchdog_last_attempt: dict[int, float] = {}
  8503. async def _recover_dead_printer_sessions() -> int:
  8504. """Rebuild MQTT clients that have been offline too long to still be trying.
  8505. Returns the number of printers a rebuild was attempted for (for tests and
  8506. for the caller's logging). Never raises: one unreachable printer must not
  8507. stop the sweep for the rest of the farm.
  8508. """
  8509. logger = logging.getLogger(__name__)
  8510. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8511. now = time.monotonic()
  8512. recovered = 0
  8513. for printer_id, client in list(printer_manager._clients.items()):
  8514. try:
  8515. if client.state.connected:
  8516. _connection_watchdog_last_attempt.pop(printer_id, None)
  8517. continue
  8518. # Time since the last inbound message is the age of the last known
  8519. # good session — no extra bookkeeping needed, and it is the same
  8520. # clock is_stale() reads. 0 means this client has never had one:
  8521. # that is the initial-connect path, where paho retrying is the
  8522. # correct and only behaviour, so leave it be.
  8523. last_msg = client._last_message_time
  8524. if not last_msg:
  8525. continue
  8526. offline_for = time.time() - last_msg
  8527. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8528. continue
  8529. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8530. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8531. continue
  8532. if not await check_port(client.ip_address, PORT_MQTT):
  8533. # Switched off, unplugged, or off the network. Paho's retry is
  8534. # the right handler; say so at debug level and move on.
  8535. logger.debug(
  8536. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8537. "— leaving the reconnect to paho",
  8538. printer_id,
  8539. offline_for,
  8540. )
  8541. _connection_watchdog_last_attempt[printer_id] = now
  8542. continue
  8543. _connection_watchdog_last_attempt[printer_id] = now
  8544. recovered += 1
  8545. logger.warning(
  8546. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8547. "rebuilding the client with a fresh session (last connect error: %s)",
  8548. printer_id,
  8549. offline_for,
  8550. PORT_MQTT,
  8551. client.last_connect_error or "none recorded",
  8552. )
  8553. # Async context, so this takes the hard-reset path: fresh client_id,
  8554. # paho's QoS 1 queue dropped. That matters — a project_file left
  8555. # unacked on the dead session would otherwise replay into the new
  8556. # one and trip 0500_4003 on the printer (#1136).
  8557. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8558. except Exception as e:
  8559. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8560. return recovered
  8561. async def _connection_watchdog_loop():
  8562. logger = logging.getLogger(__name__)
  8563. # Let the initial connects settle before judging anyone offline.
  8564. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8565. while True:
  8566. try:
  8567. await _recover_dead_printer_sessions()
  8568. except asyncio.CancelledError:
  8569. break
  8570. except Exception as e:
  8571. logger.warning("Connection watchdog sweep failed: %s", e)
  8572. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8573. def start_connection_watchdog():
  8574. global _connection_watchdog_task
  8575. if _connection_watchdog_task is None:
  8576. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8577. logging.getLogger(__name__).info("Printer connection watchdog started")
  8578. def stop_connection_watchdog():
  8579. global _connection_watchdog_task
  8580. if _connection_watchdog_task:
  8581. _connection_watchdog_task.cancel()
  8582. _connection_watchdog_task = None
  8583. _connection_watchdog_last_attempt.clear()
  8584. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8585. # Camera stream orphan cleanup
  8586. _camera_cleanup_task: asyncio.Task | None = None
  8587. CAMERA_CLEANUP_INTERVAL = 60
  8588. async def _camera_cleanup_loop():
  8589. """Periodically clean up orphaned ffmpeg processes."""
  8590. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8591. while True:
  8592. try:
  8593. await cleanup_orphaned_streams()
  8594. except asyncio.CancelledError:
  8595. break
  8596. except Exception as e:
  8597. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8598. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8599. def start_camera_cleanup():
  8600. global _camera_cleanup_task
  8601. if _camera_cleanup_task is None:
  8602. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8603. logging.getLogger(__name__).info("Camera stream cleanup started")
  8604. def stop_camera_cleanup():
  8605. global _camera_cleanup_task
  8606. if _camera_cleanup_task:
  8607. _camera_cleanup_task.cancel()
  8608. _camera_cleanup_task = None
  8609. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8610. # ---------------------------------------------------------------------------
  8611. # Expected-print TTL eviction
  8612. # ---------------------------------------------------------------------------
  8613. def _evict_stale_expected_prints() -> None:
  8614. """Remove entries from _expected_prints / _expected_print_creators that are
  8615. older than _EXPECTED_PRINT_TTL_SECONDS.
  8616. This prevents unbounded growth when a print is registered (via
  8617. register_expected_print) but on_print_start never fires — e.g. because the
  8618. printer disconnects, the app restarts, or the print is started directly from
  8619. the printer panel without going through the queue.
  8620. """
  8621. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8622. # (e.g. NTP sync, DST changes).
  8623. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8624. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8625. if not stale_keys:
  8626. return
  8627. evicted_archive_ids: set[int] = set()
  8628. for key in stale_keys:
  8629. archive_id = _expected_prints.pop(key, None)
  8630. if archive_id is not None:
  8631. evicted_archive_ids.add(archive_id)
  8632. _expected_print_creators.pop(key, None)
  8633. _expected_print_registered_at.pop(key, None)
  8634. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8635. # that have no remaining live keys in _expected_prints (all variants
  8636. # were just evicted).
  8637. live_archive_ids = set(_expected_prints.values())
  8638. for archive_id in evicted_archive_ids:
  8639. if archive_id not in live_archive_ids:
  8640. _print_ams_mappings.pop(archive_id, None)
  8641. _print_cost_center_ids.pop(archive_id, None)
  8642. _print_plate_ids.pop(archive_id, None)
  8643. logging.getLogger(__name__).info(
  8644. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8645. )
  8646. async def _expected_prints_cleanup_loop() -> None:
  8647. """Background task: periodically evict stale expected-print entries."""
  8648. while True:
  8649. try:
  8650. _evict_stale_expected_prints()
  8651. except asyncio.CancelledError:
  8652. raise
  8653. except Exception as e:
  8654. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8655. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8656. def start_expected_prints_cleanup() -> None:
  8657. global _expected_prints_cleanup_task
  8658. if _expected_prints_cleanup_task is None:
  8659. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8660. logging.getLogger(__name__).info("Expected prints cleanup started")
  8661. def stop_expected_prints_cleanup() -> None:
  8662. global _expected_prints_cleanup_task
  8663. if _expected_prints_cleanup_task:
  8664. _expected_prints_cleanup_task.cancel()
  8665. _expected_prints_cleanup_task = None
  8666. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8667. # ---------------------------------------------------------------------------
  8668. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8669. # ---------------------------------------------------------------------------
  8670. _auth_cleanup_task: asyncio.Task | None = None
  8671. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8672. async def _run_auth_cleanup() -> None:
  8673. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8674. from backend.app.core.database import async_session
  8675. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8676. from backend.app.models.user_totp import UserTOTP
  8677. now = datetime.now(timezone.utc)
  8678. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8679. try:
  8680. async with async_session() as db:
  8681. stale_cutoff = now - timedelta(hours=1)
  8682. result = await db.execute(
  8683. select(UserTOTP).where(
  8684. UserTOTP.is_enabled.is_(False),
  8685. UserTOTP.created_at < stale_cutoff,
  8686. )
  8687. )
  8688. stale_records = result.scalars().all()
  8689. if stale_records:
  8690. for rec in stale_records:
  8691. await db.delete(rec)
  8692. await db.commit()
  8693. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8694. except Exception as e:
  8695. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8696. # Remove expired revoked-JTI entries (they are no longer needed once the
  8697. # original token's exp has passed — the token would be rejected by JWT
  8698. # signature verification regardless).
  8699. try:
  8700. async with async_session() as db:
  8701. await db.execute(
  8702. delete(AuthEphemeralToken).where(
  8703. AuthEphemeralToken.token_type == "revoked_jti",
  8704. AuthEphemeralToken.expires_at < now,
  8705. )
  8706. )
  8707. await db.commit()
  8708. except Exception as e:
  8709. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8710. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8711. # Events outside this window can never affect rate-limit decisions — they only
  8712. # consume DB space. Use the same window constant as the rate limiter so the
  8713. # two are always in sync.
  8714. try:
  8715. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8716. async with async_session() as db:
  8717. await db.execute(
  8718. delete(AuthRateLimitEvent).where(
  8719. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8720. )
  8721. )
  8722. await db.commit()
  8723. except Exception as e:
  8724. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8725. async def _auth_cleanup_loop() -> None:
  8726. """Periodic background task: run auth cleanup every hour."""
  8727. while True:
  8728. try:
  8729. await _run_auth_cleanup()
  8730. except asyncio.CancelledError:
  8731. break
  8732. except Exception as e:
  8733. logging.warning("Auth cleanup loop error: %s", e)
  8734. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8735. def start_auth_cleanup() -> None:
  8736. global _auth_cleanup_task
  8737. if _auth_cleanup_task is None:
  8738. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8739. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8740. def stop_auth_cleanup() -> None:
  8741. global _auth_cleanup_task
  8742. if _auth_cleanup_task:
  8743. _auth_cleanup_task.cancel()
  8744. _auth_cleanup_task = None
  8745. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8746. @asynccontextmanager
  8747. async def lifespan(app: FastAPI):
  8748. # Startup
  8749. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8750. # anything else can spawn tasks that might trip it.
  8751. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8752. install_proactor_reset_filter()
  8753. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  8754. # what turned descriptor exhaustion into a corrupted database (#2883).
  8755. from backend.app.core.fd_limit import raise_open_file_limit
  8756. raise_open_file_limit()
  8757. # Before init_db, so the warning is near the top of the log rather than
  8758. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8759. warn_if_running_on_uvloop()
  8760. await init_db()
  8761. # Browser download tokens expire after five minutes. Remove abandoned
  8762. # prepared ZIPs at startup as well as before each new preparation so a
  8763. # quiet appliance cannot retain an unusable bundle indefinitely.
  8764. try:
  8765. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8766. await prune_stale_printer_file_bundles()
  8767. except Exception as exc:
  8768. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8769. # After migrations, so the is_env_managed column exists. Never raises --
  8770. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8771. # startup (see apply_env_oidc_provider).
  8772. from backend.app.core.oidc_env import apply_env_oidc_provider
  8773. async with async_session() as oidc_db:
  8774. await apply_env_oidc_provider(oidc_db)
  8775. # Close out batches that finished before `completed` was a reachable status
  8776. # (#342). Without this the Batches tab opens on every batch created since
  8777. # the feature shipped, all still marked active. Never blocks startup.
  8778. try:
  8779. from backend.app.services.print_batch import backfill_batch_statuses
  8780. async with async_session() as batch_db:
  8781. await backfill_batch_statuses(batch_db)
  8782. except Exception as exc:
  8783. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8784. # Register an app-scoped httpx client for Bambu Cloud services so
  8785. # per-request BambuCloudService instances reuse the same connection pool
  8786. # (important for routes like /cloud/filament-info that chain many
  8787. # get_setting_detail calls). The shared client stores no region/token
  8788. # state, so the per-request ownership pattern that fixed the region-bleed
  8789. # bug is preserved.
  8790. import httpx as _httpx
  8791. from backend.app.services.bambu_cloud import set_shared_http_client
  8792. from backend.app.services.model_providers.makerworld.service import (
  8793. set_shared_http_client as set_shared_makerworld_http_client,
  8794. )
  8795. from backend.app.services.orca_cloud import (
  8796. set_shared_http_client as set_shared_orca_http_client,
  8797. )
  8798. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8799. set_shared_http_client(_shared_cloud_http_client)
  8800. # Reuse the same connection pool for MakerWorld — different host, same
  8801. # keep-alive pool saves a TLS handshake per request.
  8802. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8803. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8804. # each spun up (and never closed) its own client, leaking sockets.
  8805. set_shared_orca_http_client(_shared_cloud_http_client)
  8806. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8807. # This can happen when a print was cancelled mid-print on versions before this fix.
  8808. try:
  8809. async with async_session() as db:
  8810. from backend.app.models.print_queue import PrintQueueItem
  8811. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8812. aborted_items = result.scalars().all()
  8813. if aborted_items:
  8814. for item in aborted_items:
  8815. item.status = "cancelled"
  8816. await db.commit()
  8817. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8818. except Exception as e:
  8819. logging.warning("Failed to fix aborted queue items: %s", e)
  8820. # Restore debug logging state from previous session
  8821. await init_debug_logging()
  8822. # Set up printer manager callbacks
  8823. loop = asyncio.get_event_loop()
  8824. printer_manager.set_event_loop(loop)
  8825. printer_manager.set_status_change_callback(on_printer_status_change)
  8826. printer_manager.set_print_start_callback(on_print_start)
  8827. printer_manager.set_print_complete_callback(on_print_complete)
  8828. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8829. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8830. printer_manager.set_ams_change_callback(on_ams_change)
  8831. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8832. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8833. await printer_manager.load_awaiting_plate_clear_from_db()
  8834. # Layer change callback for external camera timelapse
  8835. async def on_layer_change(printer_id: int, layer_num: int):
  8836. """Capture timelapse frame on layer change + first layer notification."""
  8837. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8838. await tl_layer_change(printer_id, layer_num)
  8839. # #1867: bank a recent in-print frame so the finish-photo path has a
  8840. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8841. # #2547 added `on_print_progress` as a second driver — this one alone
  8842. # stops firing once the final layer begins.
  8843. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8844. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8845. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8846. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8847. # nozzle clean), so a bare layer_num check can fire minutes before the
  8848. # first real extrusion. We require gcode_state == RUNNING and
  8849. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8850. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8851. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8852. # edge fires later; _first_layer_notified stays clear until we actually send
  8853. # so a deferred re-evaluation can win. See issue #1837.
  8854. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8855. client = printer_manager.get_client(printer_id)
  8856. state = client.state if client else None
  8857. if not state or state.state != "RUNNING":
  8858. return
  8859. if state.mc_print_sub_stage not in (None, 0):
  8860. return
  8861. _first_layer_notified[printer_id] = True
  8862. try:
  8863. async with async_session() as db:
  8864. from backend.app.models.printer import Printer
  8865. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8866. printer = result.scalar_one_or_none()
  8867. if not printer:
  8868. return
  8869. printer_name = printer.name
  8870. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8871. total_layers = state.total_layers if state else 0
  8872. image_data = await _capture_snapshot_for_notification(
  8873. printer_id, printer, logging.getLogger(__name__)
  8874. )
  8875. await notification_service.on_first_layer_complete(
  8876. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8877. )
  8878. except Exception as e:
  8879. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8880. printer_manager.set_layer_change_callback(on_layer_change)
  8881. async def on_print_progress(printer_id: int, percent: int):
  8882. """#2547: keep the in-print frame bank fresh through the final layer.
  8883. `on_layer_change` stops the moment the last layer starts, which on the
  8884. H2C capture that closed #2547 left the bank stale for the three minutes
  8885. that layer took. Progress is the only field that keeps advancing there,
  8886. and it freezes before the End G-code runs — so banking on it stays
  8887. inside the print and never sees a swapped plate.
  8888. """
  8889. client = printer_manager.get_client(printer_id)
  8890. state = client.state if client else None
  8891. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8892. printer_manager.set_print_progress_callback(on_print_progress)
  8893. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8894. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8895. waiter = _bed_cool_waiters.get(printer_id)
  8896. if not waiter:
  8897. return
  8898. threshold = waiter["threshold"]
  8899. if bed_temp > threshold:
  8900. return
  8901. # Bed is at or below threshold — fire notification and remove waiter
  8902. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8903. if not waiter_info:
  8904. return # Another callback already handled it
  8905. bed_cool_logger = logging.getLogger(__name__)
  8906. bed_cool_logger.info(
  8907. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8908. bed_temp,
  8909. printer_id,
  8910. threshold,
  8911. )
  8912. try:
  8913. printer_info = printer_manager.get_printer(printer_id)
  8914. p_name = printer_info.name if printer_info else "Unknown"
  8915. async with async_session() as db:
  8916. await notification_service.on_bed_cooled(
  8917. printer_id=printer_id,
  8918. printer_name=p_name,
  8919. bed_temp=bed_temp,
  8920. threshold=threshold,
  8921. filename=waiter_info["filename"],
  8922. db=db,
  8923. )
  8924. except Exception as e:
  8925. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8926. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8927. async def on_drying_complete(printer_id: int, ams_id: int):
  8928. """Smart-plug auto-off-after-drying trigger (#1349).
  8929. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8930. manager walks all plugs linked to this printer and turns off only
  8931. the ones with ``auto_off_after_drying`` enabled, after their
  8932. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8933. dual-AMS dry that ends within the same MQTT push) call this once
  8934. per unit — the manager's ``_cancel_pending_off`` collapses
  8935. repeated scheduling on the same plug to one timer, so duplicate
  8936. fires are safe.
  8937. """
  8938. try:
  8939. async with async_session() as db:
  8940. await smart_plug_manager.on_drying_complete(printer_id, db)
  8941. except Exception as e:
  8942. logging.getLogger(__name__).warning(
  8943. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8944. printer_id,
  8945. ams_id,
  8946. e,
  8947. )
  8948. printer_manager.set_drying_complete_callback(on_drying_complete)
  8949. async def on_drying_cycle_end(printer_id: int, cycle):
  8950. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  8951. from backend.app.services.spool_drying import record_drying_cycle
  8952. try:
  8953. async with async_session() as db:
  8954. await record_drying_cycle(db, printer_id, cycle)
  8955. except Exception as e:
  8956. logging.getLogger(__name__).warning(
  8957. "Failed to record drying for printer %d (AMS %d): %s",
  8958. printer_id,
  8959. cycle.ams_id,
  8960. e,
  8961. )
  8962. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  8963. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  8964. """Surface the read-back result of a spool assignment to the UI (#2582).
  8965. The MQTT client confirms (or fails to confirm) that the tray telemetry
  8966. echoed back the filament id we pushed. We relay that as a websocket
  8967. event so the frontend can toast "loaded" / "assignment didn't take"
  8968. instead of the historic silent fire-and-forget, which made the
  8969. AMS→Studio hand-off feel random to users.
  8970. """
  8971. try:
  8972. from backend.app.services.spool_assignment_notifications import (
  8973. _slot_label_from_global_tray,
  8974. )
  8975. if ams_id == 255:
  8976. global_id = 254 + tray_id
  8977. elif ams_id >= 128:
  8978. global_id = ams_id
  8979. else:
  8980. global_id = ams_id * 4 + tray_id
  8981. slot_label = _slot_label_from_global_tray(global_id)
  8982. printer_info = printer_manager.get_printer(printer_id)
  8983. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8984. await ws_manager.broadcast(
  8985. {
  8986. "type": "spool_assignment_verified",
  8987. "printer_id": printer_id,
  8988. "printer_name": printer_name,
  8989. "ams_id": ams_id,
  8990. "tray_id": tray_id,
  8991. "slot": slot_label,
  8992. "verified": verified,
  8993. # Present on success: False means the filament setting landed
  8994. # but the K-profile (cali_idx) did not — the reporter's exact
  8995. # "loaded but no flow profile" symptom.
  8996. "kprofile_applied": detail.get("kprofile_applied", True),
  8997. # Present on failure: whether any tray telemetry was seen in
  8998. # the window (distinguishes "printer silent" from "printer
  8999. # stored something else").
  9000. "saw_tray": detail.get("saw_tray", False),
  9001. }
  9002. )
  9003. except Exception as e:
  9004. logging.getLogger(__name__).warning(
  9005. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9006. printer_id,
  9007. ams_id,
  9008. tray_id,
  9009. e,
  9010. )
  9011. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9012. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9013. """Persist a mid-print tray change for completion-time attribution.
  9014. AMS filament backup switches trays without telling the slicer, so the
  9015. tray-change log is the only record of which spool fed which layers.
  9016. Keeping it only in memory meant a restart mid-print charged everything
  9017. to the tray that finished the job.
  9018. """
  9019. try:
  9020. from backend.app.services.usage_tracker import record_tray_change
  9021. async with async_session() as db:
  9022. await record_tray_change(db, printer_id, tray_global, layer_num)
  9023. except Exception as e:
  9024. logging.getLogger(__name__).warning(
  9025. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9026. printer_id,
  9027. tray_global,
  9028. layer_num,
  9029. e,
  9030. )
  9031. printer_manager.set_tray_change_callback(on_tray_change)
  9032. # Initialize MQTT relay from settings
  9033. async with async_session() as db:
  9034. from backend.app.api.routes.settings import get_setting
  9035. mqtt_settings = {
  9036. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9037. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9038. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9039. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9040. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9041. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9042. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9043. }
  9044. await mqtt_relay.configure(mqtt_settings)
  9045. # Restore MQTT smart plug subscriptions
  9046. if mqtt_settings.get("mqtt_enabled"):
  9047. from backend.app.models.smart_plug import SmartPlug
  9048. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9049. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9050. mqtt_plugs = result.scalars().all()
  9051. restored = 0
  9052. for plug in mqtt_plugs:
  9053. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9054. restored += 1
  9055. if restored:
  9056. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9057. # Connect to all active printers
  9058. async with async_session() as db:
  9059. await init_printer_connections(db)
  9060. # Auto-connect to Spoolman if enabled
  9061. async with async_session() as db:
  9062. from backend.app.api.routes.settings import get_setting
  9063. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9064. spoolman_url = await get_setting(db, "spoolman_url")
  9065. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9066. try:
  9067. client = await init_spoolman_client(spoolman_url)
  9068. if await client.health_check():
  9069. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9070. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9071. field_ok = await client.ensure_tag_extra_field()
  9072. if not field_ok:
  9073. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9074. # Register the BambuStudio slicer-preset fields used by the
  9075. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9076. # unknown extra keys, so these must exist before any update
  9077. # that touches them.
  9078. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9079. if not await client.ensure_extra_field(field_name):
  9080. logging.warning(
  9081. "Spoolman extra field %r registration failed — "
  9082. "spool slicer-preset edits will return 502",
  9083. field_name,
  9084. )
  9085. else:
  9086. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9087. except Exception as e:
  9088. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9089. # Start the print scheduler
  9090. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9091. # Start the smart plug scheduler for time-based on/off
  9092. smart_plug_manager.start_scheduler()
  9093. # Start the Home Assistant sensor poller (#1148)
  9094. ha_sensor_manager.start()
  9095. location_ha_sensor_manager.start()
  9096. # Resume any pending auto-offs that were interrupted by restart
  9097. await smart_plug_manager.resume_pending_auto_offs()
  9098. # Start the notification digest scheduler
  9099. notification_service.start_digest_scheduler()
  9100. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9101. # provider in reactions/both mode; the notification routes resync them.
  9102. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9103. # until the next provider save, not the whole startup.
  9104. try:
  9105. await telegram_reaction_poller.start()
  9106. except Exception as e:
  9107. logging.warning("Telegram reaction poller did not start: %s", e)
  9108. # Start the GitHub backup scheduler
  9109. await github_backup_service.start_scheduler()
  9110. # Start the local backup scheduler
  9111. await local_backup_service.start_scheduler()
  9112. await obico_detection_service.start()
  9113. # Start the library trash sweeper (#1008)
  9114. await library_trash_service.start_scheduler()
  9115. # Start the archive auto-purge sweeper (#1008 follow-up)
  9116. await archive_purge_service.start_scheduler()
  9117. # Start AMS history recording
  9118. start_ams_history_recording()
  9119. # Start printer sensor (nozzle / bed / chamber) history recording
  9120. start_printer_sensor_history_recording()
  9121. # Start printer runtime tracking
  9122. start_runtime_tracking()
  9123. # Start SpoolBuddy device watchdog
  9124. start_spoolbuddy_watchdog()
  9125. # Start camera stream orphan cleanup
  9126. start_camera_cleanup()
  9127. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9128. start_connection_watchdog()
  9129. # One-shot sweep for timelapse session directories orphaned by a crash
  9130. # or restart that happened mid-print (in-memory session tracking can't
  9131. # survive that, and nothing else reaps the leftover frames/output file)
  9132. try:
  9133. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9134. removed = cleanup_orphaned_timelapse_sessions()
  9135. if removed:
  9136. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9137. except Exception as e:
  9138. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9139. # Start expected-print TTL eviction (prevents memory leak when prints are
  9140. # registered but on_print_start never fires)
  9141. start_expected_prints_cleanup()
  9142. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9143. start_auth_cleanup()
  9144. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9145. from backend.app.services import announcements as announcements_service
  9146. announcements_service.start()
  9147. from backend.app.services.printer_media import start_printer_download_cleanup
  9148. start_printer_download_cleanup()
  9149. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9150. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9151. from backend.app.services.loop_watchdog import start_loop_watchdog
  9152. start_loop_watchdog()
  9153. # Initialize virtual printer manager and sync from DB
  9154. from backend.app.services.virtual_printer import virtual_printer_manager
  9155. virtual_printer_manager.set_session_factory(async_session)
  9156. virtual_printer_manager.set_printer_manager(printer_manager)
  9157. try:
  9158. await virtual_printer_manager.sync_from_db()
  9159. logging.info("Virtual printer manager synced from database")
  9160. except Exception as e:
  9161. logging.warning("Failed to sync virtual printers: %s", e)
  9162. yield
  9163. # Shutdown
  9164. print_scheduler.stop()
  9165. smart_plug_manager.stop_scheduler()
  9166. ha_sensor_manager.stop()
  9167. location_ha_sensor_manager.stop()
  9168. notification_service.stop_digest_scheduler()
  9169. await telegram_reaction_poller.aclose()
  9170. github_backup_service.stop_scheduler()
  9171. local_backup_service.stop_scheduler()
  9172. library_trash_service.stop_scheduler()
  9173. archive_purge_service.stop_scheduler()
  9174. obico_detection_service.stop()
  9175. stop_ams_history_recording()
  9176. stop_printer_sensor_history_recording()
  9177. stop_runtime_tracking()
  9178. stop_spoolbuddy_watchdog()
  9179. stop_camera_cleanup()
  9180. stop_connection_watchdog()
  9181. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9182. stop_loop_watchdog()
  9183. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9184. # cleanly rather than waiting on a queue that nothing will ever fill.
  9185. try:
  9186. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9187. await shutdown_all_broadcasters()
  9188. except Exception as e:
  9189. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9190. stop_expected_prints_cleanup()
  9191. stop_auth_cleanup()
  9192. from backend.app.services import announcements as announcements_service
  9193. announcements_service.stop()
  9194. from backend.app.services.printer_media import stop_printer_download_cleanup
  9195. await stop_printer_download_cleanup()
  9196. printer_manager.disconnect_all()
  9197. slot_unlink_grace.reset()
  9198. await close_spoolman_client()
  9199. # Stop all virtual printer services
  9200. await virtual_printer_manager.stop_all()
  9201. await mqtt_smart_plug_service.disconnect(timeout=2)
  9202. await mqtt_relay.disconnect(timeout=2)
  9203. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9204. set_shared_http_client(None)
  9205. set_shared_makerworld_http_client(None)
  9206. set_shared_orca_http_client(None)
  9207. await _shared_cloud_http_client.aclose()
  9208. # Checkpoint WAL (SQLite only) and close all database connections
  9209. from backend.app.core.db_dialect import is_sqlite
  9210. if is_sqlite():
  9211. try:
  9212. async with engine.begin() as conn:
  9213. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9214. logging.info("WAL checkpoint completed")
  9215. except Exception as e:
  9216. logging.warning("WAL checkpoint failed: %s", e)
  9217. await engine.dispose()
  9218. app = FastAPI(
  9219. title=app_settings.app_name,
  9220. description="Archive and manage Bambu Lab 3MF files",
  9221. version=APP_VERSION,
  9222. lifespan=lifespan,
  9223. )
  9224. # =============================================================================
  9225. # Authentication Middleware - Secures ALL API routes by default
  9226. # =============================================================================
  9227. # Public routes that don't require authentication even when auth is enabled
  9228. PUBLIC_API_ROUTES = {
  9229. # Auth routes needed before/during login
  9230. "/api/v1/auth/status",
  9231. "/api/v1/auth/login",
  9232. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9233. # Advanced auth status needed for login page
  9234. "/api/v1/auth/advanced-auth/status",
  9235. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9236. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9237. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9238. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9239. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9240. # OIDC routes that must be reachable without a JWT
  9241. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9242. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9243. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9244. # Connected apps: the app's server swaps a code for the user's identity,
  9245. # authenticated by its client secret rather than a login token.
  9246. "/api/v1/connect/token",
  9247. # Version check for updates (no sensitive data)
  9248. "/api/v1/updates/version",
  9249. # Metrics endpoint handles its own prometheus_token authentication
  9250. "/api/v1/metrics",
  9251. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9252. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9253. # hostname / timezone / locale and the chrony NTP-gate state. The
  9254. # response contains user-set defaults and a public sync flag — no
  9255. # secrets. Without this entry the global auth middleware returns 401
  9256. # before the route handler runs, regardless of the route's own
  9257. # "no auth required" intent.
  9258. "/api/v1/system/appliance",
  9259. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9260. # authenticates with a long-lived ``camwall``-scoped token in the query
  9261. # string — exactly like the camera streams two lists below, and for the same
  9262. # reason (no header to put a JWT in). "Public" here only means the middleware
  9263. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9264. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9265. # plain ``camera_stream`` token does NOT open this door.
  9266. "/api/v1/camwall/printers",
  9267. # Overlay branding: the route enforces overlay-scoped token authentication.
  9268. "/api/v1/overlay-branding/logo",
  9269. }
  9270. # Route prefixes that are public (for routes with dynamic segments)
  9271. PUBLIC_API_PREFIXES = [
  9272. # WebSocket connections handle their own auth
  9273. "/api/v1/ws",
  9274. # OIDC authorize redirects — include provider_id in path
  9275. "/api/v1/auth/oidc/authorize/",
  9276. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9277. # a phone with no session, so no header can carry a JWT — the single-use
  9278. # capability token in the path IS the credential (same reasoning as the
  9279. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9280. # good/reject on the one archive the token was minted for.
  9281. "/api/v1/archives/confirm/",
  9282. ]
  9283. # Route patterns that are public (read-only display data)
  9284. # These are checked with "in path" - needed because browsers load images/videos
  9285. # via <img src> and <video src> which don't include Authorization headers
  9286. PUBLIC_API_PATTERNS = [
  9287. # Thumbnails
  9288. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9289. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9290. # Images and media
  9291. "/photos/", # /archives/{id}/photos/{filename}
  9292. "/project-image/", # /archives/{id}/project-image/{path}
  9293. "/qrcode", # /archives/{id}/qrcode
  9294. "/timelapse", # /archives/{id}/timelapse (video)
  9295. "/cover", # /printers/{id}/cover
  9296. "/icon", # /external-links/{id}/icon
  9297. # Camera (streams loaded via <img> tag)
  9298. "/camera/stream", # /printers/{id}/camera/stream
  9299. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9300. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9301. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9302. # string (same reasoning as the camera streams above — no header to carry a
  9303. # JWT). "Public" only means the middleware steps aside; the route still runs
  9304. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9305. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9306. "/overlay-status", # /printers/{id}/overlay-status
  9307. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9308. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9309. # download token in the URL path instead.
  9310. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9311. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9312. # and these patterns match by substring. Without its own entry the middleware
  9313. # 401s the slicer's header-less request before the route's token check runs,
  9314. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9315. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9316. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9317. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9318. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9319. ]
  9320. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9321. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9322. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9323. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9324. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9325. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9326. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9327. Invalid entries are dropped with a warning rather than failing startup, so
  9328. a typo in one origin doesn't take the whole deployment down.
  9329. """
  9330. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9331. if not raw:
  9332. return ()
  9333. valid: list[str] = []
  9334. for item in raw.split(","):
  9335. candidate = item.strip()
  9336. if not candidate:
  9337. continue
  9338. try:
  9339. parsed = urlparse(candidate)
  9340. except ValueError as e:
  9341. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9342. continue
  9343. if parsed.scheme not in ("http", "https"):
  9344. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9345. continue
  9346. if not parsed.netloc:
  9347. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9348. continue
  9349. if parsed.path and parsed.path != "/":
  9350. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9351. continue
  9352. if parsed.query or parsed.fragment:
  9353. _security_headers_logger.warning(
  9354. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9355. )
  9356. continue
  9357. if "*" in parsed.netloc:
  9358. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9359. continue
  9360. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9361. if valid:
  9362. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9363. return tuple(valid)
  9364. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9365. def _frame_ancestors(default_value: str) -> str:
  9366. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9367. ``default_value`` is the strict directive used when the operator has not
  9368. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9369. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9370. Settings URL builder's preview). When trusted origins
  9371. are configured, ``'self'`` is always included so same-origin embedding never
  9372. breaks even if an operator forgets to add their own origin to the list.
  9373. """
  9374. if _TRUSTED_FRAME_ORIGINS:
  9375. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9376. return f"frame-ancestors {default_value};"
  9377. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9378. # patterns are anchored on the exact emitted name so the relaxed policies
  9379. # below can never apply to any other asset.
  9380. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9381. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9382. # -> /assets/pdf.worker.min-<hash>.js
  9383. # Vite also emits a one-line chunk under the second name that only exports the
  9384. # worker's URL. The page imports it as a module, and a module script is run
  9385. # under the importing document's policy, never its own response's, so it
  9386. # matching as well changes nothing.
  9387. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9388. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9389. @app.middleware("http")
  9390. async def security_headers_middleware(request, call_next):
  9391. """Add standard HTTP security headers to every response."""
  9392. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9393. # changes nothing for Bambuddy's own pages — index.html has no inline
  9394. # scripts since the SW registration moved to /sw-register.js. The reason
  9395. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9396. # script injected into the HTML on the edge, with a fresh hash on every
  9397. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9398. # it clones the same nonce onto its injected <script>, and the inline
  9399. # script passes the policy without us needing 'unsafe-inline'. See
  9400. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9401. csp_nonce = secrets.token_urlsafe(16)
  9402. # Routes that render their own HTML need it too, or their inline script is
  9403. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9404. # one that does: it submits its own form so a verdict still costs one tap.
  9405. request.state.csp_nonce = csp_nonce
  9406. response = await call_next(request)
  9407. response.headers["X-Content-Type-Options"] = "nosniff"
  9408. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9409. # browsers honour CSP frame-ancestors instead, and the legacy
  9410. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9411. # When operators have explicitly allowlisted trusted frame origins (#1191
  9412. # — typically Home Assistant on a different port), drop X-Frame-Options
  9413. # and let the CSP-side frame-ancestors directive govern embedding.
  9414. if not _TRUSTED_FRAME_ORIGINS:
  9415. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9416. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9417. # Content-Security-Policy for the React SPA.
  9418. # Notes:
  9419. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9420. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9421. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9422. # - media-src blob:: timelapse video player uses Blob URLs.
  9423. # - font-src data:: some icon fonts are embedded as data URIs.
  9424. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9425. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9426. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9427. # default CSP would render a blank page.
  9428. response.headers["Content-Security-Policy"] = (
  9429. "default-src 'self'; "
  9430. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9431. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9432. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9433. "connect-src 'self'; "
  9434. "font-src 'self' data: https://fonts.gstatic.com; "
  9435. "worker-src 'self' blob:; "
  9436. "object-src 'none'; "
  9437. "base-uri 'self'; " + _frame_ancestors("'none'")
  9438. )
  9439. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9440. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9441. # its emscripten/embind glue generates invoker functions with `new
  9442. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9443. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9444. # own response — not the document's — so relaxing it here confines
  9445. # eval to that DOM-less worker context. The document policy below
  9446. # stays nonce-strict, and this response header has no effect when the
  9447. # file is merely fetched (a fetch's CSP is enforced against the
  9448. # requesting document, not the resource's own headers).
  9449. response.headers["Content-Security-Policy"] = (
  9450. "default-src 'self'; "
  9451. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9452. "connect-src 'self'; "
  9453. "object-src 'none'; "
  9454. "base-uri 'self'; " + _frame_ancestors("'none'")
  9455. )
  9456. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9457. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9458. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9459. # rule as the STEP worker above: the policy that governs a dedicated
  9460. # worker is the one delivered with its own script, so the wasm compile
  9461. # has to be permitted here rather than on the document. Unlike the STEP
  9462. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9463. response.headers["Content-Security-Policy"] = (
  9464. "default-src 'self'; "
  9465. "script-src 'self' 'wasm-unsafe-eval'; "
  9466. "connect-src 'self'; "
  9467. "object-src 'none'; "
  9468. "base-uri 'self'; " + _frame_ancestors("'none'")
  9469. )
  9470. else:
  9471. # The streaming overlay is embedded same-origin by the URL builder's
  9472. # preview in Settings (#1422), so this branch allows 'self'.
  9473. # Embedding from anywhere else is still refused: 'self'
  9474. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9475. # a clickjacking page on another host is blocked exactly as before.
  9476. # (The overlay draws status over a camera feed and its only interactive
  9477. # element is the logo link, so there is nothing to bait a click into
  9478. # even from a same-origin framer.) Cross-origin embedding of the
  9479. # overlay — Home Assistant on another port — remains what
  9480. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9481. # allowlist in.
  9482. #
  9483. # The connected-app consent page (/connect/authorize) gets the same
  9484. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9485. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9486. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9487. # requires every ancestor to be this origin, so a foreign page -- a
  9488. # sidebar link's site included -- still cannot frame the consent
  9489. # screen to bait a click.
  9490. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9491. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9492. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9493. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9494. # the policy served with their own script, so each gets it in its own
  9495. # branch above and the document policy stays as strict as it was.
  9496. response.headers["Content-Security-Policy"] = (
  9497. "default-src 'self'; "
  9498. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9499. "style-src 'self' 'unsafe-inline'; "
  9500. "img-src 'self' data: blob:; "
  9501. "media-src 'self' blob:; "
  9502. "connect-src 'self' ws: wss:; "
  9503. "font-src 'self' data:; "
  9504. "object-src 'none'; "
  9505. "base-uri 'self'; "
  9506. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9507. )
  9508. if request.url.scheme == "https":
  9509. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9510. return response
  9511. @app.middleware("http")
  9512. async def auth_middleware(request, call_next):
  9513. """Enforce authentication on all API routes when auth is enabled.
  9514. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9515. regardless of whether individual routes have auth dependencies.
  9516. """
  9517. from starlette.responses import JSONResponse
  9518. path = request.url.path
  9519. # Only apply to API routes
  9520. if not path.startswith("/api/"):
  9521. return await call_next(request)
  9522. # Allow public routes
  9523. if path in PUBLIC_API_ROUTES:
  9524. return await call_next(request)
  9525. # Allow public prefixes
  9526. for prefix in PUBLIC_API_PREFIXES:
  9527. if path.startswith(prefix):
  9528. return await call_next(request)
  9529. # Allow public patterns (read-only display data like thumbnails)
  9530. for pattern in PUBLIC_API_PATTERNS:
  9531. if pattern in path:
  9532. return await call_next(request)
  9533. # Check if auth is enabled. Fail CLOSED on any exception during the
  9534. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9535. # an attacker who could force a DB exception (e.g. file-descriptor
  9536. # exhaustion via login flood) bypass auth on every protected endpoint.
  9537. try:
  9538. async with async_session() as db:
  9539. from backend.app.core.auth import is_auth_enabled
  9540. auth_enabled = await is_auth_enabled(db)
  9541. if not auth_enabled:
  9542. # Auth disabled, allow all requests
  9543. return await call_next(request)
  9544. except Exception:
  9545. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9546. return JSONResponse(
  9547. status_code=503,
  9548. content={"detail": "Authentication service temporarily unavailable"},
  9549. )
  9550. # Auth is enabled - require valid token
  9551. auth_header = request.headers.get("Authorization")
  9552. x_api_key = request.headers.get("X-API-Key")
  9553. # Check for API key auth first
  9554. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9555. # API key authentication - let the request through to be validated by route handler
  9556. # API keys are validated per-route since they have different permission levels
  9557. return await call_next(request)
  9558. # Check for JWT auth
  9559. if not auth_header or not auth_header.startswith("Bearer "):
  9560. return JSONResponse(
  9561. status_code=401,
  9562. content={"detail": "Authentication required"},
  9563. headers={"WWW-Authenticate": "Bearer"},
  9564. )
  9565. # Validate JWT token
  9566. import jwt
  9567. try:
  9568. from backend.app.core.auth import (
  9569. ALGORITHM,
  9570. SECRET_KEY,
  9571. _is_token_fresh,
  9572. get_user_by_username,
  9573. is_jti_revoked,
  9574. )
  9575. token = auth_header.replace("Bearer ", "")
  9576. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9577. username = payload.get("sub")
  9578. if not username:
  9579. raise ValueError("No username in token")
  9580. jti = payload.get("jti")
  9581. if not jti:
  9582. raise ValueError("No jti in token")
  9583. iat = payload.get("iat")
  9584. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9585. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9586. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9587. async with async_session() as db:
  9588. if await is_jti_revoked(jti, db):
  9589. return JSONResponse(
  9590. status_code=401,
  9591. content={"detail": "Token has been revoked"},
  9592. headers={"WWW-Authenticate": "Bearer"},
  9593. )
  9594. user = await get_user_by_username(db, username)
  9595. if not user or not user.is_active:
  9596. return JSONResponse(
  9597. status_code=401,
  9598. content={"detail": "User not found or inactive"},
  9599. headers={"WWW-Authenticate": "Bearer"},
  9600. )
  9601. if not _is_token_fresh(iat, user):
  9602. return JSONResponse(
  9603. status_code=401,
  9604. content={"detail": "Token no longer valid"},
  9605. headers={"WWW-Authenticate": "Bearer"},
  9606. )
  9607. except jwt.ExpiredSignatureError:
  9608. return JSONResponse(
  9609. status_code=401,
  9610. content={"detail": "Token has expired"},
  9611. headers={"WWW-Authenticate": "Bearer"},
  9612. )
  9613. except (jwt.InvalidTokenError, ValueError, Exception):
  9614. return JSONResponse(
  9615. status_code=401,
  9616. content={"detail": "Invalid token"},
  9617. headers={"WWW-Authenticate": "Bearer"},
  9618. )
  9619. return await call_next(request)
  9620. @app.middleware("http")
  9621. async def trace_id_middleware(request, call_next):
  9622. """Stamp every HTTP request with a trace ID and echo it back.
  9623. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9624. @app.middleware decorators LIFO, so the last-decorated runs first
  9625. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9626. which means auth-middleware log lines (and every line emitted on the
  9627. way down to and back from the route handler) all carry the same
  9628. trace ID. If we put it before auth, auth's logs would be stamped
  9629. with the *previous* request's ID — useless for correlation.
  9630. Honours an inbound ``X-Trace-Id`` header so callers running their
  9631. own tracing can correlate their span IDs with our log lines, but
  9632. only if the value passes the whitelist gate in
  9633. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9634. rejected (too long, contains control chars, etc.) silently triggers
  9635. a freshly minted server-side ID rather than failing the request.
  9636. The minted (or echoed) ID is set on a ContextVar so that every log
  9637. record emitted during the request — application logs *and* uvicorn's
  9638. access log — carries it via TraceIDFilter, and is also written to
  9639. the ``X-Trace-Id`` response header so clients can pin a server-side
  9640. log search to the exact request they made.
  9641. """
  9642. from backend.app.core.trace import (
  9643. generate_trace_id,
  9644. normalise_inbound_trace_id,
  9645. trace_id_var,
  9646. )
  9647. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9648. trace_id = inbound if inbound is not None else generate_trace_id()
  9649. token = trace_id_var.set(trace_id)
  9650. try:
  9651. response = await call_next(request)
  9652. finally:
  9653. # Reset the ContextVar so a record emitted in a totally
  9654. # unrelated background task that just happens to inherit this
  9655. # context doesn't keep referencing this request's ID forever.
  9656. # In practice ContextVar.reset is best-effort under asyncio
  9657. # task-spawn semantics, but the cost is one attribute write so
  9658. # we may as well do it.
  9659. trace_id_var.reset(token)
  9660. response.headers["X-Trace-Id"] = trace_id
  9661. return response
  9662. # API routes
  9663. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9664. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9665. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9666. app.include_router(users.router, prefix=app_settings.api_prefix)
  9667. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9668. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9669. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  9670. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9671. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9672. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9673. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9674. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9675. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9676. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  9677. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9678. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9679. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9680. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9681. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  9682. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  9683. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  9684. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  9685. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  9686. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  9687. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  9688. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  9689. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  9690. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  9691. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  9692. app.include_router(updates.router, prefix=app_settings.api_prefix)
  9693. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  9694. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  9695. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  9696. app.include_router(camera.router, prefix=app_settings.api_prefix)
  9697. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  9698. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  9699. app.include_router(projects.router, prefix=app_settings.api_prefix)
  9700. app.include_router(library.router, prefix=app_settings.api_prefix)
  9701. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  9702. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  9703. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  9704. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  9705. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  9706. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  9707. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  9708. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  9709. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  9710. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  9711. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  9712. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  9713. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  9714. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  9715. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  9716. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  9717. app.include_router(system.router, prefix=app_settings.api_prefix)
  9718. app.include_router(support.router, prefix=app_settings.api_prefix)
  9719. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  9720. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  9721. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9722. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9723. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9724. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9725. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9726. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9727. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9728. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9729. # Serve static files (React build)
  9730. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9731. # Compressed, and cached for good where Vite hashed the name (#3175).
  9732. app.mount(
  9733. "/assets",
  9734. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  9735. name="assets",
  9736. )
  9737. if (app_settings.static_dir / "img").exists():
  9738. app.mount(
  9739. "/img",
  9740. StaticFiles(directory=app_settings.static_dir / "img"),
  9741. name="img",
  9742. )
  9743. if (app_settings.static_dir / "icons").exists():
  9744. app.mount(
  9745. "/icons",
  9746. StaticFiles(directory=app_settings.static_dir / "icons"),
  9747. name="icons",
  9748. )
  9749. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9750. # falls through to the SPA catch-all and returns index.html, which the
  9751. # browser's font sanitizer rejects ("downloadable font: rejected by
  9752. # sanitizer").
  9753. if (app_settings.static_dir / "fonts").exists():
  9754. app.mount(
  9755. "/fonts",
  9756. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9757. name="fonts",
  9758. )
  9759. @app.get("/")
  9760. async def serve_frontend():
  9761. """Serve the React frontend."""
  9762. index_file = app_settings.static_dir / "index.html"
  9763. if index_file.exists():
  9764. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9765. return {
  9766. "message": "Bambuddy API",
  9767. "docs": "/docs",
  9768. "frontend": "Build and place React app in /static directory",
  9769. }
  9770. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9771. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9772. # forever, but the HTML wrapping it is the only file that knows which hash
  9773. # is current. Without explicit cache-control headers Chromium decides
  9774. # heuristically (typically 10% of the time since Last-Modified) and on
  9775. # long-running kiosks happily serves stale HTML across browser restarts.
  9776. # That stale HTML references an old bundle hash, the old bundle is also
  9777. # in the disk cache, and the user ends up running pre-update JS forever
  9778. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9779. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9780. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9781. @app.get("/health")
  9782. async def health_check():
  9783. """Health check endpoint."""
  9784. return {"status": "healthy"}
  9785. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9786. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9787. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9788. # in deployment debugging.
  9789. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9790. async def serve_manifest():
  9791. """Serve PWA manifest."""
  9792. manifest_file = app_settings.static_dir / "manifest.json"
  9793. if manifest_file.exists():
  9794. return FileResponse(manifest_file, media_type="application/manifest+json")
  9795. return {"error": "Manifest not found"}
  9796. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9797. async def serve_service_worker():
  9798. """Serve service worker."""
  9799. sw_file = app_settings.static_dir / "sw.js"
  9800. if sw_file.exists():
  9801. return FileResponse(
  9802. sw_file,
  9803. media_type="application/javascript",
  9804. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9805. )
  9806. return {"error": "Service worker not found"}
  9807. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9808. async def serve_sw_register():
  9809. """Serve the service-worker registration bootstrap script.
  9810. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9811. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9812. """
  9813. reg_file = app_settings.static_dir / "sw-register.js"
  9814. if reg_file.exists():
  9815. return FileResponse(reg_file, media_type="application/javascript")
  9816. return {"error": "sw-register.js not found"}
  9817. # ── GCode viewer static files ────────────────────────────────────────────────
  9818. # Catch-all route for React Router (must be last)
  9819. @app.get("/{full_path:path}")
  9820. async def serve_spa(full_path: str):
  9821. """Serve React app for client-side routing."""
  9822. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9823. if full_path.startswith("api/"):
  9824. from fastapi import HTTPException
  9825. raise HTTPException(status_code=404, detail="Not found")
  9826. index_file = app_settings.static_dir / "index.html"
  9827. if index_file.exists():
  9828. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9829. return {"error": "Frontend not built"}