main.py 482 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import secrets
  8. import time
  9. from contextlib import asynccontextmanager
  10. from datetime import datetime, timedelta, timezone
  11. from logging.handlers import RotatingFileHandler
  12. from pathlib import Path, PurePosixPath
  13. from urllib.parse import urlparse
  14. from fastapi import FastAPI
  15. from fastapi.responses import FileResponse
  16. from fastapi.staticfiles import StaticFiles
  17. from sqlalchemy import delete, or_, select, text
  18. from backend.app.api.routes import (
  19. ams_history,
  20. api_keys,
  21. archive_purge,
  22. archives,
  23. auth,
  24. bug_report,
  25. camera,
  26. camwall,
  27. cloud,
  28. discovery,
  29. external_links,
  30. filaments,
  31. finance,
  32. firmware,
  33. github_backup,
  34. groups,
  35. ha_sensors,
  36. inventory,
  37. kprofiles,
  38. labels,
  39. library,
  40. library_tags,
  41. library_trash,
  42. library_variants,
  43. local_backup,
  44. local_presets,
  45. location_ha_sensors,
  46. maintenance,
  47. makerworld,
  48. metrics,
  49. mfa,
  50. notification_templates,
  51. notifications,
  52. obico,
  53. orca_cloud,
  54. pending_uploads,
  55. pipeline_runs,
  56. print_log,
  57. print_queue,
  58. printer_sensor_history,
  59. printers,
  60. projects,
  61. scheduled_dryings,
  62. settings as settings_routes,
  63. slice_jobs,
  64. slicer_pipelines,
  65. slicer_presets,
  66. smart_plugs,
  67. sponsor_prompt,
  68. spoolbuddy,
  69. spoolman,
  70. spoolman_inventory,
  71. support,
  72. system,
  73. updates,
  74. user_notifications,
  75. users,
  76. virtual_printers,
  77. webhook,
  78. websocket,
  79. )
  80. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  81. from backend.app.api.routes.support import init_debug_logging
  82. from backend.app.core.config import APP_VERSION, settings as app_settings
  83. from backend.app.core.database import async_session, engine, init_db
  84. from backend.app.core.tasks import spawn_background_task
  85. from backend.app.core.websocket import ws_manager
  86. from backend.app.services import print_dispatch_context
  87. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  88. from backend.app.services.archive_purge import archive_purge_service
  89. from backend.app.services.bambu_ftp import (
  90. FileNotOnPrinterError,
  91. cache_3mf_download,
  92. clear_3mf_cache,
  93. download_file_async,
  94. download_file_try_paths_async,
  95. ftps_handshake_blocked,
  96. get_cached_3mf,
  97. get_ftp_retry_settings,
  98. normalize_3mf_name,
  99. with_ftp_retry,
  100. )
  101. from backend.app.services.bambu_mqtt import PrinterState
  102. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  103. from backend.app.services.github_backup import github_backup_service
  104. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  105. from backend.app.services.homeassistant import homeassistant_service
  106. from backend.app.services.library_trash import library_trash_service
  107. from backend.app.services.local_backup import local_backup_service
  108. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  109. from backend.app.services.mqtt_relay import mqtt_relay
  110. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  111. from backend.app.services.notification_service import notification_service
  112. from backend.app.services.obico_detection import obico_detection_service
  113. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  114. from backend.app.services.print_scheduler import scheduler as print_scheduler
  115. from backend.app.services.print_storage import (
  116. REASON_FTP_TRANSFER_FAILED,
  117. REASON_FTPS_COOLOFF,
  118. external_storage_present,
  119. ftp_probe_paths,
  120. print_file_reachable_over_ftp,
  121. )
  122. from backend.app.services.printer_manager import (
  123. init_printer_connections,
  124. parse_plate_id,
  125. printer_manager,
  126. printer_state_to_dict,
  127. resolve_plate_id,
  128. )
  129. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  130. from backend.app.services.slot_nozzle import (
  131. nozzle_diameter_for_extruder,
  132. nozzle_flow_for_extruder,
  133. resolve_slot_nozzle,
  134. )
  135. from backend.app.services.smart_plug_manager import smart_plug_manager
  136. from backend.app.services.spool_assignment_notifications import (
  137. notify_missing_spool_assignments_on_print_start,
  138. )
  139. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  140. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  141. from backend.app.services.spoolman_tracking import (
  142. cleanup_tracking as _cleanup_spoolman_tracking,
  143. report_usage as _report_spoolman_usage,
  144. store_print_data as _store_spoolman_print_data,
  145. )
  146. from backend.app.services.tasmota import tasmota_service
  147. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  148. from backend.app.utils.filament_types import printer_filament_type
  149. from backend.app.utils.fts_routing import extruder_for_inlet
  150. from backend.app.utils.local_time import utcnow_naive
  151. from backend.app.utils.print_jobs import is_internal_printer_job
  152. # =============================================================================
  153. # Dependency Check - runs before other imports to give helpful error messages
  154. # =============================================================================
  155. def _start_error_server(missing_packages: list):
  156. """Start a minimal HTTP server to display dependency errors in browser."""
  157. import os
  158. import signal
  159. from http.server import BaseHTTPRequestHandler, HTTPServer
  160. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  161. html = f"""<!DOCTYPE html>
  162. <html>
  163. <head>
  164. <title>Bambuddy - Setup Required</title>
  165. <style>
  166. body {{
  167. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  168. background: #0f172a; color: #e2e8f0;
  169. display: flex; justify-content: center; align-items: center;
  170. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  171. }}
  172. .container {{
  173. background: #1e293b; border-radius: 12px; padding: 40px;
  174. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  175. }}
  176. h1 {{ color: #f87171; margin-bottom: 10px; }}
  177. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  178. .packages {{
  179. background: #0f172a; border-radius: 8px; padding: 20px;
  180. margin: 20px 0; text-align: left;
  181. }}
  182. .packages ul {{ margin: 0; padding-left: 20px; }}
  183. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  184. .command {{
  185. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  186. margin: 15px 0; font-family: monospace; color: #4ade80;
  187. text-align: left; overflow-x: auto;
  188. }}
  189. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  190. </style>
  191. </head>
  192. <body>
  193. <div class="container">
  194. <h1>Setup Required</h1>
  195. <h2>Missing Python packages</h2>
  196. <div class="packages"><ul>{packages_html}</ul></div>
  197. <p>To fix, run this command on your server:</p>
  198. <div class="command">pip install -r requirements.txt</div>
  199. <p>Or if using a virtual environment:</p>
  200. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  201. <p class="note">After installing, restart Bambuddy:<br>
  202. <code>sudo systemctl restart bambuddy</code></p>
  203. </div>
  204. </body>
  205. </html>"""
  206. class ErrorHandler(BaseHTTPRequestHandler):
  207. def do_GET(self):
  208. self.send_response(503)
  209. self.send_header("Content-type", "text/html")
  210. self.end_headers()
  211. self.wfile.write(html.encode())
  212. def log_message(self, format, *args):
  213. print(f"[Error Server] {args[0]}")
  214. port = int(os.environ.get("PORT", 8000))
  215. print(f"\nStarting error server on http://0.0.0.0:{port}")
  216. print("Visit this URL in your browser to see the error details.\n")
  217. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  218. def shutdown(signum, frame):
  219. print("\nShutting down error server...")
  220. raise SystemExit(0)
  221. signal.signal(signal.SIGTERM, shutdown)
  222. signal.signal(signal.SIGINT, shutdown)
  223. server.serve_forever()
  224. def check_dependencies():
  225. """Check that all required packages are installed."""
  226. missing = []
  227. # Map of import name -> package name (for pip install)
  228. required = {
  229. "jwt": "PyJWT",
  230. "fastapi": "fastapi",
  231. "uvicorn": "uvicorn",
  232. "sqlalchemy": "sqlalchemy",
  233. "aiosqlite": "aiosqlite",
  234. "pydantic": "pydantic",
  235. "paho.mqtt": "paho-mqtt",
  236. }
  237. for module, package in required.items():
  238. try:
  239. __import__(module)
  240. except ImportError:
  241. missing.append(package)
  242. if missing:
  243. print("\n" + "=" * 60)
  244. print("ERROR: Missing required Python packages!")
  245. print("=" * 60)
  246. print(f"\nMissing packages: {', '.join(missing)}")
  247. print("\nTo fix, run:")
  248. print(" pip install -r requirements.txt")
  249. print("\nOr if using a virtual environment:")
  250. print(" ./venv/bin/pip install -r requirements.txt")
  251. print("=" * 60 + "\n")
  252. _start_error_server(missing)
  253. check_dependencies()
  254. # =============================================================================
  255. # Import settings first for logging configuration
  256. # Configure logging based on settings
  257. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  258. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  259. log_level = getattr(logging, log_level_str, logging.INFO)
  260. # Trace ID column ([-] when no request scope is active — startup, MQTT
  261. # callbacks, scheduled tasks not chained from a request — so the column
  262. # stays visually aligned and missing values are obvious in grep). See
  263. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  264. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  265. # Create root logger
  266. root_logger = logging.getLogger()
  267. root_logger.setLevel(log_level)
  268. # Trace-ID injection: this filter populates record.trace_id from the
  269. # per-request ContextVar so the format string above can reference it.
  270. # Attached to each HANDLER (not the root logger) because Python's
  271. # logging semantics only invoke a logger's filters on records that
  272. # *originated* at that logger — records propagated up from child
  273. # loggers (every named logger in the app) never trigger root's filter.
  274. # Putting it on the handlers means every record any handler emits gets
  275. # trace_id injected just before the formatter runs, regardless of which
  276. # logger created the record. Without this, the formatter raises
  277. # KeyError on every child-logger record and the record is silently
  278. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  279. # partially" bug we hit. See backend/app/core/trace.py for the
  280. # ContextVar the filter reads.
  281. from backend.app.core.trace import TraceIDFilter
  282. _trace_id_filter = TraceIDFilter()
  283. # Console handler - always enabled
  284. console_handler = logging.StreamHandler()
  285. console_handler.setLevel(log_level)
  286. console_handler.setFormatter(logging.Formatter(log_format))
  287. console_handler.addFilter(_trace_id_filter)
  288. root_logger.addHandler(console_handler)
  289. # File handler - only in production or if explicitly enabled
  290. if app_settings.log_to_file:
  291. log_file = app_settings.log_dir / "bambuddy.log"
  292. file_handler = RotatingFileHandler(
  293. log_file,
  294. maxBytes=app_settings.log_max_bytes,
  295. backupCount=app_settings.log_backup_count,
  296. encoding="utf-8",
  297. )
  298. file_handler.setLevel(log_level)
  299. file_handler.setFormatter(logging.Formatter(log_format))
  300. file_handler.addFilter(_trace_id_filter)
  301. root_logger.addHandler(file_handler)
  302. logging.info("Logging to file: %s", log_file)
  303. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  304. # access logger with propagate=False by default, so without this attach
  305. # there is no on-disk record of which endpoint triggered a server-state
  306. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  307. # for exactly this reason. Filtered to write methods only
  308. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  309. # frontend don't churn the rotation window faster than it's useful.
  310. from backend.app.core.logging_filters import (
  311. CancelledPoolNoiseFilter,
  312. WriteRequestsOnlyFilter,
  313. )
  314. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  315. uvicorn_access_logger.addHandler(file_handler)
  316. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  317. # Uvicorn's access logger has propagate=False (its own default), so the
  318. # root-attached TraceIDFilter never sees these records. Attach a
  319. # second instance directly so HTTP access lines carry the same trace
  320. # ID column as the application logs they correlate with.
  321. uvicorn_access_logger.addFilter(TraceIDFilter())
  322. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  323. # BaseHTTPMiddleware cancelling the inner task scope on client
  324. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  325. # underlying transaction leak; this filter only suppresses the residual
  326. # log records that pre-existing pools still emit during their cleanup.
  327. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  328. # Reduce noise from third-party libraries in production
  329. if not app_settings.debug:
  330. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  331. logging.getLogger("httpcore").setLevel(logging.WARNING)
  332. logging.getLogger("httpx").setLevel(logging.WARNING)
  333. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  334. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  335. # Track active prints: {(printer_id, filename): archive_id}
  336. _active_prints: dict[tuple[int, str], int] = {}
  337. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  338. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  339. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  340. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  341. # instead of running its own grab-now chain when present, so the finish photo
  342. # captures the better-framed pre-bed-drop moment without us having to force
  343. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  344. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  345. #
  346. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  347. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  348. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  349. # bank and the others are not — so the consumer can't tell them apart and
  350. # must not rotate again.
  351. _stage22_finish_frames: dict[int, bytes] = {}
  352. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  353. # `finally` block (whether it captured a frame or not). The consumer in
  354. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  355. # so the FINISH-state fallback path — where moment and completion are dispatched
  356. # back-to-back — doesn't race past the producer with an empty pop, and the
  357. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  358. # grab (Bambu printers allow only one RTSP client at a time).
  359. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  360. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  361. # layer-change and on print-progress advances (#2547) while the model is still
  362. # printing, then consumed by the FINISH-state finish-photo path when the
  363. # dispatcher recorded that it injected End G-code into this print. Bambu
  364. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  365. # plate-swap) has run, so a live grab there would capture the swapped/empty
  366. # plate.
  367. #
  368. # The load-bearing property: both drivers are print telemetry that stops before
  369. # the End G-code executes — no further layer_num increases, and mc_percent
  370. # freezes — so the last banked frame is always the finished print before the
  371. # swap. Anything added as a third driver must hold that same property.
  372. _inprint_frame_bank: dict[int, bytes] = {}
  373. # Monotonic timestamp of the last banked frame per printer — throttles banking
  374. # so tall prints don't add a camera grab on every layer.
  375. _inprint_frame_bank_ts: dict[int, float] = {}
  376. # Minimum seconds between banked frames, except the final object layer which
  377. # always refreshes for the best framing.
  378. _INPRINT_BANK_MIN_INTERVAL = 25.0
  379. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  380. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  381. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  382. # the first connected status update for that connection; transitions back
  383. # to False whenever we observe `state.connected = False` so the next
  384. # reconnect re-arms reconciliation. Keyed by printer_id.
  385. _printer_reconciled_since_connect: dict[int, bool] = {}
  386. # Same edge, same keying, for priming the printer's calibration table exactly
  387. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  388. # is otherwise filled only when someone opens the Profiles page or Configure
  389. # Slot, when a GitHub backup runs, or when the printer happens to answer
  390. # somebody else's query on the report topic. Until then the AMS slot card has
  391. # no K value to show on the printers whose trays carry none of their own
  392. # (#2854 — H2-series report cali_idx and nothing more).
  393. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  394. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  395. # {(printer_id, filename): archive_id}
  396. _expected_prints: dict[tuple[int, str], int] = {}
  397. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  398. # Used by usage tracker to map 3MF slots to physical AMS trays
  399. _print_ams_mappings: dict[int, list[int]] = {}
  400. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  401. _print_cost_center_ids: dict[int, int] = {}
  402. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  403. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  404. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  405. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  406. # for the queue path. Cleared on print completion or TTL eviction.
  407. _print_plate_ids: dict[int, int] = {}
  408. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  409. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  410. _last_progress_milestone: dict[int, int] = {}
  411. # Track whether first layer complete notification has been sent for current print
  412. _first_layer_notified: dict[int, bool] = {}
  413. # Track whether we already sent a kill-switch stop for the current unauthorized print
  414. _unauthorized_print_kill_sent: set[int] = set()
  415. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  416. # lookup briefly so an unknown active print does not query the database on
  417. # every status frame. A short TTL keeps settings changes responsive.
  418. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  419. _kill_switch_setting_cache: tuple[bool, float] | None = None
  420. # Provider notification started when the kill switch stops a print. The later
  421. # MQTT print-complete callback awaits this task and only sends its regular
  422. # provider notification when the immediate attempt failed.
  423. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  424. # Track HMS errors that have been notified: {printer_id: set of error codes}
  425. # This prevents sending duplicate notifications for the same error
  426. _notified_hms_errors: dict[int, set[str]] = {}
  427. # Track when HMS errors were last seen: {printer_id: timestamp}
  428. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  429. _hms_last_seen: dict[int, float] = {}
  430. _HMS_CLEAR_GRACE_SECONDS = 30.0
  431. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  432. # Used for snapshot-diff detection at print completion
  433. _timelapse_baselines: dict[int, set[str]] = {}
  434. # Track printers waiting for bed to cool after print completion.
  435. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  436. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  437. _bed_cool_waiters: dict[int, dict] = {}
  438. # Track printers where the user explicitly stopped the print from the queue UI.
  439. # When on_print_complete fires with status "failed" for these printers we treat it
  440. # as "cancelled" (stopped by user) so the correct notification email is sent.
  441. _user_stopped_printers: set[int] = set()
  442. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  443. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  444. # holds the previous observation so we only fire on the True → False edge (a
  445. # False → False repeat doesn't notify; an initial False at startup doesn't
  446. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  447. # holds the per-printer pending asyncio task that fires the notification
  448. # after a debounce window — cancelled if the printer reconnects before the
  449. # window elapses, so transient MQTT blips don't flood the user.
  450. _printer_last_connected: dict[int, bool] = {}
  451. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  452. # Debounce: a printer must stay offline this long before we notify. Sized
  453. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  454. # so a single stale-trigger cooldown isn't enough to fire — only a real
  455. # offline that survives one reconnect attempt notifies.
  456. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  457. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  458. # when status="failed" to label the print's failure_reason in archives.
  459. #
  460. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  461. # which is wrong on two counts:
  462. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  463. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  464. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  465. # the public wiki) as part of its user-cancel sequence. Matching on the module
  466. # alone caused user-cancellations to be archived as "Layer shift" failures.
  467. # We now match by full short code only — anything not in this map leaves
  468. # failure_reason=None rather than guessing.
  469. # Values are the canonical camelCase failure-reason keys, NOT display labels
  470. # (issue #2974). The vocabulary is enforced on writes by
  471. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  472. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  473. # Statistics breakdown. Storing a label here instead put a second spelling of
  474. # the same cause into one column: the Failure Analysis widget groups on the raw
  475. # value, so a print the backend classified and an identical one a user
  476. # classified counted as two different reasons, and the label form could never
  477. # be translated because there was no key for ``t()`` to resolve.
  478. _HMS_FAILURE_REASONS: dict[str, str] = {
  479. # Layer shift / step loss
  480. "0300_4057": "layerShift",
  481. "0300_4068": "layerShift",
  482. "0300_800C": "layerShift",
  483. # Filament runout (printer-side & per-AMS-slot)
  484. "0300_8004": "filamentRunout",
  485. "0700_8011": "filamentRunout",
  486. "0701_8011": "filamentRunout",
  487. "0702_8011": "filamentRunout",
  488. "0703_8011": "filamentRunout",
  489. "0704_8011": "filamentRunout",
  490. "0705_8011": "filamentRunout",
  491. "0706_8011": "filamentRunout",
  492. "0707_8011": "filamentRunout",
  493. "07FF_8011": "filamentRunout",
  494. # Clogged nozzle / extruder
  495. "0300_4006": "cloggedNozzle",
  496. "0300_8016": "cloggedNozzle",
  497. "0300_801C": "cloggedNozzle",
  498. "0700_8003": "cloggedNozzle",
  499. "0700_8007": "cloggedNozzle",
  500. "0700_8013": "cloggedNozzle",
  501. "0701_8003": "cloggedNozzle",
  502. "0701_8007": "cloggedNozzle",
  503. "0701_8013": "cloggedNozzle",
  504. "0702_8003": "cloggedNozzle",
  505. }
  506. def _hms_short_code(attr: int, code: int | str) -> str:
  507. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  508. if isinstance(code, str):
  509. code_int = int(code.replace("0x", ""), 16) if code else 0
  510. else:
  511. code_int = int(code or 0)
  512. attr_int = int(attr or 0)
  513. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  514. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  515. """Derive a human-readable failure_reason for an archived print.
  516. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  517. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  518. no HMS code matches (don't guess — null is honest).
  519. """
  520. if status in ("aborted", "cancelled"):
  521. return "userCancelled"
  522. if status != "failed":
  523. return None
  524. for err in hms_errors or []:
  525. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  526. if short_code in _HMS_FAILURE_REASONS:
  527. return _HMS_FAILURE_REASONS[short_code]
  528. return None
  529. # Track created_by_id for expected prints so the user email can be sent even when
  530. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  531. # {(printer_id, filename): created_by_id}
  532. _expected_print_creators: dict[tuple[int, str], int] = {}
  533. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  534. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  535. # updates for the same printer in quick succession (~30 ms apart, observed in
  536. # the wild on H2D + dual AMS).
  537. #
  538. # Without this serialisation, two concurrent on_ams_change callbacks each read
  539. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  540. # the second commit hits
  541. # IntegrityError: duplicate key value violates unique constraint
  542. # "spool_assignment_printer_id_ams_id_tray_id_key"
  543. # SQLite's WAL serial-write semantics had been silently swallowing the race
  544. # until optional Postgres support landed (asyncpg allows true concurrent
  545. # transactions and surfaces the constraint violation).
  546. #
  547. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  548. # assign) are inside the lock. The Spoolman sync block further down stays
  549. # concurrent because it's network-bound and idempotent.
  550. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  551. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  552. """Return the per-printer assignment lock, creating it on first use."""
  553. lock = _ams_assignment_locks.get(printer_id)
  554. if lock is None:
  555. lock = asyncio.Lock()
  556. _ams_assignment_locks[printer_id] = lock
  557. return lock
  558. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  559. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  560. # tag tuple changes for the slot. Cleared when the slot is reported empty
  561. # so remove + reinsert reliably re-prompts the UI.
  562. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  563. async def _broadcast_unknown_tag(
  564. *,
  565. printer_id: int,
  566. ams_id: int,
  567. tray_id: int,
  568. tag_uid: str,
  569. tray_uuid: str,
  570. tray_type: str | None = None,
  571. tray_color: str | None = None,
  572. tray_sub_brands: str | None = None,
  573. tray_count: int | None = None,
  574. ) -> None:
  575. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  576. _logger = logging.getLogger(__name__)
  577. slot_key = (ams_id, tray_id)
  578. tag_key = (tag_uid or "", tray_uuid or "")
  579. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  580. if per_printer.get(slot_key) == tag_key:
  581. _logger.debug(
  582. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  583. printer_id,
  584. ams_id,
  585. tray_id,
  586. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  587. )
  588. return
  589. _logger.info(
  590. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  591. printer_id,
  592. ams_id,
  593. tray_id,
  594. tray_type,
  595. tray_color,
  596. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  597. )
  598. # Broadcast first; only commit the dedup if the WS write succeeds.
  599. # If broadcast raises, the next MQTT push retries instead of being
  600. # permanently silenced by a poisoned dedup entry.
  601. await ws_manager.broadcast(
  602. {
  603. "type": "unknown_tag",
  604. "printer_id": printer_id,
  605. "ams_id": ams_id,
  606. "tray_id": tray_id,
  607. "tag_uid": tag_uid,
  608. "tray_uuid": tray_uuid,
  609. "tray_type": tray_type,
  610. "tray_color": tray_color,
  611. "tray_sub_brands": tray_sub_brands,
  612. "tray_count": tray_count,
  613. }
  614. )
  615. per_printer[slot_key] = tag_key
  616. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  617. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  618. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  619. if per_printer is None:
  620. return
  621. per_printer.pop((ams_id, tray_id), None)
  622. # TTL for expected-print entries: evict registrations older than this to prevent
  623. # unbounded growth when a print is registered but never starts (e.g. printer
  624. # disconnect, app restart, print started from the printer panel).
  625. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  626. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  627. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  628. # Cleanup loop interval
  629. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  630. _expected_prints_cleanup_task: asyncio.Task | None = None
  631. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  632. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  633. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  634. possible_keys: list[tuple[int, str]] = []
  635. filename = (state.gcode_file or state.current_print or "").strip()
  636. subtask_name = (state.subtask_name or "").strip()
  637. if subtask_name:
  638. possible_keys.append((printer_id, subtask_name))
  639. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  640. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  641. if filename:
  642. base_name = filename.rsplit("/", 1)[-1]
  643. if base_name.endswith(".gcode.3mf"):
  644. root_name = base_name[: -len(".gcode.3mf")]
  645. possible_keys.append((printer_id, root_name))
  646. possible_keys.append((printer_id, base_name))
  647. possible_keys.append((printer_id, f"{root_name}.gcode"))
  648. possible_keys.append((printer_id, f"{root_name}.3mf"))
  649. elif base_name.endswith(".3mf"):
  650. root_name = base_name[: -len(".3mf")]
  651. possible_keys.append((printer_id, root_name))
  652. possible_keys.append((printer_id, base_name))
  653. elif base_name.endswith(".gcode"):
  654. root_name = base_name[: -len(".gcode")]
  655. possible_keys.append((printer_id, root_name))
  656. possible_keys.append((printer_id, f"{root_name}.3mf"))
  657. possible_keys.append((printer_id, base_name))
  658. else:
  659. possible_keys.append((printer_id, base_name))
  660. possible_keys.append((printer_id, f"{base_name}.3mf"))
  661. return possible_keys
  662. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  663. """Check the cheap, process-local print ownership signals."""
  664. if printer_manager.get_current_print_user(printer_id):
  665. return True
  666. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  667. async def _is_printer_kill_switch_enabled_cached() -> bool:
  668. """Return the kill-switch setting without querying on every MQTT frame."""
  669. global _kill_switch_setting_cache
  670. now = time.monotonic()
  671. if _kill_switch_setting_cache is not None:
  672. enabled, expires_at = _kill_switch_setting_cache
  673. if now < expires_at:
  674. return enabled
  675. async with async_session() as db:
  676. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  677. enabled = await is_printer_kill_switch_enabled(db)
  678. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  679. return enabled
  680. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  681. """Resolve whether the current print was started by Bambuddy.
  682. ``None`` means identity is not yet safe to decide. The kill switch must
  683. defer in that case: stopping a print is irreversible, and the first status
  684. frames after a restart may arrive before all subtask fields are populated.
  685. """
  686. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  687. return True
  688. possible_keys = _build_status_print_keys(printer_id, state)
  689. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  690. # is on disk. subtask_id is minted per print and pins the answer to the job
  691. # actually running, rather than to an unrelated one that reuses a filename.
  692. raw_subtask_id = getattr(state, "subtask_id", None)
  693. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  694. if subtask_id in ("", "0"):
  695. return None
  696. from backend.app.models.archive import PrintArchive
  697. result = await db.execute(
  698. select(PrintArchive)
  699. .where(
  700. PrintArchive.printer_id == printer_id,
  701. PrintArchive.status == "printing",
  702. PrintArchive.subtask_id == subtask_id,
  703. )
  704. .order_by(PrintArchive.created_at.desc())
  705. .limit(1)
  706. )
  707. archive = result.scalar_one_or_none()
  708. # An archive row on its own proves nothing: `on_print_start` archives every
  709. # print it observes, including ones started from Bambu Studio or Handy, and
  710. # stamps them with the same status and subtask_id. Authorizing on its mere
  711. # existence would disable the kill switch the moment the 3MF finishes
  712. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  713. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  714. # (carried over from the queue item that started it).
  715. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  716. # Rehydrate the fast in-memory path for subsequent status frames. Include
  717. # both the archive filename and every normalized key reported by MQTT.
  718. _active_prints[(printer_id, archive.filename)] = archive.id
  719. for key in possible_keys:
  720. _active_prints[key] = archive.id
  721. return True
  722. # No dispatch marker. Before calling this someone else's print, check whether
  723. # Bambuddy has a job of its own running on this printer: a library-file
  724. # dispatch has no archive at send time, and an archive created seconds later
  725. # by `on_print_start` carries neither marker. The queue row, which the
  726. # scheduler commits to status="printing" before the MQTT send, is the one
  727. # durable record every Bambuddy print has. It cannot be tied to this
  728. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  729. # print is irreversible, and refusing to act costs nothing but a log line.
  730. from backend.app.models.print_queue import PrintQueueItem
  731. dispatched_here = await db.scalar(
  732. select(PrintQueueItem.id)
  733. .where(
  734. PrintQueueItem.printer_id == printer_id,
  735. PrintQueueItem.status == "printing",
  736. )
  737. .limit(1)
  738. )
  739. if dispatched_here is not None:
  740. return None
  741. return False
  742. async def _send_kill_switch_provider_notification(
  743. printer_id: int,
  744. printer_name: str,
  745. data: dict,
  746. ) -> bool:
  747. """Send the immediate print-stopped provider notification.
  748. Returning a success flag lets the normal MQTT completion path retry when
  749. this early notification could not be delivered.
  750. """
  751. logger = logging.getLogger(__name__)
  752. try:
  753. async with async_session() as db:
  754. await notification_service.on_print_complete(
  755. printer_id,
  756. printer_name,
  757. "stopped",
  758. data,
  759. db,
  760. )
  761. return True
  762. except Exception as e:
  763. logger.warning(
  764. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  765. printer_id,
  766. e,
  767. )
  768. return False
  769. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  770. """Wait for an immediate kill-switch notification, if one was scheduled."""
  771. if task is None:
  772. return False
  773. try:
  774. return await task
  775. except Exception as e:
  776. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  777. return False
  778. async def _get_plug_energy(plug, db) -> dict | None:
  779. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  780. For HA plugs, configures the service with current settings from DB.
  781. For MQTT plugs, returns data from the subscription service.
  782. For REST plugs, polls the status URL with JSON path extraction.
  783. """
  784. if plug.plug_type == "homeassistant":
  785. from backend.app.api.routes.settings import get_homeassistant_settings
  786. ha_settings = await get_homeassistant_settings(db)
  787. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  788. return await homeassistant_service.get_energy(plug)
  789. elif plug.plug_type == "mqtt":
  790. # MQTT plugs report "today" energy, not lifetime total
  791. # For per-print tracking, we use "today" as the counter (resets at midnight)
  792. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  793. if mqtt_data:
  794. return {
  795. "power": mqtt_data.power,
  796. "today": mqtt_data.energy,
  797. "total": mqtt_data.energy, # Use today as total for per-print calculations
  798. }
  799. return None
  800. elif plug.plug_type == "rest":
  801. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  802. return await rest_smart_plug_service.get_energy(plug)
  803. else:
  804. return await tasmota_service.get_energy(plug)
  805. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  806. """Capture the smart plug lifetime counter on the archive at print start.
  807. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  808. tracking survives a backend restart mid-print. The print-end handler reads
  809. this value back from the DB and computes the delta against the current
  810. plug counter.
  811. """
  812. _logger = logging.getLogger(__name__)
  813. try:
  814. candidates = await energy_plug_candidates(db, printer_id)
  815. if not candidates:
  816. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  817. return False
  818. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  819. if selected is None:
  820. # Naming the plugs matters here: with several linked to one printer
  821. # this is the difference between "the meter is offline" and "you
  822. # linked only accessories" (#2859).
  823. _logger.warning(
  824. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  825. printer_id,
  826. archive.id,
  827. ", ".join(plug.name for plug in candidates),
  828. )
  829. return False
  830. plug, energy = selected
  831. archive.energy_start_kwh = float(energy["total"])
  832. await db.commit()
  833. _logger.info(
  834. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  835. f" ({context})" if context else "",
  836. archive.id,
  837. plug.name,
  838. energy["total"],
  839. )
  840. return True
  841. except Exception as e:
  842. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  843. return False
  844. def register_expected_print(
  845. printer_id: int,
  846. filename: str,
  847. archive_id: int,
  848. ams_mapping: list[int] | None = None,
  849. created_by_id: int | None = None,
  850. cost_center_id: int | None = None,
  851. plate_id: int | None = None,
  852. ):
  853. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  854. # Store with multiple filename variations to catch different naming patterns
  855. _expected_prints[(printer_id, filename)] = archive_id
  856. # Also store without .3mf extension if present
  857. if filename.endswith(".3mf"):
  858. base = filename[:-4]
  859. _expected_prints[(printer_id, base)] = archive_id
  860. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  861. # Store AMS mapping for usage tracking at print completion
  862. if ams_mapping is not None:
  863. _print_ams_mappings[archive_id] = ams_mapping
  864. if cost_center_id is not None:
  865. _print_cost_center_ids[archive_id] = cost_center_id
  866. # Store plate_id for usage tracking when this is a single-plate dispatch from
  867. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  868. # file's filament total to the spool instead of just the printed plate (#1697).
  869. if plate_id is not None:
  870. _print_plate_ids[archive_id] = plate_id
  871. # Store created_by_id so the user start email can be sent even when the archive
  872. # itself has no created_by_id (e.g. library-file-based queue prints)
  873. if created_by_id is not None:
  874. _expected_print_creators[(printer_id, filename)] = created_by_id
  875. if filename.endswith(".3mf"):
  876. base = filename[:-4]
  877. _expected_print_creators[(printer_id, base)] = created_by_id
  878. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  879. # Record registration time for TTL-based eviction
  880. _registered_at = time.monotonic()
  881. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  882. if filename.endswith(".3mf"):
  883. base = filename[:-4]
  884. _expected_print_registered_at[(printer_id, base)] = _registered_at
  885. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  886. logging.getLogger(__name__).info(
  887. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  888. )
  889. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  890. """Undo :func:`register_expected_print` when the print never went out.
  891. Registration has to happen *before* the MQTT print command, because the
  892. printer can report the print before the line after the send executes. So
  893. every path that registers and then fails to send — a cancel winning the
  894. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  895. between — leaves an expectation for a print that will never arrive.
  896. The TTL sweep evicts those after two hours, which is far longer than it
  897. takes a user to react to a failed dispatch by pressing print again: that
  898. reprint would be folded into the *old* archive and take the stale
  899. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  900. Mirrors the sweep's rules, including the one that is easy to get wrong:
  901. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  902. file, so they may only be dropped once no live key still points at that
  903. archive.
  904. """
  905. keys = [(printer_id, filename)]
  906. if filename.endswith(".3mf"):
  907. base = filename[:-4]
  908. keys.append((printer_id, base))
  909. keys.append((printer_id, f"{base}.gcode"))
  910. removed = False
  911. for key in keys:
  912. if _expected_prints.pop(key, None) is not None:
  913. removed = True
  914. _expected_print_creators.pop(key, None)
  915. _expected_print_registered_at.pop(key, None)
  916. if archive_id not in set(_expected_prints.values()):
  917. _print_ams_mappings.pop(archive_id, None)
  918. _print_plate_ids.pop(archive_id, None)
  919. if removed:
  920. logging.getLogger(__name__).info(
  921. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  922. printer_id,
  923. filename,
  924. archive_id,
  925. )
  926. def _compute_run_filament_grams(
  927. status: str,
  928. archive_filament_used_grams: float | None,
  929. progress: float | int | None,
  930. usage_results: list[dict] | None,
  931. ) -> float | None:
  932. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  933. Priority for every status:
  934. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  935. weight delta — same source that drives "Total Consumed" on the
  936. Inventory page, so Stats and Inventory totals stay aligned).
  937. 2. For ``completed``: the slicer estimate (no tracker available, fall
  938. back to the canonical "this print used X" value).
  939. 3. For partial statuses: ``estimate * progress%``.
  940. 4. ``None`` if nothing is known.
  941. """
  942. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  943. if tracked_grams > 0:
  944. return round(tracked_grams, 1)
  945. if status == "completed":
  946. return archive_filament_used_grams
  947. if archive_filament_used_grams:
  948. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  949. if scale > 0:
  950. return round(archive_filament_used_grams * scale, 1)
  951. return None
  952. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  953. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  954. stored_ams_mapping = data.get("ams_mapping")
  955. if not stored_ams_mapping and archive_id:
  956. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  957. return stored_ams_mapping
  958. def _get_start_plate_id(archive_id: int | None) -> int | None:
  959. """Resolve plate_id for print start without consuming stored direct-Print state.
  960. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  961. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  962. read it back at print-start without popping (the entry is popped on print
  963. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  964. """
  965. if archive_id is None:
  966. return None
  967. return _print_plate_ids.get(archive_id)
  968. def _partial_progress_scale(progress: int | float | None) -> float:
  969. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  970. Used by every site that multiplies a "would-have-used" slicer estimate
  971. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  972. so the three sites in ``_background_notifications`` (and the per-plate
  973. override helper) can't drift apart on the coercion shape.
  974. """
  975. return max(0.0, min((progress or 0) / 100.0, 1.0))
  976. def _scope_notification_archive_data_to_plate(
  977. archive_data: dict,
  978. archive_file_path: str | None,
  979. plate_id: int | None,
  980. print_status: str,
  981. progress: int | float | None,
  982. base_dir: Path,
  983. ) -> dict:
  984. """Override summed-across-plates totals in ``archive_data`` with the values
  985. for ``plate_id`` so the completion notification reports what was actually
  986. printed, not the whole project (#1785).
  987. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  988. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  989. the archive card's "whole project" headline, wrong for the completion
  990. notification of a single-plate print. The queue UI already re-reads the
  991. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  992. notification payload (filament grams, time estimate, per-slot breakdown).
  993. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  994. no per-plate values — in every fail case the original ``archive_data`` is
  995. returned unchanged so the notification still sends.
  996. """
  997. if plate_id is None or not archive_file_path:
  998. return archive_data
  999. from backend.app.utils.threemf_tools import (
  1000. extract_filament_usage_from_3mf,
  1001. extract_print_time_from_3mf,
  1002. )
  1003. archive_path = base_dir / archive_file_path
  1004. if not archive_path.exists():
  1005. return archive_data
  1006. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1007. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1008. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1009. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1010. if plate_time:
  1011. archive_data["print_time_seconds"] = plate_time
  1012. # Gate both the grams headline AND the per-slot breakdown on the same
  1013. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1014. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1015. # to the project-level grams the archive columns already provide rather
  1016. # than ship a project-level headline next to an all-zero per-plate
  1017. # breakdown.
  1018. if plate_grams > 0:
  1019. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1020. archive_data["filament_slots"] = [
  1021. {
  1022. "slot_id": s.get("slot_id"),
  1023. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1024. "type": s.get("type", ""),
  1025. "color": s.get("color", ""),
  1026. }
  1027. for s in plate_slots
  1028. ]
  1029. return archive_data
  1030. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1031. """Best-effort filament metadata from the MQTT print-start snapshot.
  1032. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1033. file during print, see #1533) so the fallback PrintArchive still has
  1034. enough filament info to support the inventory views and AMS-expansion
  1035. planning the operator opens it for. Returns a dict with optional
  1036. ``filament_type`` and ``filament_color`` keys in the same
  1037. comma-separated format the 3MF extractor produces, so the rest of the
  1038. codebase treats the fallback archive identically to a normal one.
  1039. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1040. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1041. entries). When supplied, only the slots actually consumed by this
  1042. print contribute. Without it the function falls back to every loaded
  1043. AMS slot — less accurate but still useful.
  1044. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1045. that the unit tests pass directly, AND the on_print_start callback
  1046. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1047. bambu_mqtt service hands to main.py at runtime. The original
  1048. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1049. handled the inner shape and silently returned ``{}`` for every real
  1050. print start, leaving fallback archives' filament fields NULL — the
  1051. exact regression the fix was meant to close. Reported with a log
  1052. proving the AMS state was right there at
  1053. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1054. """
  1055. result: dict[str, str] = {}
  1056. # Look at the on_print_start wrapper first, then the inner shape.
  1057. raw_data = (data or {}).get("raw_data")
  1058. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1059. if not isinstance(ams_root, dict):
  1060. ams_root = (data or {}).get("ams") or {}
  1061. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1062. if not isinstance(ams_units, list) or not ams_units:
  1063. return result
  1064. # Map global tray id (unit * 4 + tray) → (type, color).
  1065. loaded: dict[int, tuple[str, str]] = {}
  1066. for unit in ams_units:
  1067. if not isinstance(unit, dict):
  1068. continue
  1069. try:
  1070. unit_id = int(unit.get("id", 0))
  1071. except (TypeError, ValueError):
  1072. continue
  1073. for tray in unit.get("tray") or []:
  1074. if not isinstance(tray, dict):
  1075. continue
  1076. try:
  1077. tray_id = int(tray.get("id", 0))
  1078. except (TypeError, ValueError):
  1079. continue
  1080. ttype = (tray.get("tray_type") or "").strip()
  1081. tcolor = (tray.get("tray_color") or "").strip().upper()
  1082. if not ttype:
  1083. continue # Empty / unloaded slot.
  1084. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1085. if not loaded:
  1086. return result
  1087. if ams_mapping:
  1088. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1089. filaments = [loaded[g] for g in used_ids if g in loaded]
  1090. if not filaments:
  1091. return result # Mapping points entirely at slots we have no data for.
  1092. else:
  1093. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1094. types_joined = ",".join(f[0] for f in filaments)
  1095. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1096. # Column limits per backend/app/models/archive.py: filament_type=50,
  1097. # filament_color=200.
  1098. if types_joined:
  1099. result["filament_type"] = types_joined[:50]
  1100. if colors_joined:
  1101. result["filament_color"] = colors_joined[:200]
  1102. return result
  1103. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1104. """Start a layer-timelapse session for *archive_id* when the printer has
  1105. an external camera configured. Returns True if a session was started.
  1106. Three call sites in on_print_start (expected-archive promotion, fallback
  1107. archive creation, fresh-archive creation) used to inline this same
  1108. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1109. on the first pass). Centralising the conditional + call here makes the
  1110. contract testable in isolation and keeps the three sites locked in step.
  1111. """
  1112. if not (printer.external_camera_enabled and printer.external_camera_url):
  1113. return False
  1114. from backend.app.services.layer_timelapse import start_session
  1115. start_session(
  1116. printer_id,
  1117. archive_id,
  1118. printer.external_camera_url,
  1119. printer.external_camera_type or "mjpeg",
  1120. snapshot_url=printer.external_camera_snapshot_url,
  1121. rotation=getattr(printer, "camera_rotation", 0),
  1122. )
  1123. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1124. return True
  1125. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1126. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1127. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1128. — since #2926 — the description the parser already resolved, which is preferred
  1129. when present so the queue's failure reason reads the same as the status
  1130. response. The short code still produces the bracketed label, and still
  1131. resolves the sentence for a caller whose entries predate the field. Falls back
  1132. to the bare short code when no description is on file. Returns None for an
  1133. empty list so callers can leave error_message unset.
  1134. """
  1135. if not hms_errors:
  1136. return None
  1137. from backend.app.services.hms_errors import get_error_description
  1138. parts: list[str] = []
  1139. for err in hms_errors:
  1140. try:
  1141. # `_hms_short_code` rather than a local derivation: this one used to
  1142. # format the error without masking it to 16 bits, so an `hms[]` entry
  1143. # whose code carries an alert-level group produced a five-digit label
  1144. # like "0500_3000A" — not a code the user can look up, and never a
  1145. # catalogue key, so the sentence was lost with it.
  1146. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1147. except (TypeError, ValueError):
  1148. continue
  1149. description = err.get("description") or get_error_description(short_code)
  1150. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  1151. return "; ".join(parts) if parts else None
  1152. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1153. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1154. print completes successfully. Gated to status=='completed': failed, cancelled
  1155. and aborted prints do not count as usage. Caller is responsible for committing
  1156. the session. No-op when the queue item has no linked library file (e.g. reprints
  1157. from an archive). See #1008."""
  1158. if queue_status != "completed" or item.library_file_id is None:
  1159. return
  1160. from backend.app.models.library import LibraryFile
  1161. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1162. if lib_file is None:
  1163. return
  1164. lib_file.print_count = (lib_file.print_count or 0) + 1
  1165. lib_file.last_printed_at = datetime.now(timezone.utc)
  1166. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1167. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1168. When on_print_complete fires with status 'failed' for a printer in this set we
  1169. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1170. rather than a 'print failed' notification.
  1171. """
  1172. _user_stopped_printers.add(printer_id)
  1173. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1174. _last_status_broadcast: dict[int, str] = {}
  1175. # Track printers where we've updated nozzle_count
  1176. _nozzle_count_updated: set[int] = set()
  1177. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1178. """Wait the debounce window then fire `on_printer_offline` if the printer
  1179. is still offline.
  1180. Scheduled by `on_printer_status_change` on the connected → disconnected
  1181. edge (#1752). Cancelled by the same handler if the printer reconnects
  1182. before the window elapses, so a single MQTT blip + recovery doesn't
  1183. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1184. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1185. route through the same status-change callback, so this covers both.
  1186. """
  1187. logger = logging.getLogger(__name__)
  1188. try:
  1189. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1190. still_offline = not printer_manager.is_connected(printer_id)
  1191. logger.info(
  1192. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1193. printer_id,
  1194. still_offline,
  1195. )
  1196. if not still_offline:
  1197. return
  1198. async with async_session() as db:
  1199. from backend.app.models.printer import Printer
  1200. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1201. printer = result.scalar_one_or_none()
  1202. if not printer:
  1203. logger.warning(
  1204. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1205. printer_id,
  1206. )
  1207. return
  1208. logger.info(
  1209. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1210. printer_id,
  1211. printer.name,
  1212. )
  1213. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1214. except asyncio.CancelledError:
  1215. raise
  1216. except Exception as e:
  1217. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1218. finally:
  1219. _printer_offline_notify_tasks.pop(printer_id, None)
  1220. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1221. """Handle printer status changes - broadcast via WebSocket."""
  1222. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1223. # transitions disconnected → connected — which covers both Bambuddy
  1224. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1225. # `reconcile_stale_active_prints` exactly once for this connection so
  1226. # any archive still in `status="printing"` that can't actually be
  1227. # running anymore (printer IDLE / different subtask / empty subtask)
  1228. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1229. # finished during a disconnect window + a smart-plug power cycle
  1230. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1231. # next boot. Reconciliation runs concurrently — it must not block the
  1232. # WebSocket dedup / broadcast logic below, and the connected edge is
  1233. # marked True BEFORE the await so concurrent status updates inside
  1234. # the same connection don't re-trigger reconciliation.
  1235. #
  1236. # Wait for a real push_status before reconciling (#1679): MQTT
  1237. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1238. # the connection, BEFORE `_request_push_all` round-trips. At that
  1239. # instant the `PrinterState` is still on construction defaults — most
  1240. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1241. # If reconcile spawns here, every in-flight archive falls through to
  1242. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1243. # creates a duplicate archive on the real PRINT COMPLETE and
  1244. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1245. # keeps the #1542 mechanism intact: once the first real push_status
  1246. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1247. # fires again with the flag still False — reconcile then runs against
  1248. # actual evidence.
  1249. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1250. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1251. _printer_reconciled_since_connect[printer_id] = True
  1252. spawn_background_task(
  1253. reconcile_stale_active_prints(printer_id),
  1254. name=f"reconcile-stale-prints-{printer_id}",
  1255. )
  1256. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1257. # Re-arm so the next reconnect triggers reconciliation again.
  1258. _printer_reconciled_since_connect[printer_id] = False
  1259. # Same edge, for the calibration table the AMS card reads its K values from.
  1260. #
  1261. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1262. # tables to ask for. A `state_known` gate alone is not enough: the first
  1263. # real push_status is what makes the state known, and the nozzle fields do
  1264. # not always arrive in it. Latching there would spend this connection's one
  1265. # attempt on a printer that could not yet say what was fitted.
  1266. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1267. if (
  1268. state.connected
  1269. and state_known
  1270. and nozzle_known
  1271. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1272. ):
  1273. _printer_kprofiles_primed_since_connect[printer_id] = True
  1274. spawn_background_task(
  1275. prime_kprofile_table(printer_id),
  1276. name=f"prime-kprofiles-{printer_id}",
  1277. )
  1278. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1279. _printer_kprofiles_primed_since_connect[printer_id] = False
  1280. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1281. # connected → disconnected. The "back online" channel is already covered
  1282. # by the print-failure notification (firmware reports gcode_state=FAILED
  1283. # on reconnect of an interrupted print), so we don't add a symmetric
  1284. # online event here.
  1285. prev_connected = _printer_last_connected.get(printer_id)
  1286. _printer_last_connected[printer_id] = state.connected
  1287. if prev_connected is True and not state.connected:
  1288. existing = _printer_offline_notify_tasks.get(printer_id)
  1289. if existing is None or existing.done():
  1290. logging.getLogger(__name__).info(
  1291. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1292. printer_id,
  1293. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1294. )
  1295. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1296. _maybe_notify_printer_offline(printer_id),
  1297. name=f"printer-offline-notify-{printer_id}",
  1298. )
  1299. elif state.connected:
  1300. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1301. if pending is not None and not pending.done():
  1302. logging.getLogger(__name__).info(
  1303. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1304. printer_id,
  1305. )
  1306. pending.cancel()
  1307. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1308. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1309. temps = state.temperatures or {}
  1310. nozzle_temp = round(temps.get("nozzle", 0))
  1311. bed_temp = round(temps.get("bed", 0))
  1312. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1313. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1314. # Auto-detect dual-nozzle printers from MQTT temperature data
  1315. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1316. _nozzle_count_updated.add(printer_id)
  1317. # Update nozzle_count in database
  1318. async with async_session() as db:
  1319. from backend.app.models.printer import Printer
  1320. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1321. printer = result.scalar_one_or_none()
  1322. if printer and printer.nozzle_count != 2:
  1323. printer.nozzle_count = 2
  1324. await db.commit()
  1325. logging.getLogger(__name__).info(
  1326. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1327. )
  1328. # Include target temps for heating phase detection
  1329. bed_target = round(temps.get("bed_target", 0))
  1330. nozzle_target = round(temps.get("nozzle_target", 0))
  1331. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1332. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1333. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  1334. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  1335. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1336. #
  1337. # The filament identity fields are here because Configure Slot writes
  1338. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1339. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1340. # matched, this function returned before broadcasting, and the card kept
  1341. # showing the old filament until the 30s fallback poll or a page reload —
  1342. # even though the configure route asks the printer for a fresh pushall and
  1343. # that push does carry the new values. Reset always worked, because it
  1344. # clears tray_type.
  1345. #
  1346. # These fields only change when someone configures a slot or swaps a spool,
  1347. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1348. ams_tray_key = (
  1349. tuple(
  1350. (
  1351. t.get("id"),
  1352. t.get("tray_type", ""),
  1353. t.get("state"),
  1354. t.get("tray_color", ""),
  1355. t.get("tray_info_idx", ""),
  1356. t.get("tray_sub_brands", ""),
  1357. t.get("cali_idx"),
  1358. )
  1359. for a in (state.raw_data.get("ams") or [])
  1360. for t in a.get("tray", [])
  1361. )
  1362. if state.raw_data
  1363. else ()
  1364. )
  1365. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1366. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1367. # in the AMS change-hash (tray fields only, and widening that would fire
  1368. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1369. # screen changed no key at all and the card's inlet badges sat stale until a
  1370. # reload. Like the filament-backup flag, these only move when someone
  1371. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1372. fts_key = (
  1373. state.fila_switch.installed if state.fila_switch else False,
  1374. tuple(sorted(state.ams_switch_inlet.items())),
  1375. # Which hotend holds which slot. Unlike the two above this does move
  1376. # mid-print, on every filament change — but only between discrete slots,
  1377. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1378. # it live: it decides which hotend the Load dialog may offer and whether
  1379. # Unload has anything to act on.
  1380. tuple(
  1381. sorted(
  1382. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1383. # Sort on the extruder id alone: the other members are nullable
  1384. # and comparing None with an int raises.
  1385. key=lambda entry: entry[0],
  1386. )
  1387. ),
  1388. )
  1389. status_key = (
  1390. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1391. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1392. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1393. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1394. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1395. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1396. )
  1397. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1398. if not is_active_print:
  1399. _unauthorized_print_kill_sent.discard(printer_id)
  1400. elif printer_id in _unauthorized_print_kill_sent:
  1401. # stop_print() was already sent for this print; avoid all further
  1402. # ownership and settings work until the printer leaves an active state.
  1403. pass
  1404. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1405. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1406. _unauthorized_print_kill_sent.discard(printer_id)
  1407. else:
  1408. kill_switch_enabled = False
  1409. authorization: bool | None = None
  1410. status_logger = logging.getLogger(__name__)
  1411. try:
  1412. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1413. if kill_switch_enabled:
  1414. async with async_session() as db:
  1415. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1416. except Exception as e:
  1417. # Fail safe: a database/reconciliation error must never turn into an
  1418. # irreversible stop of a print whose ownership is still unknown.
  1419. authorization = None
  1420. status_logger.warning(
  1421. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1422. )
  1423. if not kill_switch_enabled or authorization is True:
  1424. _unauthorized_print_kill_sent.discard(printer_id)
  1425. elif authorization is None:
  1426. _unauthorized_print_kill_sent.discard(printer_id)
  1427. status_logger.debug(
  1428. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1429. printer_id,
  1430. )
  1431. else:
  1432. try:
  1433. stopped = printer_manager.stop_print(printer_id)
  1434. if stopped:
  1435. _unauthorized_print_kill_sent.add(printer_id)
  1436. printer_info = printer_manager.get_printer(printer_id)
  1437. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1438. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1439. notification_data = {
  1440. "status": "stopped",
  1441. "filename": state.gcode_file or state.current_print or "",
  1442. "subtask_name": state.subtask_name or "",
  1443. "progress": state.progress,
  1444. "reason": "unauthorized_print",
  1445. }
  1446. status_logger.warning(
  1447. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1448. printer_id,
  1449. state.state,
  1450. )
  1451. try:
  1452. await ws_manager.broadcast(
  1453. {
  1454. "type": "kill_switch_triggered",
  1455. "printer_id": printer_id,
  1456. "printer_name": printer_name,
  1457. "filename": filename,
  1458. "reason": "unauthorized_print",
  1459. }
  1460. )
  1461. except Exception as e:
  1462. status_logger.warning(
  1463. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1464. )
  1465. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1466. if previous_task is not None and not previous_task.done():
  1467. previous_task.cancel()
  1468. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1469. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1470. name=f"kill-switch-notification-{printer_id}",
  1471. )
  1472. else:
  1473. status_logger.warning(
  1474. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1475. printer_id,
  1476. state.state,
  1477. )
  1478. except Exception as e:
  1479. status_logger.warning(
  1480. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1481. )
  1482. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1483. try:
  1484. printer_info = printer_manager.get_printer(printer_id)
  1485. if printer_info:
  1486. await mqtt_relay.on_printer_status(
  1487. printer_id,
  1488. state,
  1489. printer_info.name,
  1490. printer_info.serial_number,
  1491. printer_manager.is_awaiting_plate_clear(printer_id),
  1492. )
  1493. except Exception:
  1494. pass # Don't fail status callback if MQTT fails
  1495. if _last_status_broadcast.get(printer_id) == status_key:
  1496. return # No change, skip WebSocket broadcast
  1497. _last_status_broadcast[printer_id] = status_key
  1498. # Check for progress milestone notifications (25%, 50%, 75%)
  1499. progress = state.progress or 0
  1500. is_printing = state.state in ("RUNNING", "PRINTING")
  1501. if is_printing and progress > 0:
  1502. # Determine which milestone we've reached
  1503. current_milestone = 0
  1504. if progress >= 75:
  1505. current_milestone = 75
  1506. elif progress >= 50:
  1507. current_milestone = 50
  1508. elif progress >= 25:
  1509. current_milestone = 25
  1510. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1511. # If we've crossed a new milestone, send notification
  1512. if current_milestone > last_milestone:
  1513. _last_progress_milestone[printer_id] = current_milestone
  1514. try:
  1515. from backend.app.models.printer import Printer
  1516. # Read the printer in a short session and release the connection
  1517. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1518. # pinned a pooled connection per milestone, per printer (issue #2572).
  1519. async with async_session() as db:
  1520. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1521. printer = result.scalar_one_or_none()
  1522. printer_name = printer.name if printer else f"Printer {printer_id}"
  1523. filename = state.subtask_name or state.gcode_file or "Unknown"
  1524. # remaining_time is in minutes, convert to seconds for notification
  1525. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1526. # Capture camera snapshot for notification image attachment (no DB held).
  1527. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1528. # Notification send needs a session (provider/template lookups).
  1529. async with async_session() as db:
  1530. await notification_service.on_print_progress(
  1531. printer_id,
  1532. printer_name,
  1533. filename,
  1534. current_milestone,
  1535. db,
  1536. remaining_time_seconds,
  1537. image_data=image_data,
  1538. )
  1539. except Exception as e:
  1540. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1541. elif progress < 5:
  1542. # Reset milestone tracking when print restarts or new print begins
  1543. _last_progress_milestone[printer_id] = 0
  1544. _first_layer_notified[printer_id] = False
  1545. # HMS error codes that should not trigger notifications even though they
  1546. # have known descriptions (e.g. user-initiated actions, not real errors).
  1547. _HMS_NOTIFICATION_SUPPRESS = {
  1548. "0500_400E", # Printing was cancelled (user action, not an error)
  1549. }
  1550. # Check for new HMS errors and send notifications
  1551. current_hms_errors = getattr(state, "hms_errors", []) or []
  1552. if current_hms_errors:
  1553. # Build set of current error codes (using attr for uniqueness)
  1554. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1555. previously_notified = _notified_hms_errors.get(printer_id, set())
  1556. # Find new errors that haven't been notified yet
  1557. new_error_codes = current_error_codes - previously_notified
  1558. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1559. _notified_hms_errors[printer_id] = current_error_codes
  1560. _hms_last_seen[printer_id] = time.time()
  1561. if new_error_codes:
  1562. # Get the actual new errors for the notification
  1563. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1564. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1565. try:
  1566. from backend.app.models.printer import Printer
  1567. # Read the printer in a short session and release the connection
  1568. # BEFORE the ~15s camera snapshot below (issue #2572).
  1569. async with async_session() as db:
  1570. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1571. printer = result.scalar_one_or_none()
  1572. printer_name = printer.name if printer else f"Printer {printer_id}"
  1573. # Format error details for notification
  1574. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1575. module_names = {
  1576. 0x03: "Print/Task",
  1577. 0x05: "Nozzle/Extruder",
  1578. 0x07: "AMS/Filament",
  1579. 0x0C: "Motion Controller",
  1580. 0x12: "Chamber",
  1581. }
  1582. # Capture camera snapshot once for all error notifications (no DB held).
  1583. error_image_data = await _capture_snapshot_for_notification(
  1584. printer_id, printer, logging.getLogger(__name__)
  1585. )
  1586. # Notification sends need a session (provider/template lookups).
  1587. async with async_session() as db:
  1588. sent_count = 0
  1589. for error in new_errors:
  1590. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1591. # Build short code like "0700_8010"
  1592. # Mask to 16 bits to handle printers that send larger values
  1593. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1594. error_code_masked = error_code_int & 0xFFFF
  1595. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1596. # Only notify for errors with known descriptions — printers
  1597. # send many undocumented/phantom codes that aren't real errors.
  1598. # Resolved at parse time (#2926); short_code is still needed
  1599. # for the suppression set below.
  1600. description = error.description
  1601. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1602. continue
  1603. error_type = f"{module_name} Error"
  1604. error_detail = description
  1605. await notification_service.on_printer_error(
  1606. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1607. )
  1608. sent_count += 1
  1609. if sent_count:
  1610. logging.getLogger(__name__).info(
  1611. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1612. )
  1613. # Also publish to MQTT relay (no DB).
  1614. printer_info = printer_manager.get_printer(printer_id)
  1615. if printer_info:
  1616. errors_data = [
  1617. {
  1618. "code": e.code,
  1619. "attr": e.attr,
  1620. "module": e.module,
  1621. "severity": e.severity,
  1622. }
  1623. for e in new_errors
  1624. ]
  1625. await mqtt_relay.on_printer_error(
  1626. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1627. )
  1628. except Exception as e:
  1629. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1630. else:
  1631. # No HMS errors — only clear tracking after a grace period to prevent
  1632. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1633. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1634. # on/off every few seconds as conditions fluctuate around thresholds.
  1635. if printer_id in _notified_hms_errors:
  1636. last_seen = _hms_last_seen.get(printer_id, 0)
  1637. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1638. _notified_hms_errors.pop(printer_id, None)
  1639. _hms_last_seen.pop(printer_id, None)
  1640. await ws_manager.send_printer_status(
  1641. printer_id,
  1642. printer_state_to_dict(
  1643. state,
  1644. printer_id,
  1645. printer_manager.get_model(printer_id),
  1646. printer_manager.get_drying_targets(printer_id),
  1647. ),
  1648. )
  1649. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1650. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1651. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1652. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1653. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1654. K-profiles are per-nozzle and the printer's calibration table is numbered
  1655. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1656. switch's other inlet therefore silently invalidates every configured slot in
  1657. it: the index stays put and now resolves against the other nozzle's table.
  1658. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1659. and 0.020 on the right kept the left profile after the move, and a manual
  1660. RFID re-read only re-asserted the same wrong one.
  1661. Configuring a slot is a deliberate preparation step, so this re-selects
  1662. rather than re-configures: only the calibration binding moves, and only for
  1663. slots whose spool already has a stored profile for the new nozzle. A slot
  1664. Bambuddy knows nothing about is left exactly as the operator left it.
  1665. """
  1666. logger = logging.getLogger(__name__)
  1667. target_extruder = extruder_for_inlet(inlet)
  1668. if target_extruder is None:
  1669. return
  1670. client = printer_manager.get_client(printer_id)
  1671. state = printer_manager.get_status(printer_id)
  1672. if not client or not state or not state.raw_data:
  1673. return
  1674. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1675. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1676. # the nozzle width, which changes both the K profile to select and the
  1677. # preset the slot should carry.
  1678. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1679. ams_raw = state.raw_data.get("ams")
  1680. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1681. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1682. if not unit:
  1683. return
  1684. try:
  1685. async with async_session() as db:
  1686. for tray in unit.get("tray", []):
  1687. tray_id = int(tray.get("id", -1))
  1688. if tray_id < 0 or not tray.get("tray_type"):
  1689. continue
  1690. current_idx = tray.get("cali_idx")
  1691. profile = await find_slot_kprofile_for_extruder(
  1692. db,
  1693. printer_id,
  1694. ams_id,
  1695. tray_id,
  1696. target_extruder,
  1697. nozzle_diameter,
  1698. printer_manager.get_model(printer_id),
  1699. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1700. )
  1701. if profile is None or profile.cali_idx is None:
  1702. continue
  1703. if current_idx == profile.cali_idx:
  1704. continue # Already on the right one.
  1705. logger.info(
  1706. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1707. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1708. printer_id,
  1709. ams_id,
  1710. tray_id,
  1711. inlet,
  1712. target_extruder,
  1713. profile.name,
  1714. current_idx,
  1715. profile.cali_idx,
  1716. profile.k_value,
  1717. )
  1718. client.extrusion_cali_sel(
  1719. ams_id=ams_id,
  1720. tray_id=tray_id,
  1721. cali_idx=profile.cali_idx,
  1722. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1723. nozzle_diameter=nozzle_diameter,
  1724. )
  1725. except Exception as e:
  1726. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1727. async def on_ams_change(printer_id: int, ams_data: list):
  1728. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1729. logger = logging.getLogger(__name__)
  1730. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1731. # on_print_complete may pop _active_sessions during our awaits (#880).
  1732. from backend.app.services.usage_tracker import _active_sessions
  1733. _print_active = printer_id in _active_sessions
  1734. # A slot that reports empty while a print is running is a filament runout,
  1735. # not a spool swap: the spool is still physically in the AMS, just
  1736. # consumed. Dropping either inventory backend's slot link there loses the
  1737. # only record of which spool fed the print, so the completion path can't
  1738. # charge the runout segment to anything. Both cleanup passes below consult
  1739. # this; computed once, up front, so neither depends on the other having run.
  1740. _unlink_state = printer_manager.get_status(printer_id)
  1741. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  1742. # MQTT relay - publish AMS change
  1743. try:
  1744. printer_info = printer_manager.get_printer(printer_id)
  1745. if printer_info:
  1746. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1747. except Exception:
  1748. pass # Don't fail AMS callback if MQTT fails
  1749. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1750. # This ensures frontend gets immediate updates when AMS slots are configured
  1751. try:
  1752. state = printer_manager.get_status(printer_id)
  1753. if state:
  1754. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1755. await ws_manager.send_printer_status(
  1756. printer_id,
  1757. printer_state_to_dict(
  1758. state,
  1759. printer_id,
  1760. printer_manager.get_model(printer_id),
  1761. printer_manager.get_drying_targets(printer_id),
  1762. ),
  1763. )
  1764. except Exception as e:
  1765. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1766. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1767. # Auto-unlink spool assignments with stale fingerprints
  1768. try:
  1769. async with async_session() as db:
  1770. from sqlalchemy.orm import selectinload
  1771. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1772. from backend.app.models.spool import Spool as _Spool
  1773. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1774. from backend.app.services.ams_slot_presence import spool_present
  1775. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1776. # Built-in assignments only. Since #2812 they survive a switch to
  1777. # Spoolman mode rather than being deleted by it, and this pass ends
  1778. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1779. # time as the AMS contents changed under the other mode, undoing the
  1780. # preservation more slowly but just as completely.
  1781. assignments = []
  1782. if not await spoolman_owns_assignments(db):
  1783. result = await db.execute(
  1784. select(SA)
  1785. .where(SA.printer_id == printer_id)
  1786. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1787. )
  1788. assignments = result.scalars().all()
  1789. # ``printing_now`` (top of this function) keeps a runout from
  1790. # unlinking the spool that fed the print — the next idle-time pass
  1791. # unlinks it if the user really did take it out.
  1792. stale = []
  1793. for assignment in assignments:
  1794. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1795. if assignment.ams_id == 255:
  1796. ps = printer_manager.get_status(printer_id)
  1797. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1798. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1799. current_tray = None
  1800. for vt in vt_tray_raw:
  1801. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1802. current_tray = vt
  1803. break
  1804. if not current_tray:
  1805. # vt_tray data may not have arrived yet — keep assignment
  1806. continue
  1807. else:
  1808. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1809. if not current_tray:
  1810. if printing_now:
  1811. logger.info(
  1812. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1813. assignment.spool_id,
  1814. assignment.ams_id,
  1815. assignment.tray_id,
  1816. )
  1817. continue
  1818. logger.info(
  1819. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1820. assignment.spool_id,
  1821. assignment.ams_id,
  1822. assignment.tray_id,
  1823. )
  1824. stale.append(assignment) # Slot empty
  1825. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1826. # A Bambu Lab spool is in this slot — check if it's the same spool
  1827. # that's currently assigned. If yes, keep the assignment (avoids
  1828. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1829. # the printer's filament preset on every startup).
  1830. tray_uuid = current_tray.get("tray_uuid", "")
  1831. tag_uid = current_tray.get("tag_uid", "")
  1832. spool = assignment.spool
  1833. spool_matches = False
  1834. if spool:
  1835. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1836. spool.tag_uid
  1837. and tag_uid
  1838. and tag_uid != "0000000000000000"
  1839. and spool.tag_uid.upper() == tag_uid.upper()
  1840. ):
  1841. spool_matches = True
  1842. if spool_matches:
  1843. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1844. cur_color = current_tray.get("tray_color", "")
  1845. cur_type = current_tray.get("tray_type", "")
  1846. fp_color = assignment.fingerprint_color or ""
  1847. fp_type = assignment.fingerprint_type or ""
  1848. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1849. assignment.fingerprint_color = cur_color
  1850. assignment.fingerprint_type = cur_type
  1851. logger.debug(
  1852. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1853. assignment.spool_id,
  1854. assignment.ams_id,
  1855. assignment.tray_id,
  1856. )
  1857. continue
  1858. # Different BL spool or unrecognized — unlink so auto-assign can match
  1859. logger.info(
  1860. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1861. assignment.spool_id,
  1862. assignment.ams_id,
  1863. assignment.tray_id,
  1864. tray_uuid,
  1865. )
  1866. stale.append(assignment)
  1867. else:
  1868. cur_color = current_tray.get("tray_color", "")
  1869. cur_type = current_tray.get("tray_type", "")
  1870. cur_state = current_tray.get("state")
  1871. fp_color = assignment.fingerprint_color or ""
  1872. fp_type = assignment.fingerprint_type or ""
  1873. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1874. # the slot was empty when the user pre-assigned via SpoolBuddy
  1875. # (the firmware drops ams_filament_setting on empty slots, so
  1876. # MQTT was deferred). The moment any filament gets inserted
  1877. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1878. # reconfigured spool — fire the deferred configuration.
  1879. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1880. # extruder" code) OR, on firmwares that don't use the state
  1881. # enum meaningfully, a non-empty tray_type when state is
  1882. # NOT one of the firmware's explicit empty signals (9, 10).
  1883. # state-only was wrong for firmwares that never set 11 — A1
  1884. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1885. # always report state=3 — so the replay never fired for them
  1886. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1887. # explicit "empty" signals authoritative over any stale
  1888. # tray_type that might survive the relay's auto-clearing.
  1889. #
  1890. # tray_exist_bits comes first because that guard cannot tell
  1891. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  1892. # writes state=9 when the bit is 0 and leaves it there when the
  1893. # bit returns. A non-RFID spool inserted into a pre-assigned
  1894. # slot brings no tray_type with it, so the stale 9 made this
  1895. # expression false forever and the deferred config never fired
  1896. # — the deadlock #1322 removed from the assign path, still in
  1897. # place here (#3084, #3100).
  1898. loaded = spool_present(current_tray) is True or (
  1899. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1900. )
  1901. if not fp_type.strip() and loaded and assignment.spool:
  1902. try:
  1903. from backend.app.api.routes.inventory import (
  1904. apply_spool_to_slot_via_mqtt,
  1905. )
  1906. await apply_spool_to_slot_via_mqtt(
  1907. db=db,
  1908. current_user=None,
  1909. spool=assignment.spool,
  1910. printer_id=printer_id,
  1911. ams_id=assignment.ams_id,
  1912. tray_id=assignment.tray_id,
  1913. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1914. current_tray_type=cur_type,
  1915. )
  1916. logger.info(
  1917. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1918. assignment.spool_id,
  1919. printer_id,
  1920. assignment.ams_id,
  1921. assignment.tray_id,
  1922. )
  1923. except Exception:
  1924. logger.exception(
  1925. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1926. assignment.spool_id,
  1927. printer_id,
  1928. assignment.ams_id,
  1929. assignment.tray_id,
  1930. )
  1931. assignment.fingerprint_color = cur_color
  1932. assignment.fingerprint_type = cur_type
  1933. continue
  1934. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1935. # Blank tray data mid-print is a runout, not a swap: the
  1936. # firmware clears colour and type when it unloads a spool
  1937. # it just emptied. Unlinking here would erase the record
  1938. # of which spool fed the print so far.
  1939. if printing_now and not cur_color.strip() and not cur_type.strip():
  1940. logger.info(
  1941. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  1942. "(runout?)",
  1943. assignment.spool_id,
  1944. assignment.ams_id,
  1945. assignment.tray_id,
  1946. )
  1947. continue
  1948. # Same reasoning off the print, on firmware's own say-so:
  1949. # a blank tray report from a slot whose tray_exist_bits
  1950. # bit is set describes a spool the AMS cannot identify —
  1951. # a non-RFID one, or one whose slot was reset — not a
  1952. # spool that was taken out. Deleting the assignment there
  1953. # threw away the identity the user had supplied, which is
  1954. # the only place it existed (#3100). A slot the bit calls
  1955. # empty, or one that carries no bit at all, still unlinks.
  1956. if spool_present(current_tray) is True and not cur_color.strip() and not cur_type.strip():
  1957. logger.info(
  1958. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  1959. "tray reports no filament data yet",
  1960. assignment.spool_id,
  1961. assignment.ams_id,
  1962. assignment.tray_id,
  1963. )
  1964. continue
  1965. # Fingerprint mismatch — but check if tray now matches the
  1966. # assigned spool (e.g. auto-configure changed the tray).
  1967. # Both sides are reduced to the type the slot can carry
  1968. # before comparing: the assign path writes that rather
  1969. # than the spool's raw material (#2902), so a spool whose
  1970. # material is a product line — "PLA+", "HTPLA" — reports
  1971. # back as "PLA" and would otherwise fail this check and
  1972. # be auto-unlinked from the slot it was just assigned to.
  1973. # Reducing the printer's side too keeps slots configured
  1974. # by an older Bambuddy, still reporting "PLA+", matching.
  1975. spool = assignment.spool
  1976. if spool:
  1977. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1978. # Two ways the assign path can have arrived at the
  1979. # slot's type, so both count as "we wrote this".
  1980. # The material column is one; the spool's preset is
  1981. # the other, and it outranks the material when the
  1982. # spool has one -- a spool whose material says PLA
  1983. # and whose preset is "Bambu PLA Aero" puts
  1984. # PLA-AERO in the slot (#2902). Read from the stored
  1985. # preset name rather than resolving the preset,
  1986. # because this runs on every AMS push and a cloud
  1987. # lookup here would be both slow and unavailable on
  1988. # the unauthenticated replay path.
  1989. spool_types = {printer_filament_type(spool.material).upper()}
  1990. if spool.slicer_filament_name:
  1991. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  1992. # An imported local preset stores its type outright,
  1993. # which is what the assign path used -- and the name
  1994. # above may be unset. One keyed read, and only on a
  1995. # mismatch, which is rare.
  1996. #
  1997. # slicer_filament is free text up to fifty characters,
  1998. # so the digits have to be checked against the range
  1999. # of the integer primary key they are about to be
  2000. # compared with. Postgres raises on an out-of-range
  2001. # integer rather than simply not matching, and that
  2002. # would poison this session and abandon the rest of
  2003. # the cleanup pass.
  2004. lp_ref = (spool.slicer_filament or "").strip()
  2005. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2006. from backend.app.models.local_preset import LocalPreset as _LP
  2007. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2008. if lp_type:
  2009. spool_types.add(printer_filament_type(lp_type).upper())
  2010. if (
  2011. _colors_similar(cur_color, spool_color)
  2012. and printer_filament_type(cur_type).upper() in spool_types
  2013. ):
  2014. logger.info(
  2015. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2016. assignment.spool_id,
  2017. assignment.ams_id,
  2018. assignment.tray_id,
  2019. )
  2020. assignment.fingerprint_color = cur_color
  2021. assignment.fingerprint_type = cur_type
  2022. continue
  2023. logger.info(
  2024. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2025. assignment.spool_id,
  2026. assignment.ams_id,
  2027. assignment.tray_id,
  2028. cur_color,
  2029. cur_type,
  2030. fp_color,
  2031. fp_type,
  2032. spool.rgba if spool else "?",
  2033. spool.material if spool else "?",
  2034. )
  2035. stale.append(assignment) # Spool changed
  2036. # Snapshot slots before delete — ORM attribute access after the
  2037. # commit would refresh against a deleted row.
  2038. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2039. for a in stale:
  2040. await db.delete(a)
  2041. if stale:
  2042. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2043. # Commit any changes (stale deletions and/or fingerprint updates)
  2044. await db.commit()
  2045. # Tell open browsers the assignment is gone (#2575). Only the manual
  2046. # REST assign/unassign endpoints broadcast this event; without it the
  2047. # frontend's spool-assignments cache keeps rendering the unlinked
  2048. # spool on the slot until an unrelated refetch — which reads exactly
  2049. # like "the fix didn't work" (reporter verified: a browser refresh
  2050. # after the swap showed the correct state all along).
  2051. for ams_id, tray_id in unlinked_slots:
  2052. await ws_manager.broadcast(
  2053. {
  2054. "type": "spool_assignment_changed",
  2055. "printer_id": printer_id,
  2056. "ams_id": ams_id,
  2057. "tray_id": tray_id,
  2058. }
  2059. )
  2060. except Exception as e:
  2061. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2062. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2063. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2064. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2065. # "no existing assignment" for the same (printer, ams, tray) and race to
  2066. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2067. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2068. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2069. try:
  2070. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2071. from backend.app.api.routes.settings import get_setting
  2072. from backend.app.models.spool import Spool
  2073. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2074. from backend.app.services.spool_tag_matcher import (
  2075. auto_assign_spool,
  2076. create_spool_from_tray,
  2077. find_matching_untagged_spool,
  2078. get_spool_by_tag,
  2079. is_bambu_tag,
  2080. is_valid_tag,
  2081. link_tag_to_inventory_spool,
  2082. )
  2083. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2084. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2085. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2086. if not _spoolman_on or _spoolman_on.lower() != "true":
  2087. for ams_unit in ams_data:
  2088. if not isinstance(ams_unit, dict):
  2089. continue
  2090. ams_id = int(ams_unit.get("id", 0))
  2091. for tray in ams_unit.get("tray", []):
  2092. if not isinstance(tray, dict):
  2093. continue
  2094. tray_id = int(tray.get("id", 0))
  2095. tag_uid = tray.get("tag_uid", "")
  2096. tray_uuid = tray.get("tray_uuid", "")
  2097. tray_info_idx = tray.get("tray_info_idx", "")
  2098. if not tray.get("tray_type"):
  2099. # Slot reported empty — drop any cached unknown-tag
  2100. # broadcast so reinserting the same spool re-prompts.
  2101. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2102. continue # Empty slot
  2103. # Check if assignment already exists for this slot
  2104. existing = await db.execute(
  2105. select(SA)
  2106. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2107. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2108. )
  2109. existing_assignment = existing.scalar_one_or_none()
  2110. if existing_assignment:
  2111. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2112. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2113. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2114. # Skip during active prints: the usage tracker handles deduction
  2115. # precisely via 3MF data on print completion. Without this guard the
  2116. # AMS remain% SET and the usage tracker ADD both fire from the same
  2117. # MQTT message, doubling the deduction (#880).
  2118. if _print_active:
  2119. continue
  2120. remain_raw = tray.get("remain")
  2121. if (
  2122. remain_raw is not None
  2123. and existing_assignment.spool
  2124. and not existing_assignment.spool.weight_locked
  2125. ):
  2126. try:
  2127. remain_val = int(remain_raw)
  2128. except (TypeError, ValueError):
  2129. remain_val = -1
  2130. if 1 <= remain_val <= 100:
  2131. lw = existing_assignment.spool.label_weight or 1000
  2132. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2133. current_used = existing_assignment.spool.weight_used or 0
  2134. if new_used > current_used + 1:
  2135. logger.info(
  2136. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2137. existing_assignment.spool_id,
  2138. current_used,
  2139. new_used,
  2140. remain_val,
  2141. )
  2142. existing_assignment.spool.weight_used = new_used
  2143. await db.commit()
  2144. # Re-apply stored K-profile when the live tray's
  2145. # cali_idx drifted from the spool's stored profile.
  2146. # This catches "reset slot → re-read" and any other
  2147. # path where the firmware loses the user's K-profile
  2148. # selection while the SpoolAssignment row persists.
  2149. # Per the maintainer's rule: any time a spool tag is
  2150. # identified and matches inventory, the slot must be
  2151. # configured with the spool's stored settings. Without
  2152. # this block the existing-assignment branch only ran
  2153. # weight-sync and let the firmware-default cali_idx win.
  2154. try:
  2155. spool = existing_assignment.spool
  2156. if (
  2157. spool is not None
  2158. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2159. and spool.k_profiles
  2160. ):
  2161. state = printer_manager.get_status(printer_id)
  2162. slot_nozzle = resolve_slot_nozzle(
  2163. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2164. )
  2165. nozzle_diameter = slot_nozzle.diameter
  2166. slot_extruder = slot_nozzle.extruder
  2167. # Prefer exact extruder match, fall back to
  2168. # extruder-agnostic kp for the same printer +
  2169. # nozzle. Avoids hard-skipping when the AMS is
  2170. # mapped differently than at calibration time.
  2171. matching_kp = None
  2172. fallback_kp = None
  2173. for kp in spool.k_profiles:
  2174. if (
  2175. kp.printer_id != printer_id
  2176. or kp.nozzle_diameter != nozzle_diameter
  2177. or kp.cali_idx is None
  2178. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2179. ):
  2180. continue
  2181. if (
  2182. slot_extruder is not None
  2183. and kp.extruder is not None
  2184. and kp.extruder == slot_extruder
  2185. ):
  2186. matching_kp = kp
  2187. break
  2188. if fallback_kp is None:
  2189. fallback_kp = kp
  2190. chosen_kp = matching_kp or fallback_kp
  2191. if chosen_kp is not None:
  2192. live_cali_idx = tray.get("cali_idx")
  2193. # Only fire MQTT when the printer's live
  2194. # cali_idx differs from the stored value.
  2195. # Avoids spamming the broker on every
  2196. # MQTT push during steady-state operation.
  2197. if live_cali_idx != chosen_kp.cali_idx:
  2198. client = printer_manager.get_client(printer_id)
  2199. if client:
  2200. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2201. client.extrusion_cali_sel(
  2202. ams_id=ams_id,
  2203. tray_id=tray_id,
  2204. cali_idx=chosen_kp.cali_idx,
  2205. filament_id=cali_filament_id,
  2206. nozzle_diameter=nozzle_diameter,
  2207. )
  2208. logger.info(
  2209. "Re-applied K-profile cali_idx=%d for spool %d "
  2210. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2211. chosen_kp.cali_idx,
  2212. spool.id,
  2213. printer_id,
  2214. ams_id,
  2215. tray_id,
  2216. live_cali_idx,
  2217. )
  2218. except Exception:
  2219. logger.exception(
  2220. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2221. printer_id,
  2222. ams_id,
  2223. tray_id,
  2224. )
  2225. continue
  2226. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2227. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2228. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2229. if not spool:
  2230. # Try matching an untagged inventory spool (same material/color)
  2231. spool = await find_matching_untagged_spool(db, tray)
  2232. if spool:
  2233. await link_tag_to_inventory_spool(db, spool, tray)
  2234. elif _auto_add_unknown:
  2235. spool = await create_spool_from_tray(db, tray)
  2236. else:
  2237. # Auto-add disabled: surface the slot so the
  2238. # user can add it manually via the UI.
  2239. await _broadcast_unknown_tag(
  2240. printer_id=printer_id,
  2241. ams_id=ams_id,
  2242. tray_id=tray_id,
  2243. tag_uid=tag_uid,
  2244. tray_uuid=tray_uuid,
  2245. tray_type=tray.get("tray_type"),
  2246. tray_color=tray.get("tray_color"),
  2247. tray_sub_brands=tray.get("tray_sub_brands"),
  2248. tray_count=len(ams_unit.get("tray", [])),
  2249. )
  2250. continue
  2251. # Slot matched (existing tag, untagged inventory
  2252. # match, or freshly auto-created spool) — drop any
  2253. # stale dedup so a future tag swap re-prompts.
  2254. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2255. await auto_assign_spool(
  2256. printer_id,
  2257. ams_id,
  2258. tray_id,
  2259. spool,
  2260. printer_manager,
  2261. db,
  2262. tray_info_idx=tray_info_idx,
  2263. )
  2264. await db.commit()
  2265. await ws_manager.broadcast(
  2266. {
  2267. "type": "spool_auto_assigned",
  2268. "printer_id": printer_id,
  2269. "ams_id": ams_id,
  2270. "tray_id": tray_id,
  2271. "spool_id": spool.id,
  2272. }
  2273. )
  2274. logger.info(
  2275. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2276. spool.id,
  2277. printer_id,
  2278. ams_id,
  2279. tray_id,
  2280. )
  2281. elif is_valid_tag(tag_uid, tray_uuid):
  2282. # Non-BL spool with some tag — let user choose
  2283. await _broadcast_unknown_tag(
  2284. printer_id=printer_id,
  2285. ams_id=ams_id,
  2286. tray_id=tray_id,
  2287. tag_uid=tag_uid,
  2288. tray_uuid=tray_uuid,
  2289. tray_type=tray.get("tray_type"),
  2290. tray_color=tray.get("tray_color"),
  2291. tray_sub_brands=tray.get("tray_sub_brands"),
  2292. tray_count=len(ams_unit.get("tray", [])),
  2293. )
  2294. # No-tag slots (generic non-RFID filament) are left alone:
  2295. # nothing to identify, prompting "+ Add" would just create
  2296. # ghost spools with empty tags on every confirm.
  2297. except Exception as e:
  2298. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2299. try:
  2300. async with async_session() as db:
  2301. from backend.app.api.routes.settings import get_setting
  2302. from backend.app.models.printer import Printer
  2303. # Check if Spoolman is enabled
  2304. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2305. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2306. return
  2307. # Check sync mode
  2308. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2309. if sync_mode and sync_mode != "auto":
  2310. return # Only sync on auto mode
  2311. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2312. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2313. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2314. # always owned by per-print tracking, never by AMS auto-sync. The
  2315. # setting is still read by the settings UI for backwards compat but
  2316. # has no effect on the sync path here.
  2317. # Get Spoolman URL
  2318. spoolman_url = await get_setting(db, "spoolman_url")
  2319. if not spoolman_url:
  2320. return
  2321. # Get or create Spoolman client
  2322. client = await get_spoolman_client()
  2323. if not client:
  2324. try:
  2325. client = await init_spoolman_client(spoolman_url)
  2326. except ValueError as exc:
  2327. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2328. return
  2329. # Check if Spoolman is reachable
  2330. if not await client.health_check():
  2331. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2332. return
  2333. # Get printer name for location
  2334. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2335. printer = result.scalar_one_or_none()
  2336. printer_name = printer.name if printer else f"Printer {printer_id}"
  2337. # OPTIMIZATION: Fetch all spools once before processing trays
  2338. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2339. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2340. try:
  2341. cached_spools = await client.get_spools()
  2342. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2343. except Exception as e:
  2344. logger.error(
  2345. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2346. printer_id,
  2347. e,
  2348. )
  2349. return
  2350. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2351. from sqlalchemy.orm import selectinload
  2352. from backend.app.models.spool_assignment import SpoolAssignment
  2353. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2354. from backend.app.services.ams_slot_presence import spool_present
  2355. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2356. # Built-in remaining weight, used by sync_ams_tray only when the
  2357. # firmware reports an unusable remain%/tray_weight for a slot.
  2358. #
  2359. # Left empty since #2812. This block runs in Spoolman mode only,
  2360. # and until then the built-in table was emptied on the switch, so
  2361. # there was never anything here to read and the fallback was inert.
  2362. # Preserving those rows makes it live again, and it is keyed by slot
  2363. # rather than by spool: after a mode switch the tray may well hold
  2364. # different filament, and ``create_spool`` writes ``remaining_weight``
  2365. # unconditionally, so a stale figure would be seeded into a brand new
  2366. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2367. # intent survives for whoever revisits the cross-mode fallback.
  2368. inventory_weights: dict[tuple[int, int], float] = {}
  2369. if not await spoolman_owns_assignments(db):
  2370. try:
  2371. assign_result = await db.execute(
  2372. select(SpoolAssignment)
  2373. .options(selectinload(SpoolAssignment.spool))
  2374. .where(SpoolAssignment.printer_id == printer_id)
  2375. )
  2376. for assignment in assign_result.scalars().all():
  2377. spool = assignment.spool
  2378. if spool and spool.label_weight > 0:
  2379. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2380. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2381. except Exception as e:
  2382. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2383. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2384. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2385. try:
  2386. slot_result = await db.execute(
  2387. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2388. )
  2389. for slot in slot_result.scalars().all():
  2390. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2391. except Exception as e:
  2392. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2393. # Sync each AMS tray and collect slot changes for DB persistence
  2394. synced = 0
  2395. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2396. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2397. for ams_unit in ams_data:
  2398. if not isinstance(ams_unit, dict):
  2399. continue
  2400. ams_id = int(ams_unit.get("id", 0))
  2401. trays = ams_unit.get("tray", [])
  2402. for tray_data in trays:
  2403. if not isinstance(tray_data, dict):
  2404. continue
  2405. tray_id_raw = int(tray_data.get("id", 0))
  2406. tray = client.parse_ams_tray(ams_id, tray_data)
  2407. if not tray:
  2408. # Empty tray slot — record for local assignment cleanup
  2409. # and drop any cached unknown-tag broadcast so a
  2410. # reinserted spool re-prompts.
  2411. #
  2412. # Not during a running print: a slot that empties there
  2413. # is a filament runout, and the spool is still in the
  2414. # AMS. `spoolman_slot_assignments` is how a tag-less
  2415. # spool assigned through the Bambuddy UI is resolved at
  2416. # completion (#1459), so deleting the row mid-print
  2417. # loses the runout segment's usage — the same failure
  2418. # the internal inventory's auto-unlink had.
  2419. #
  2420. # Nor when firmware's presence bit says the slot is
  2421. # occupied. parse_ams_tray calls a tray with no type or
  2422. # no colour empty, and a spool the AMS cannot read has
  2423. # neither until something configures it — so a tag-less
  2424. # spool assigned through the UI had its row deleted by
  2425. # the first idle push after it was inserted. Same
  2426. # deletion as the internal inventory's in #3100, same
  2427. # answer, so the two modes stay in step.
  2428. if not printing_now and spool_present(tray_data) is not True:
  2429. empty_slots.append((ams_id, tray_id_raw))
  2430. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2431. continue
  2432. spool_tag = (
  2433. tray.tray_uuid
  2434. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2435. else tray.tag_uid
  2436. )
  2437. # Provide the hint only when no RFID is available
  2438. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2439. try:
  2440. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2441. result = await client.sync_ams_tray(
  2442. tray,
  2443. printer_name,
  2444. # Per-print tracking is the only weight writer (#1119).
  2445. # AMS auto-sync still maintains spool metadata / slot
  2446. # assignments but no longer touches remaining_weight.
  2447. disable_weight_sync=True,
  2448. cached_spools=cached_spools,
  2449. inventory_remaining=inv_remaining,
  2450. spoolman_spool_id_hint=hint,
  2451. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2452. )
  2453. if result is None and spool_tag and not auto_add_unknown_rfid:
  2454. # Spoolman skipped auto-create per user setting — surface
  2455. # the slot so the UI can offer "+ Add to inventory".
  2456. await _broadcast_unknown_tag(
  2457. printer_id=printer_id,
  2458. ams_id=ams_id,
  2459. tray_id=tray.tray_id,
  2460. tag_uid=tray.tag_uid or "",
  2461. tray_uuid=tray.tray_uuid or "",
  2462. tray_type=tray.tray_type,
  2463. tray_color=tray.tray_color,
  2464. tray_sub_brands=tray.tray_sub_brands,
  2465. tray_count=len(trays),
  2466. )
  2467. elif result:
  2468. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2469. if result:
  2470. synced += 1
  2471. if result.get("id"):
  2472. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2473. # If a new spool was created, add it to the cache
  2474. # so subsequent trays can find it if they reference the same tag
  2475. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2476. if not spool_exists:
  2477. cached_spools.append(result)
  2478. logger.debug(
  2479. "[Printer %s] Added newly created spool %s to cache",
  2480. printer_id,
  2481. result["id"],
  2482. )
  2483. # Reconcile slot_preset_mappings (the same row internal
  2484. # mode keeps in sync via inventory + spool_tag_matcher).
  2485. # Without this the slot card surfaces the previous spool's
  2486. # preset name — same bug shape, different inventory mode.
  2487. from backend.app.services.slot_preset_writer import (
  2488. upsert_slot_preset_for_spoolman_spool,
  2489. )
  2490. await upsert_slot_preset_for_spoolman_spool(
  2491. db=db,
  2492. spoolman_spool=result,
  2493. tray_info_idx=tray.tray_info_idx or "",
  2494. tray_sub_brands=tray.tray_sub_brands or "",
  2495. tray_type=tray.tray_type or "",
  2496. printer_id=printer_id,
  2497. ams_id=ams_id,
  2498. tray_id=tray.tray_id,
  2499. )
  2500. except Exception as e:
  2501. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2502. if synced > 0:
  2503. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2504. # Persist slot assignment changes to the local table
  2505. if slot_changes or empty_slots:
  2506. try:
  2507. for ams_id, tray_id, spool_id in slot_changes:
  2508. await db.execute(
  2509. text(
  2510. "INSERT INTO spoolman_slot_assignments"
  2511. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2512. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2513. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2514. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2515. ),
  2516. {
  2517. "printer_id": printer_id,
  2518. "ams_id": ams_id,
  2519. "tray_id": tray_id,
  2520. "spool_id": spool_id,
  2521. },
  2522. )
  2523. for ams_id, tray_id in empty_slots:
  2524. await db.execute(
  2525. delete(SpoolmanSlotAssignment).where(
  2526. SpoolmanSlotAssignment.printer_id == printer_id,
  2527. SpoolmanSlotAssignment.ams_id == ams_id,
  2528. SpoolmanSlotAssignment.tray_id == tray_id,
  2529. )
  2530. )
  2531. await db.commit()
  2532. except Exception as e:
  2533. await db.rollback()
  2534. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2535. else:
  2536. # Tell open browsers the slot changed. This loop rewrites
  2537. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2538. # above, and the AMS slot card reads that row ahead of the
  2539. # live tray_info_idx -- so with no event the card keeps
  2540. # showing the previous spool's preset name. Internal mode
  2541. # raises spool_auto_assigned for the same reason; this loop
  2542. # broadcast nothing at all, which made Spoolman mode the
  2543. # worse half of the same bug. On the else branch so a
  2544. # failed commit stays silent and a broadcast failure cannot
  2545. # roll back rows that are already committed.
  2546. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2547. await ws_manager.broadcast(
  2548. {
  2549. "type": "spool_assignment_changed",
  2550. "printer_id": printer_id,
  2551. "ams_id": ams_id,
  2552. "tray_id": tray_id,
  2553. }
  2554. )
  2555. except Exception as e:
  2556. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2557. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2558. """Capture a camera snapshot for notification image attachment.
  2559. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2560. Uses: external camera > buffered frame > fresh capture.
  2561. """
  2562. if not printer:
  2563. return None
  2564. try:
  2565. from backend.app.api.routes.settings import get_setting
  2566. async with async_session() as db:
  2567. capture_enabled = await get_setting(db, "capture_finish_photo")
  2568. if capture_enabled is not None and capture_enabled.lower() != "true":
  2569. return None
  2570. # Try external camera first
  2571. if printer.external_camera_enabled and printer.external_camera_url:
  2572. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2573. from backend.app.api.routes.camera import live_frame_for_capture
  2574. from backend.app.services.external_camera import capture_frame
  2575. # An external camera allows one reader, so capturing while a viewer
  2576. # is attached fails (#2707). A None here falls through to the paths
  2577. # below exactly as a failed capture did.
  2578. defer, buffered = live_frame_for_capture(printer_id)
  2579. if defer:
  2580. frame_data = buffered
  2581. else:
  2582. frame_data = await capture_frame(
  2583. printer.external_camera_url,
  2584. printer.external_camera_type or "mjpeg",
  2585. snapshot_url=printer.external_camera_snapshot_url,
  2586. )
  2587. if frame_data and len(frame_data) <= 2_500_000:
  2588. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2589. return _apply_camera_rotation(frame_data, printer, logger)
  2590. # Try buffered frame from active stream
  2591. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2592. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2593. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2594. buffered_frame = get_buffered_frame(printer_id)
  2595. if (active_for_printer or active_chamber) and buffered_frame:
  2596. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2597. if len(buffered_frame) <= 2_500_000:
  2598. return _apply_camera_rotation(buffered_frame, printer, logger)
  2599. # Fresh capture from printer camera
  2600. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2601. from backend.app.services.camera import capture_camera_frame_bytes
  2602. frame_data = await capture_camera_frame_bytes(
  2603. printer.ip_address, printer.access_code, printer.model, timeout=15
  2604. )
  2605. if frame_data and len(frame_data) <= 2_500_000:
  2606. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2607. return _apply_camera_rotation(frame_data, printer, logger)
  2608. except Exception as e:
  2609. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2610. return None
  2611. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2612. """#1867: bank a recent in-print camera frame for the finish photo.
  2613. Called on every layer change and (#2547) on every print-progress advance.
  2614. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2615. path has a pre-End-G-code image for prints that end with a plate swap.
  2616. Both drivers are print telemetry that stops the instant printing ends: no
  2617. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2618. plate swap) executes. So the last banked frame is always the finished print,
  2619. never the swapped plate — that property is what the #1867 path relies on and
  2620. it must survive any change to the throttle below.
  2621. Layer changes alone were not enough: they stop when the *final* layer
  2622. begins, which on a three-minute last layer left the bank stale by the whole
  2623. length of that layer (#2547). Progress keeps ticking through it.
  2624. Best-effort: any failure just leaves the previous banked frame.
  2625. """
  2626. logger = logging.getLogger(__name__)
  2627. client = printer_manager.get_client(printer_id)
  2628. state = client.state if client else None
  2629. if not state or state.state != "RUNNING":
  2630. return
  2631. # Only during actual extrusion — firmware ticks layer_num during the
  2632. # pre-print calibration sequence, whose sub-stages are non-zero.
  2633. if state.mc_print_sub_stage not in (None, 0):
  2634. return
  2635. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2636. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2637. # now that progress advances also drive banking, that exemption would fire a
  2638. # camera grab on every percent tick of the last layer. Bambu printers accept
  2639. # one RTSP client at a time, so each grab contends with the live view.
  2640. now = time.monotonic()
  2641. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2642. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2643. return
  2644. total = state.total_layers or 0
  2645. try:
  2646. async with async_session() as db:
  2647. from backend.app.models.printer import Printer
  2648. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2649. printer = result.scalar_one_or_none()
  2650. if not printer:
  2651. return
  2652. # Reuses the notification snapshot path, which honours the
  2653. # `capture_finish_photo` setting (returns None when disabled) so we
  2654. # don't bank frames the user never asked for.
  2655. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2656. if frame:
  2657. _inprint_frame_bank[printer_id] = frame
  2658. _inprint_frame_bank_ts[printer_id] = now
  2659. logger.debug(
  2660. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2661. printer_id,
  2662. layer_num,
  2663. total,
  2664. len(frame),
  2665. )
  2666. except Exception as e:
  2667. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2668. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2669. """Apply camera rotation to snapshot image if configured."""
  2670. from backend.app.services.camera import apply_camera_rotation
  2671. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2672. async def _send_print_start_notification(
  2673. printer_id: int,
  2674. data: dict,
  2675. archive_data: dict | None = None,
  2676. logger=None,
  2677. ):
  2678. """Helper to send print start notification with optional archive data."""
  2679. if logger is None:
  2680. logger = logging.getLogger(__name__)
  2681. try:
  2682. async with async_session() as db:
  2683. from backend.app.models.printer import Printer
  2684. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2685. printer = result.scalar_one_or_none()
  2686. printer_name = printer.name if printer else f"Printer {printer_id}"
  2687. # Capture camera snapshot for notification image attachment
  2688. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2689. if image_data:
  2690. if archive_data is None:
  2691. archive_data = {}
  2692. archive_data["image_data"] = image_data
  2693. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  2694. # Send user-specific email notification for print start
  2695. if archive_data and archive_data.get("created_by_id"):
  2696. await notification_service.send_user_print_email(
  2697. event_type="user_print_start",
  2698. created_by_id=archive_data["created_by_id"],
  2699. printer_name=printer_name,
  2700. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  2701. db=db,
  2702. )
  2703. except Exception as e:
  2704. logger.warning("Notification on_print_start failed: %s", e)
  2705. async def _dispatch_user_print_email(
  2706. status: str,
  2707. created_by_id: int | None,
  2708. printer_name: str,
  2709. filename: str,
  2710. db,
  2711. ) -> None:
  2712. """Send a user-specific print-completion email based on print status.
  2713. Maps the normalised print status to the correct event type and delegates
  2714. to :meth:`NotificationService.send_user_print_email`. A single helper
  2715. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  2716. "stopped"`` dispatch block at every call site.
  2717. Does nothing if *created_by_id* is ``None``.
  2718. """
  2719. if created_by_id is None:
  2720. return
  2721. if status == "completed":
  2722. event_type = "user_print_complete"
  2723. elif status == "failed":
  2724. event_type = "user_print_failed"
  2725. elif status in ("stopped", "aborted", "cancelled"):
  2726. event_type = "user_print_stopped"
  2727. else:
  2728. return
  2729. await notification_service.send_user_print_email(
  2730. event_type=event_type,
  2731. created_by_id=created_by_id,
  2732. printer_name=printer_name,
  2733. filename=filename,
  2734. db=db,
  2735. )
  2736. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  2737. """Extract printable objects from an archive's 3MF file and store in printer state."""
  2738. try:
  2739. from backend.app.services.archive import extract_printable_objects_from_archive
  2740. client = printer_manager.get_client(printer_id)
  2741. if not client:
  2742. return
  2743. # Extract with positions for UI overlay, scoped to the plate that
  2744. # is printing — resolve_plate_id is the same resolver /cover uses,
  2745. # so the object list can't disagree with the thumbnail it is drawn
  2746. # over (#2522).
  2747. printable_objects, bbox_all = extract_printable_objects_from_archive(
  2748. app_settings.base_dir / archive.file_path,
  2749. plate_number=resolve_plate_id(client.state),
  2750. )
  2751. if printable_objects:
  2752. client.state.printable_objects = printable_objects
  2753. client.state.printable_objects_bbox_all = bbox_all
  2754. client.state.skipped_objects = []
  2755. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  2756. except Exception as e:
  2757. logger.debug("Failed to extract printable objects from archive: %s", e)
  2758. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  2759. """Put the skip-objects list back after a restart mid-print.
  2760. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  2761. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  2762. which the #1304 guard suppresses on the first RUNNING push after startup.
  2763. Everything else this hook restores (the archive, the usage-tracking session,
  2764. the timelapse baseline) was already handled; the object list was not, so a
  2765. restart mid-print took skip-objects away for the rest of that print.
  2766. Nothing recovered it either: the printer card gates its Skip button on the
  2767. object count, and the one endpoint that can rebuild the list is reachable
  2768. only from the modal that button opens.
  2769. Anchored on ``subtask_id``, which the firmware mints per print, so a
  2770. leftover ``status="printing"`` row from a completion we never saw cannot
  2771. hand this print someone else's objects. Without one, nothing is loaded
  2772. rather than guessed — the reload path on ``GET /print/objects`` covers that
  2773. case on demand.
  2774. """
  2775. client = printer_manager.get_client(printer_id)
  2776. if client is None or client.state.printable_objects:
  2777. return
  2778. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  2779. if subtask_id in ("", "0"):
  2780. return
  2781. from backend.app.models.archive import PrintArchive
  2782. archive = await db.scalar(
  2783. select(PrintArchive)
  2784. .where(
  2785. PrintArchive.printer_id == printer_id,
  2786. PrintArchive.status == "printing",
  2787. PrintArchive.subtask_id == subtask_id,
  2788. )
  2789. .order_by(PrintArchive.created_at.desc())
  2790. .limit(1)
  2791. )
  2792. if archive is not None:
  2793. _load_objects_from_archive(archive, printer_id, logger)
  2794. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  2795. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  2796. # past it; the second covers a handshake that failed again on the way back and
  2797. # armed a fresh one. Module-level so tests can shrink them.
  2798. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  2799. # Retry ladder for the other temporary give-up: the file service answered and
  2800. # the transfer still did not finish, which at print start is usually the printer
  2801. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  2802. # to expire here, so the first attempt comes early -- #3063's reporter had the
  2803. # same 19MB file complete 48 seconds after the download budget ran out. The later
  2804. # two cover a printer that stays busy well into the print.
  2805. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  2806. # printer_id -> the in-flight retry task, so print completion can cancel it.
  2807. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  2808. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  2809. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  2810. # by view, so two views race), the cool-off retry task, and print completion.
  2811. # Without this they each read file_path == "" and each run a full copy, so the row
  2812. # ends up pointing at one timestamped directory while the others sit orphaned.
  2813. #
  2814. # Keyed by printer rather than archive because a printer runs one print at a time,
  2815. # which makes the two equally strong here — and it bounds the dict by printer
  2816. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  2817. # done safely: `Lock.locked()` reads False between release and the queued waiter
  2818. # resuming, so "no waiters" is not a question this API can answer.
  2819. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  2820. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2821. """Fill in a no-3MF archive from a 3MF that turned up later.
  2822. Returns True when the row was upgraded. Safe to call speculatively: it
  2823. verifies the archive still exists, is still a fallback, and that the file
  2824. is a readable 3MF before touching anything.
  2825. Serialised per printer — see ``_fallback_recovery_locks``.
  2826. """
  2827. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  2828. async with lock:
  2829. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  2830. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2831. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  2832. import zipfile
  2833. from backend.app.models.archive import PrintArchive
  2834. from backend.app.services.archive import ArchiveService
  2835. logger = logging.getLogger(__name__)
  2836. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  2837. return False
  2838. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  2839. # A truncated or half-written download is worse than no download: it
  2840. # would replace an honest empty archive with wrong metadata.
  2841. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  2842. return False
  2843. async with async_session() as db:
  2844. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2845. if archive is None or archive.deleted_at is not None:
  2846. return False
  2847. if archive.file_path:
  2848. # Already recovered, or never was a fallback. Either way there is a
  2849. # real 3MF attached and overwriting it is not this function's job.
  2850. return False
  2851. print_data = (archive.extra_data or {}).get("_print_data") or {}
  2852. service = ArchiveService(db)
  2853. recovered = await service.archive_print(
  2854. printer_id=printer_id,
  2855. source_file=source_3mf,
  2856. print_data={**print_data, "status": archive.status or "printing"},
  2857. subtask_id=archive.subtask_id,
  2858. update_archive_id=archive.id,
  2859. )
  2860. if recovered is None:
  2861. return False
  2862. logger.info(
  2863. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  2864. archive_id,
  2865. source_3mf,
  2866. recovered.file_size,
  2867. )
  2868. # `archive_updated`, not `archive_created` — the row was already on the
  2869. # Archives page as an empty card and is now filled in, not new.
  2870. await ws_manager.send_archive_updated(
  2871. {
  2872. "id": recovered.id,
  2873. "printer_id": recovered.printer_id,
  2874. "filename": recovered.filename,
  2875. "print_name": recovered.print_name,
  2876. "status": recovered.status,
  2877. }
  2878. )
  2879. return True
  2880. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  2881. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  2882. Called from the paths that pull a 3MF for a print that is already under way
  2883. — chiefly the cover endpoint, which downloads the very file the archive flow
  2884. could not get and, before #2957, used it for a thumbnail and nothing else.
  2885. The bytes are already local, so this costs a parse and a row update.
  2886. No-op when the running print has a real archive, which is the common case.
  2887. """
  2888. from backend.app.models.archive import PrintArchive
  2889. logger = logging.getLogger(__name__)
  2890. # `_active_prints` is keyed on the raw names seen at print start — the
  2891. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  2892. # Callers here arrive with whichever variant their own path produced, so
  2893. # match on the same normalization the download cache uses rather than on an
  2894. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  2895. # endpoint find an archive registered under "Desktop_Goose".
  2896. wanted = normalize_3mf_name(name)
  2897. archive_id = None
  2898. for (key_printer_id, key_name), value in list(_active_prints.items()):
  2899. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  2900. archive_id = value
  2901. break
  2902. if archive_id is None:
  2903. return False
  2904. async with async_session() as db:
  2905. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2906. # Cheap pre-check so the common case (a normal archive) does no work.
  2907. if archive is None or archive.file_path or archive.deleted_at is not None:
  2908. return False
  2909. try:
  2910. return await _recover_fallback_archive(archive_id, path, printer_id)
  2911. except Exception as e:
  2912. # Recovery is opportunistic. A failure here must never take down the
  2913. # caller, which is usually just trying to render a thumbnail.
  2914. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  2915. return False
  2916. def _schedule_fallback_3mf_retry(
  2917. printer_id: int,
  2918. archive_id: int,
  2919. filenames: list[str],
  2920. delays: tuple[float, ...] | None = None,
  2921. reason: str = REASON_FTPS_COOLOFF,
  2922. ) -> None:
  2923. """Re-attempt the 3MF download after a temporary give-up.
  2924. ``reason`` says which give-up this is, and picks the default ladder: an
  2925. FTPS cool-off has to be waited out, while a transfer that timed out under
  2926. contention is worth asking about again straight away (#3063). It is only
  2927. read for the ladder and the log line -- the retry itself is identical, since
  2928. in both cases the file is on the printer and the last attempt at it failed
  2929. for a reason that does not last.
  2930. """
  2931. logger = logging.getLogger(__name__)
  2932. if delays is None:
  2933. delays = (
  2934. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  2935. if reason == REASON_FTP_TRANSFER_FAILED
  2936. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  2937. )
  2938. async def _retry() -> None:
  2939. from backend.app.models.archive import PrintArchive
  2940. from backend.app.models.printer import Printer
  2941. for delay in delays:
  2942. await asyncio.sleep(delay)
  2943. async with async_session() as db:
  2944. archive = (
  2945. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2946. ).scalar_one_or_none()
  2947. if archive is None or archive.deleted_at is not None or archive.file_path:
  2948. return
  2949. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  2950. if printer is None:
  2951. return
  2952. # Read the fields while the session is open rather than touching
  2953. # a detached instance minutes later, mid-download.
  2954. printer_ip = printer.ip_address
  2955. printer_code = printer.access_code
  2956. printer_model = printer.model
  2957. # Someone else may have fetched it in the meantime — the cover
  2958. # endpoint routinely does, and its copy is the same bytes.
  2959. for name in filenames:
  2960. cached = get_cached_3mf(printer_id, name)
  2961. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  2962. return
  2963. if ftps_handshake_blocked(printer_ip):
  2964. logger.info(
  2965. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  2966. printer_id,
  2967. archive_id,
  2968. )
  2969. continue
  2970. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  2971. for candidate in filenames:
  2972. # Bare name only. These come from the print-start flow, which
  2973. # already strips the path, but the local temp write must not
  2974. # depend on that holding for every future caller — a name that
  2975. # is absolute or contains ".." would otherwise escape the data
  2976. # volume via the `/` operator.
  2977. name = Path(candidate).name
  2978. if not name or name in (".", ".."):
  2979. continue
  2980. if not name.endswith(".3mf"):
  2981. name = f"{name}.3mf"
  2982. temp_path = app_settings.archive_dir / "temp" / name
  2983. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2984. try:
  2985. hit = await download_file_try_paths_async(
  2986. printer_ip,
  2987. printer_code,
  2988. ftp_probe_paths(name),
  2989. temp_path,
  2990. socket_timeout=ftp_timeout,
  2991. printer_model=printer_model,
  2992. )
  2993. except Exception as e:
  2994. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  2995. continue
  2996. if not hit:
  2997. continue
  2998. cache_3mf_download(printer_id, name, temp_path)
  2999. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3000. return
  3001. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3002. async def _guarded() -> None:
  3003. try:
  3004. await _retry()
  3005. except asyncio.CancelledError:
  3006. raise
  3007. except Exception as e:
  3008. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3009. finally:
  3010. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3011. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3012. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3013. if existing and not existing.done():
  3014. existing.cancel()
  3015. task = asyncio.create_task(_guarded())
  3016. _fallback_3mf_retry_tasks[printer_id] = task
  3017. logger.info(
  3018. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3019. archive_id,
  3020. reason,
  3021. printer_id,
  3022. ", ".join(f"{d:g}s" for d in delays),
  3023. )
  3024. async def on_print_start(printer_id: int, data: dict):
  3025. """Handle print start - archive the 3MF file immediately."""
  3026. logger = logging.getLogger(__name__)
  3027. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3028. # Clear any stale user-stopped flag from previous print cycles
  3029. _user_stopped_printers.discard(printer_id)
  3030. _kill_switch_notification_tasks.pop(printer_id, None)
  3031. # #1721: drop any leftover pre-captured finish frame from a prior print
  3032. # so a never-consumed cache entry can't bleed into the new print's photo.
  3033. _stage22_finish_frames.pop(printer_id, None)
  3034. # #1867: same for the in-print frame bank — a queued print must not reuse
  3035. # the previous job's banked frame.
  3036. _inprint_frame_bank.pop(printer_id, None)
  3037. _inprint_frame_bank_ts.pop(printer_id, None)
  3038. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3039. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3040. # print's flag instead of inheriting it.
  3041. print_dispatch_context.adopt(printer_id)
  3042. # Cancel any active bed cooldown waiter for this printer
  3043. if _bed_cool_waiters.pop(printer_id, None):
  3044. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3045. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3046. from backend.app.api.routes.printers import clear_cover_cache
  3047. clear_cover_cache(printer_id)
  3048. await ws_manager.send_print_start(printer_id, data)
  3049. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3050. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3051. # MQTT relay - publish print start
  3052. try:
  3053. printer_info = printer_manager.get_printer(printer_id)
  3054. if printer_info:
  3055. await mqtt_relay.on_print_start(
  3056. printer_id,
  3057. printer_info.name,
  3058. printer_info.serial_number,
  3059. data.get("filename", ""),
  3060. data.get("subtask_name", ""),
  3061. )
  3062. except Exception:
  3063. pass # Don't fail print start callback if MQTT fails
  3064. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3065. # and mapping, and the seeded tray-change log.
  3066. #
  3067. # Unconditional, for both inventory backends. This only *captures* — the
  3068. # writing is still split, with the internal tracker skipped at completion
  3069. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3070. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3071. # tray-change log, and that log is the only record of which spool fed
  3072. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3073. # it on one side only would leave Spoolman users with the mid-print
  3074. # restart bug this fixes for everyone else.
  3075. try:
  3076. async with async_session() as db:
  3077. from backend.app.api.routes.settings import get_setting
  3078. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3079. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3080. await usage_on_print_start(
  3081. printer_id,
  3082. data,
  3083. printer_manager,
  3084. db=db,
  3085. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3086. )
  3087. except Exception as e:
  3088. logger.warning("Usage tracker on_print_start failed: %s", e)
  3089. # Track if notification was sent (to avoid sending twice)
  3090. notification_sent = False
  3091. # Smart plug automation: turn on plug when print starts
  3092. try:
  3093. async with async_session() as db:
  3094. await smart_plug_manager.on_print_start(printer_id, db)
  3095. except Exception as e:
  3096. logger.warning("Smart plug on_print_start failed: %s", e)
  3097. async with async_session() as db:
  3098. from backend.app.models.printer import Printer
  3099. from backend.app.services.bambu_ftp import list_files_async
  3100. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3101. printer = result.scalar_one_or_none()
  3102. # Plate detection check - pause if objects detected on build plate
  3103. logger.info(
  3104. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3105. )
  3106. if printer and printer.plate_detection_enabled:
  3107. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3108. # Release the pooled DB connection before the plate-detection camera
  3109. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3110. # printer SELECT has run so far — nothing to persist — so this commit
  3111. # is a data-noop that ends the read transaction and returns the
  3112. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3113. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3114. # archive lookups below re-acquire a fresh connection on next execute.
  3115. await db.commit()
  3116. try:
  3117. from backend.app.services.plate_detection import check_plate_empty
  3118. # Build ROI tuple from printer settings if available
  3119. roi = None
  3120. if all(
  3121. [
  3122. printer.plate_detection_roi_x is not None,
  3123. printer.plate_detection_roi_y is not None,
  3124. printer.plate_detection_roi_w is not None,
  3125. printer.plate_detection_roi_h is not None,
  3126. ]
  3127. ):
  3128. roi = (
  3129. printer.plate_detection_roi_x,
  3130. printer.plate_detection_roi_y,
  3131. printer.plate_detection_roi_w,
  3132. printer.plate_detection_roi_h,
  3133. )
  3134. # Auto-turn on chamber light if it's off for better detection
  3135. light_was_off = False
  3136. client = printer_manager.get_client(printer_id)
  3137. if client and client.state:
  3138. light_was_off = not client.state.chamber_light
  3139. if light_was_off:
  3140. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3141. client.set_chamber_light(True)
  3142. # Wait for light to physically turn on and camera to adjust exposure
  3143. await asyncio.sleep(2.5)
  3144. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3145. plate_result = await check_plate_empty(
  3146. printer_id=printer_id,
  3147. ip_address=printer.ip_address,
  3148. access_code=printer.access_code,
  3149. model=printer.model,
  3150. include_debug_image=False,
  3151. external_camera_url=printer.external_camera_url,
  3152. external_camera_type=printer.external_camera_type,
  3153. use_external=printer.external_camera_enabled,
  3154. roi=roi,
  3155. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3156. )
  3157. # Restore chamber light to original state
  3158. if light_was_off and client:
  3159. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3160. client.set_chamber_light(False)
  3161. if not plate_result.needs_calibration and not plate_result.is_empty:
  3162. # Objects detected - pause the print!
  3163. logger.warning(
  3164. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3165. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3166. )
  3167. client = printer_manager.get_client(printer_id)
  3168. if client:
  3169. client.pause_print()
  3170. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3171. # Send notification about plate not empty
  3172. await ws_manager.broadcast(
  3173. {
  3174. "type": "plate_not_empty",
  3175. "printer_id": printer_id,
  3176. "printer_name": printer.name,
  3177. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3178. }
  3179. )
  3180. # Also send push notification
  3181. try:
  3182. await notification_service.on_plate_not_empty(
  3183. printer_id=printer_id,
  3184. printer_name=printer.name,
  3185. db=db,
  3186. difference_percent=plate_result.difference_percent,
  3187. )
  3188. except Exception as notif_err:
  3189. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3190. else:
  3191. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3192. except Exception as plate_err:
  3193. # Don't block print on plate detection errors
  3194. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3195. if not printer:
  3196. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3197. if not notification_sent:
  3198. await _send_print_start_notification(printer_id, data, logger=logger)
  3199. return
  3200. if not printer.auto_archive:
  3201. # auto-archive disabled — check if there's an expected print (dispatched
  3202. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3203. # If so, fall through to the expected-print handling below so the archive
  3204. # is tracked in _active_prints and usage tracking works at completion.
  3205. _fn = data.get("filename", "")
  3206. _sn = data.get("subtask_name", "")
  3207. _check_keys: list[tuple[int, str]] = []
  3208. if _sn:
  3209. _check_keys += [
  3210. (printer_id, _sn),
  3211. (printer_id, f"{_sn}.3mf"),
  3212. (printer_id, f"{_sn}.gcode.3mf"),
  3213. ]
  3214. if _fn:
  3215. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3216. _check_keys.append((printer_id, _base_fn))
  3217. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3218. _check_keys += [
  3219. (printer_id, _no_archive_base),
  3220. (printer_id, f"{_no_archive_base}.3mf"),
  3221. ]
  3222. _has_expected = any(k in _expected_prints for k in _check_keys)
  3223. if not _has_expected:
  3224. # No expected print — truly external print (started from slicer/touchscreen)
  3225. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3226. if not notification_sent:
  3227. _no_archive_creator: int | None = None
  3228. for _key in _check_keys:
  3229. _expected_prints.pop(_key, None)
  3230. _expected_print_registered_at.pop(_key, None)
  3231. popped_creator = _expected_print_creators.pop(_key, None)
  3232. if _no_archive_creator is None:
  3233. _no_archive_creator = popped_creator
  3234. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3235. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3236. return
  3237. else:
  3238. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3239. # Get the filename and subtask_name
  3240. filename = data.get("filename", "")
  3241. subtask_name = data.get("subtask_name", "")
  3242. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3243. # present, it lets us match an archive across a backend restart (#972):
  3244. # same id → same print → resume the existing row instead of cancelling
  3245. # it and recreating from scratch (which loses started_at). Treat "0"
  3246. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3247. raw_mqtt = data.get("raw_data") or {}
  3248. subtask_id = raw_mqtt.get("subtask_id")
  3249. if subtask_id is not None:
  3250. subtask_id = str(subtask_id).strip()
  3251. if subtask_id in ("", "0"):
  3252. subtask_id = None
  3253. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3254. # Skip the printer's own jobs — a calibration run is not a user's print.
  3255. # See is_internal_printer_job for what counts and why both fields are
  3256. # tested; the pressure-advance line reports as a subtask name with no
  3257. # /usr/ path, which the old prefix-only test here missed entirely.
  3258. #
  3259. # No notification either. The event describes the printer calibrating
  3260. # itself, so "Print started" is as wrong as the archive was, and the
  3261. # matching completion is suppressed in on_print_complete for the same
  3262. # reason.
  3263. if is_internal_printer_job(filename, subtask_name):
  3264. logger.info(
  3265. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3266. filename,
  3267. subtask_name,
  3268. )
  3269. return
  3270. if not filename and not subtask_name:
  3271. # Send notification without archive data (no filename)
  3272. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3273. if not notification_sent:
  3274. await _send_print_start_notification(printer_id, data, logger=logger)
  3275. return
  3276. # Check if this is an expected print from reprint/scheduled
  3277. # Build list of possible keys to check
  3278. expected_keys = []
  3279. if subtask_name:
  3280. expected_keys.append((printer_id, subtask_name))
  3281. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3282. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3283. if filename:
  3284. fname = filename.split("/")[-1] if "/" in filename else filename
  3285. expected_keys.append((printer_id, fname))
  3286. # Strip extensions to match
  3287. base = fname.replace(".gcode", "").replace(".3mf", "")
  3288. expected_keys.append((printer_id, base))
  3289. expected_keys.append((printer_id, f"{base}.3mf"))
  3290. expected_archive_id = None
  3291. for key in expected_keys:
  3292. expected_archive_id = _expected_prints.pop(key, None)
  3293. _expected_print_registered_at.pop(key, None)
  3294. if expected_archive_id:
  3295. # Clean up other possible keys for this print
  3296. for other_key in expected_keys:
  3297. _expected_prints.pop(other_key, None)
  3298. _expected_print_registered_at.pop(other_key, None)
  3299. break
  3300. if expected_archive_id:
  3301. # This is a reprint/scheduled print - use existing archive, don't create new one
  3302. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3303. from backend.app.models.archive import PrintArchive
  3304. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3305. archive = result.scalar_one_or_none()
  3306. if archive:
  3307. # Update archive status to printing
  3308. archive.status = "printing"
  3309. archive.started_at = datetime.now(timezone.utc)
  3310. # Reprint of an archive reuses the source row. Without resetting
  3311. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3312. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3313. # extracts the *original* print's last frame, which then ships in
  3314. # the completion notification (#1707). Clear the path so the
  3315. # scanner runs fresh; also unlink the old video file so reprints
  3316. # don't accumulate orphans in the archive directory. Photos list
  3317. # is left alone — accumulating one finish photo per run is fine.
  3318. # The print-start baseline (#2704) is stale for the same reason:
  3319. # it describes the printer before the previous run. The capture
  3320. # below overwrites it, but clear it here too so an early failure
  3321. # can't leave the scan diffing against the wrong snapshot.
  3322. archive.timelapse_baseline = None
  3323. stale_timelapse_relpath = archive.timelapse_path
  3324. if stale_timelapse_relpath:
  3325. archive.timelapse_path = None
  3326. try:
  3327. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3328. if stale_path.is_file():
  3329. stale_path.unlink()
  3330. logger.info(
  3331. "Deleted stale timelapse %s on reprint of archive %s",
  3332. stale_timelapse_relpath,
  3333. expected_archive_id,
  3334. )
  3335. except OSError as e:
  3336. logger.warning(
  3337. "Failed to delete stale timelapse %s on reprint: %s",
  3338. stale_timelapse_relpath,
  3339. e,
  3340. )
  3341. # Persist a restart-stable id so a later restart resumes this
  3342. # archive by subtask_id instead of name-matching + duplicating
  3343. # it (#1485). The printer often hasn't echoed subtask_id back
  3344. # this soon after dispatch, so fall back to the id Bambuddy
  3345. # minted when it sent the print command. Scoped to this
  3346. # expected-print branch on purpose: an expected match means
  3347. # Bambuddy dispatched this exact print in this process, so the
  3348. # client's last-dispatch id genuinely belongs to it — using it
  3349. # for an externally-started print could mis-tag the archive.
  3350. effective_subtask_id = subtask_id
  3351. if not effective_subtask_id:
  3352. _client = printer_manager.get_client(printer_id)
  3353. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3354. if _dispatched:
  3355. effective_subtask_id = str(_dispatched).strip() or None
  3356. # Update on first-set OR on reprint (the queue dispatcher mints
  3357. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3358. # the rewrite for reprints leaves the archive holding the FIRST
  3359. # run's id; if MQTT then reconnects mid-print, the reconciler
  3360. # (#1542) compares the stale stored id against the printer's
  3361. # live id, sees a mismatch, and synthesises a bogus PRINT
  3362. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3363. # in #1807. Inequality check preserves the noop-on-stable-push
  3364. # behaviour the earlier `not archive.subtask_id` guard provided.
  3365. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3366. archive.subtask_id = effective_subtask_id
  3367. # #1403 follow-up: VP-queue archives are created with
  3368. # printer_id=None at queue-add time (we don't know which
  3369. # printer will run the job yet). When the print actually
  3370. # starts on a specific printer the expected-archive lookup
  3371. # used to skip this assignment, leaving printer_id=None
  3372. # forever — which then disables the "Scan for timelapse"
  3373. # button in ArchivesPage (gated on !archive.printer_id).
  3374. if archive.printer_id != printer_id:
  3375. archive.printer_id = printer_id
  3376. await db.commit()
  3377. # Track as active print
  3378. _active_prints[(printer_id, archive.filename)] = archive.id
  3379. if subtask_name:
  3380. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3381. # Start timelapse session if external camera is enabled (#1353).
  3382. # Queue / VP-dispatched prints land here in the expected-archive
  3383. # branch and used to skip start_session entirely — frames were
  3384. # never captured and the post-print stitch silently returned None.
  3385. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3386. # Inject ams_mapping into usage tracker session — the session was created
  3387. # before expected-print promotion, so it may have ams_mapping=None when
  3388. # the MQTT request topic subscription failed (common on P1S/A1).
  3389. _stored_map = _print_ams_mappings.get(expected_archive_id)
  3390. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  3391. if _stored_map or _stored_plate_id is not None:
  3392. try:
  3393. from backend.app.services.usage_tracker import _active_sessions
  3394. _ut_session = _active_sessions.get(printer_id)
  3395. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  3396. _ut_session.ams_mapping = _stored_map
  3397. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  3398. # plate_id injection covers direct-Print of plate N of a multi-plate
  3399. # 3MF — queue prints already capture it via the on_print_start queue
  3400. # lookup, but direct-Print never goes through the queue (#1697).
  3401. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  3402. _ut_session.plate_id = _stored_plate_id
  3403. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  3404. except Exception:
  3405. pass
  3406. # Set up energy tracking (#941: persist start on archive row)
  3407. await _record_energy_start(archive, printer_id, db, context="expected-print")
  3408. await ws_manager.send_archive_updated(
  3409. {
  3410. "id": archive.id,
  3411. "status": "printing",
  3412. }
  3413. )
  3414. # Send notification with archive data (reprint/scheduled)
  3415. if not notification_sent:
  3416. # Use archive's created_by_id; fall back to the creator registered via
  3417. # register_expected_print (handles library-file-based queue items where
  3418. # the freshly-created archive has no created_by_id yet).
  3419. # Pop ALL matching keys so no stale entries remain in the dict.
  3420. fallback_creator = None
  3421. for key in expected_keys:
  3422. popped = _expected_print_creators.pop(key, None)
  3423. if fallback_creator is None:
  3424. fallback_creator = popped
  3425. archive_data = {
  3426. "print_time_seconds": archive.print_time_seconds,
  3427. "created_by_id": archive.created_by_id or fallback_creator,
  3428. }
  3429. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3430. # Extract printable objects from the archived 3MF file
  3431. _load_objects_from_archive(archive, printer_id, logger)
  3432. # Store Spoolman tracking data for per-filament usage reporting
  3433. try:
  3434. await _store_spoolman_print_data(
  3435. printer_id,
  3436. archive.id,
  3437. archive.file_path,
  3438. db,
  3439. printer_manager,
  3440. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3441. plate_id=_get_start_plate_id(archive.id),
  3442. )
  3443. except Exception as e:
  3444. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3445. # Capture timelapse file baseline for snapshot-diff on completion
  3446. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  3447. # hit this branch — without the baseline the completion-time scan
  3448. # falls into its "take baseline now" fallback, which snapshots
  3449. # AFTER the new MP4 already exists and never matches a diff
  3450. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  3451. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3452. return # Skip creating a new archive
  3453. # Check if there's already a "printing" archive for this printer/file
  3454. # This prevents duplicates when backend restarts during an active print
  3455. from backend.app.models.archive import PrintArchive
  3456. existing_archive: PrintArchive | None = None
  3457. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  3458. # across a backend restart for the same print, so this is the most
  3459. # reliable way to reattach. We also accept a previously stale-cancelled
  3460. # archive here so users upgrading mid-print get revived when the row
  3461. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  3462. if subtask_id:
  3463. by_id = await db.execute(
  3464. select(PrintArchive)
  3465. .where(PrintArchive.printer_id == printer_id)
  3466. .where(PrintArchive.subtask_id == subtask_id)
  3467. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  3468. .order_by(PrintArchive.created_at.desc())
  3469. .limit(1)
  3470. )
  3471. candidate = by_id.scalar_one_or_none()
  3472. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3473. existing_archive = candidate
  3474. # Fallback match: name-based lookup. Kept as-is for prints whose
  3475. # subtask_id is missing ("0" / local / non-cloud prints).
  3476. if existing_archive is None:
  3477. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3478. existing = await db.execute(
  3479. select(PrintArchive)
  3480. .where(PrintArchive.printer_id == printer_id)
  3481. .where(PrintArchive.status == "printing")
  3482. .where(
  3483. or_(
  3484. PrintArchive.print_name == check_name,
  3485. PrintArchive.filename.in_(
  3486. [
  3487. f"{check_name}.3mf",
  3488. f"{check_name}.gcode.3mf",
  3489. ]
  3490. ),
  3491. )
  3492. )
  3493. .order_by(PrintArchive.created_at.desc())
  3494. .limit(1)
  3495. )
  3496. existing_archive = existing.scalar_one_or_none()
  3497. if existing_archive:
  3498. # subtask_id match → always resume, regardless of age. Same print,
  3499. # just a backend restart. Revive if it was previously stale-cancelled.
  3500. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  3501. if subtask_match:
  3502. if existing_archive.status == "cancelled":
  3503. logger.warning(
  3504. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  3505. existing_archive.id,
  3506. subtask_id,
  3507. )
  3508. existing_archive.status = "printing"
  3509. existing_archive.failure_reason = None
  3510. await db.commit()
  3511. else:
  3512. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  3513. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3514. if existing_archive.energy_start_kwh is None:
  3515. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  3516. if not notification_sent:
  3517. archive_data = {
  3518. "print_time_seconds": existing_archive.print_time_seconds,
  3519. "created_by_id": existing_archive.created_by_id,
  3520. }
  3521. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3522. _load_objects_from_archive(existing_archive, printer_id, logger)
  3523. return
  3524. # Name-match only (no subtask_id to anchor on): decide resume vs.
  3525. # stale from the printer's *current* progress, not wall-clock age.
  3526. # A genuinely long print used to trip a blind 4h cutoff and have its
  3527. # live archive cancelled + duplicated on every backend restart
  3528. # (#1485). If the printer reports real progress, this name-matched
  3529. # 'printing' archive IS that ongoing print — resume it whatever its
  3530. # age. Only treat it as a stale leftover when the printer clearly
  3531. # shows a different, freshly-started print: near-0% progress on an
  3532. # archive far too old to still be at 0%. Unknown progress (printer
  3533. # not connected) never cancels — resuming is the safe default.
  3534. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  3535. live_status = printer_manager.get_status(printer_id)
  3536. live_progress = getattr(live_status, "progress", None) if live_status else None
  3537. looks_stale = (
  3538. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  3539. )
  3540. if looks_stale:
  3541. logger.warning(
  3542. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  3543. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  3544. )
  3545. existing_archive.status = "cancelled"
  3546. # Canonical key, not a sentence (issue #2974). "No status update
  3547. # received" is what both stale paths actually observed; which of
  3548. # the two it was is already carried by ``status`` -- cancelled
  3549. # here, the reconciled outcome at the reconnect site -- so one
  3550. # key loses no information and gives the Statistics breakdown a
  3551. # single bucket instead of two untranslatable prose strings.
  3552. existing_archive.failure_reason = "noStatusUpdate"
  3553. await db.commit()
  3554. # Fall through to create new archive (don't return)
  3555. else:
  3556. logger.info(
  3557. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  3558. )
  3559. # Track this as the active print
  3560. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3561. # Attach subtask_id retroactively so future restarts can resume.
  3562. # Compare for inequality (not "is empty") to also pick up reprint
  3563. # dispatches that mint a fresh id — see #1807 for the bogus
  3564. # "Print Stopped" the strict-empty guard caused on reconnect.
  3565. if subtask_id and existing_archive.subtask_id != subtask_id:
  3566. existing_archive.subtask_id = subtask_id
  3567. await db.commit()
  3568. # Also set up energy tracking if not already tracked (#941: persisted column)
  3569. if existing_archive.energy_start_kwh is None:
  3570. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  3571. # Send notification with archive data (existing archive)
  3572. if not notification_sent:
  3573. archive_data = {
  3574. "print_time_seconds": existing_archive.print_time_seconds,
  3575. "created_by_id": existing_archive.created_by_id,
  3576. }
  3577. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3578. # Extract printable objects from the archived 3MF file
  3579. _load_objects_from_archive(existing_archive, printer_id, logger)
  3580. return
  3581. # Build list of possible 3MF filenames to try
  3582. possible_names = []
  3583. # Bambu printers typically store files as "Name.gcode.3mf"
  3584. # The subtask_name is usually the best source for the filename
  3585. if subtask_name:
  3586. # Try common Bambu naming patterns
  3587. possible_names.append(f"{subtask_name}.gcode.3mf")
  3588. possible_names.append(f"{subtask_name}.3mf")
  3589. # Try original filename with .3mf extension
  3590. if filename:
  3591. # Extract just the filename part, not the full path
  3592. fname = filename.split("/")[-1] if "/" in filename else filename
  3593. if fname.endswith(".3mf"):
  3594. possible_names.append(fname)
  3595. elif fname.endswith(".gcode"):
  3596. base = fname.rsplit(".", 1)[0]
  3597. possible_names.append(f"{base}.gcode.3mf")
  3598. possible_names.append(f"{base}.3mf")
  3599. else:
  3600. possible_names.append(f"{fname}.gcode.3mf")
  3601. possible_names.append(f"{fname}.3mf")
  3602. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3603. space_variants = []
  3604. for name in possible_names:
  3605. if " " in name:
  3606. space_variants.append(name.replace(" ", "_"))
  3607. possible_names.extend(space_variants)
  3608. # Remove duplicates while preserving order
  3609. seen = set()
  3610. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  3611. logger.info("Trying filenames: %s", possible_names)
  3612. # Release the pooled DB connection before the 3MF FTP download. Reaching
  3613. # here means none of the expected-/existing-archive write branches ran
  3614. # (they all return earlier) — only SELECTs have executed on this path, so
  3615. # this commit persists nothing; it ends the read transaction so the
  3616. # connection returns to the pool during the download. That download tries
  3617. # up to five remote paths per candidate filename with retry/backoff and
  3618. # can run for minutes under FTP contention; holding the session across it
  3619. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  3620. # work runs during the download — the new-archive writes below re-acquire
  3621. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  3622. await db.commit()
  3623. # Try to find and download the 3MF file
  3624. temp_path = None
  3625. downloaded_filename = None
  3626. # Cache check: cover endpoint may have already pulled this 3MF during
  3627. # the print (frontend opens the card and shows the thumbnail) — reuse
  3628. # that file instead of re-downloading 36MB over the same FTP link that
  3629. # just served it (#972). The cache keys on a normalized filename so
  3630. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  3631. for try_filename in possible_names:
  3632. if not try_filename.endswith(".3mf"):
  3633. continue
  3634. cached = get_cached_3mf(printer_id, try_filename)
  3635. if cached:
  3636. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  3637. temp_path = cached
  3638. downloaded_filename = try_filename
  3639. break
  3640. # Does this printer keep the sliced file somewhere FTPS can reach? On
  3641. # H2-series and P2S the answer is routinely no — the file stays on
  3642. # internal eMMC and port 990 only ever serves external storage — and
  3643. # then the whole sweep below (six filenames x five directories x four
  3644. # retries, then the directory walk) is ~110 connections that cannot
  3645. # succeed. Skip it and say why (#2780).
  3646. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  3647. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  3648. # running rather than because the file is somewhere unreachable. The
  3649. # distinction is the whole of #2957: one is permanent, the other clears
  3650. # in minutes with the file still sitting on the printer.
  3651. blocked_by_ftps_cooloff = False
  3652. # Set when a probe reached the printer and still came back without the
  3653. # file -- a timeout mid-transfer, a refused connection, anything that is
  3654. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  3655. # caught by name below, so a file that genuinely is not on the card
  3656. # leaves this False and schedules nothing. Anything else means the
  3657. # transfer, not the file, is what failed, and that does not last (#3063).
  3658. ftp_transfer_failed = False
  3659. # Get FTP retry settings
  3660. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3661. # ...but "the printer put it on eMMC" is where it went, not whether we
  3662. # can read it. An H2D with a card in mirrors the job to /cache and
  3663. # serves it happily, and skipping on the URL alone cost that reporter
  3664. # every archive for two days (#2856). So ask the printer instead of
  3665. # guessing: the dispatch named the exact file, which is one connection
  3666. # walking five paths rather than the sweep's ~110. Only when the probe
  3667. # comes back empty does the verdict's reason stand.
  3668. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  3669. if ftps_handshake_blocked(printer.ip_address):
  3670. # Deliberately NOT recorded as a cool-off give-up. This branch
  3671. # only runs on an unreachable verdict, and that verdict is the
  3672. # honest, permanent reason the archive is empty — the probe was
  3673. # a long shot on top of it. Blaming the cool-off here would
  3674. # schedule a retry for a file sitting on internal eMMC, which is
  3675. # the sweep #2780 removed (#2957).
  3676. logger.debug(
  3677. "Not probing for %s on printer %s: its file service is not answering over TLS",
  3678. storage.probe_filename,
  3679. printer_id,
  3680. )
  3681. else:
  3682. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  3683. probe_path.parent.mkdir(parents=True, exist_ok=True)
  3684. try:
  3685. probe_hit = await download_file_try_paths_async(
  3686. printer.ip_address,
  3687. printer.access_code,
  3688. ftp_probe_paths(storage.probe_filename),
  3689. probe_path,
  3690. socket_timeout=ftp_timeout,
  3691. printer_model=printer.model,
  3692. )
  3693. except Exception as e:
  3694. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  3695. probe_hit = False
  3696. if probe_hit:
  3697. downloaded_filename = storage.probe_filename
  3698. temp_path = probe_path
  3699. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  3700. # Naming the path, not just the file: a printer that keeps
  3701. # uploads around for weeks can serve a same-named copy of an
  3702. # earlier slice, and without the directory in the log that
  3703. # mismatch is invisible rather than merely rare (#1820).
  3704. logger.info(
  3705. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  3706. downloaded_filename,
  3707. probe_hit,
  3708. printer_id,
  3709. storage.reason,
  3710. )
  3711. if not storage.reachable and not downloaded_filename:
  3712. # Same opening words whether or not a probe ran, because that is
  3713. # the phrase support asks people to grep for — only the tail says
  3714. # which of the two happened.
  3715. logger.info(
  3716. "Skipping the 3MF lookup for printer %s: %s — %s",
  3717. printer_id,
  3718. storage.reason,
  3719. "no copy of it on external storage either"
  3720. if storage.probe_filename
  3721. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  3722. )
  3723. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  3724. if not try_filename.endswith(".3mf"):
  3725. continue
  3726. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  3727. # printers, so try it first — deferring it to last cost #972's reporter
  3728. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  3729. # landing on the path that actually had the file.
  3730. remote_paths = [
  3731. f"/{try_filename}",
  3732. f"/cache/{try_filename}",
  3733. f"/model/{try_filename}",
  3734. f"/data/{try_filename}",
  3735. f"/data/Metadata/{try_filename}",
  3736. ]
  3737. temp_path = app_settings.archive_dir / "temp" / try_filename
  3738. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3739. for remote_path in remote_paths:
  3740. if ftps_handshake_blocked(printer.ip_address):
  3741. # The printer's FTPS service is not completing a TLS
  3742. # handshake, so it has no path we could reach — walking the
  3743. # remaining candidates only re-runs the same failure
  3744. # (#2780). Fall through to the no-3MF archive now.
  3745. #
  3746. # Remember *why*, though. This is the one give-up that is
  3747. # temporary: the cool-off clears in minutes and the file was
  3748. # on the printer the whole time. The fallback archive is
  3749. # stamped with it so a retry can be scheduled, and so the
  3750. # Archives banner stops blaming storage (#2957).
  3751. blocked_by_ftps_cooloff = True
  3752. logger.warning(
  3753. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  3754. printer_id,
  3755. )
  3756. break
  3757. logger.debug("Trying FTP download: %s", remote_path)
  3758. try:
  3759. if ftp_retry_enabled:
  3760. downloaded = await with_ftp_retry(
  3761. download_file_async,
  3762. printer.ip_address,
  3763. printer.access_code,
  3764. remote_path,
  3765. temp_path,
  3766. timeout=ftp_timeout,
  3767. socket_timeout=ftp_timeout,
  3768. printer_model=printer.model,
  3769. max_retries=ftp_retry_count,
  3770. retry_delay=ftp_retry_delay,
  3771. operation_name=f"Download 3MF from {remote_path}",
  3772. cooloff_ip=printer.ip_address,
  3773. non_retry_exceptions=(FileNotOnPrinterError,),
  3774. )
  3775. else:
  3776. downloaded = await download_file_async(
  3777. printer.ip_address,
  3778. printer.access_code,
  3779. remote_path,
  3780. temp_path,
  3781. timeout=ftp_timeout,
  3782. socket_timeout=ftp_timeout,
  3783. printer_model=printer.model,
  3784. )
  3785. if downloaded:
  3786. downloaded_filename = try_filename
  3787. logger.info("Downloaded: %s", remote_path)
  3788. # Populate shared cache so the cover endpoint (if it
  3789. # runs next) doesn't refetch the same 36MB over FTP.
  3790. cache_3mf_download(printer_id, try_filename, temp_path)
  3791. break
  3792. # with_ftp_retry returns None once it has spent its budget,
  3793. # and download_file_async returns False on a timeout, so an
  3794. # exhausted transfer arrives here rather than as an
  3795. # exception (#3063).
  3796. ftp_transfer_failed = True
  3797. except FileNotOnPrinterError:
  3798. # 550 — file isn't at this path. Advance to next candidate
  3799. # without burning the retry budget.
  3800. logger.debug("3MF not at %s (550), trying next path", remote_path)
  3801. except Exception as e:
  3802. ftp_transfer_failed = True
  3803. logger.debug("FTP download failed for %s: %s", remote_path, e)
  3804. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  3805. break
  3806. # If still not found, try listing directories to find matching file
  3807. # Different printer models use different directory structures. Skipped
  3808. # when the printer's FTPS handshake is failing — the directory walk is
  3809. # five more connections that cannot get further than the download did.
  3810. if (
  3811. not downloaded_filename
  3812. and storage.reachable
  3813. and (filename or subtask_name)
  3814. and not ftps_handshake_blocked(printer.ip_address)
  3815. ):
  3816. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  3817. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  3818. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  3819. for search_dir in search_dirs:
  3820. if downloaded_filename:
  3821. break
  3822. try:
  3823. dir_files = await list_files_async(
  3824. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  3825. )
  3826. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  3827. if threemf_files:
  3828. logger.info(
  3829. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  3830. )
  3831. for f in dir_files:
  3832. if f.get("is_directory"):
  3833. continue
  3834. fname = f.get("name", "")
  3835. # Normalize both for comparison (spaces and underscores are equivalent)
  3836. fname_normalized = fname.lower().replace(" ", "_")
  3837. search_normalized = search_term.replace(" ", "_")
  3838. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  3839. logger.info("Found matching file in %s: %s", search_dir, fname)
  3840. temp_path = app_settings.archive_dir / "temp" / fname
  3841. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3842. remote_full_path = posixpath.join(search_dir, fname)
  3843. if ftp_retry_enabled:
  3844. downloaded = await with_ftp_retry(
  3845. download_file_async,
  3846. printer.ip_address,
  3847. printer.access_code,
  3848. remote_full_path,
  3849. temp_path,
  3850. timeout=ftp_timeout,
  3851. socket_timeout=ftp_timeout,
  3852. printer_model=printer.model,
  3853. max_retries=ftp_retry_count,
  3854. retry_delay=ftp_retry_delay,
  3855. operation_name=f"Download 3MF from {remote_full_path}",
  3856. cooloff_ip=printer.ip_address,
  3857. )
  3858. else:
  3859. downloaded = await download_file_async(
  3860. printer.ip_address,
  3861. printer.access_code,
  3862. remote_full_path,
  3863. temp_path,
  3864. timeout=ftp_timeout,
  3865. socket_timeout=ftp_timeout,
  3866. printer_model=printer.model,
  3867. )
  3868. if downloaded:
  3869. downloaded_filename = fname
  3870. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  3871. cache_3mf_download(printer_id, fname, temp_path)
  3872. break
  3873. # The listing named the file, so it is on the card;
  3874. # only the transfer failed (#3063).
  3875. ftp_transfer_failed = True
  3876. except Exception as e:
  3877. logger.debug("Failed to list %s: %s", search_dir, e)
  3878. # Validate the downloaded 3MF actually matches the plate that's running
  3879. # (#1204): subtask_name lags across consecutive plates of the same model,
  3880. # so the first FTP candidate (built from subtask_name) can land on the
  3881. # previous plate's still-resident upload. Cross-check the slice_info
  3882. # plate index against the plate parsed from gcode_file (always fresh —
  3883. # it's the field whose change triggered this callback).
  3884. if downloaded_filename and temp_path:
  3885. expected_plate = parse_plate_id(filename)
  3886. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  3887. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  3888. logger.warning(
  3889. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  3890. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  3891. downloaded_filename,
  3892. actual_plate,
  3893. expected_plate,
  3894. subtask_name,
  3895. )
  3896. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  3897. retry_succeeded = False
  3898. if corrected_subtask and corrected_subtask != subtask_name:
  3899. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  3900. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  3901. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  3902. for remote_path in (
  3903. f"/{try_filename}",
  3904. f"/cache/{try_filename}",
  3905. f"/model/{try_filename}",
  3906. f"/data/{try_filename}",
  3907. f"/data/Metadata/{try_filename}",
  3908. ):
  3909. try:
  3910. if ftp_retry_enabled:
  3911. downloaded = await with_ftp_retry(
  3912. download_file_async,
  3913. printer.ip_address,
  3914. printer.access_code,
  3915. remote_path,
  3916. retry_temp_path,
  3917. timeout=ftp_timeout,
  3918. socket_timeout=ftp_timeout,
  3919. printer_model=printer.model,
  3920. max_retries=ftp_retry_count,
  3921. retry_delay=ftp_retry_delay,
  3922. operation_name=f"Re-download 3MF from {remote_path}",
  3923. cooloff_ip=printer.ip_address,
  3924. non_retry_exceptions=(FileNotOnPrinterError,),
  3925. )
  3926. else:
  3927. downloaded = await download_file_async(
  3928. printer.ip_address,
  3929. printer.access_code,
  3930. remote_path,
  3931. retry_temp_path,
  3932. timeout=ftp_timeout,
  3933. socket_timeout=ftp_timeout,
  3934. printer_model=printer.model,
  3935. )
  3936. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  3937. logger.info(
  3938. "[CALLBACK] Re-download succeeded with corrected name %s "
  3939. "(plate %s) — replacing wrong file",
  3940. try_filename,
  3941. expected_plate,
  3942. )
  3943. try:
  3944. temp_path.unlink(missing_ok=True)
  3945. except OSError:
  3946. pass
  3947. temp_path = retry_temp_path
  3948. downloaded_filename = try_filename
  3949. subtask_name = corrected_subtask
  3950. cache_3mf_download(printer_id, try_filename, temp_path)
  3951. retry_succeeded = True
  3952. break
  3953. elif downloaded:
  3954. # Wrong plate again — discard and keep trying
  3955. try:
  3956. retry_temp_path.unlink(missing_ok=True)
  3957. except OSError:
  3958. pass
  3959. except FileNotOnPrinterError:
  3960. continue
  3961. except Exception as e:
  3962. logger.debug("Re-download failed for %s: %s", remote_path, e)
  3963. if retry_succeeded:
  3964. break
  3965. # If the retry didn't find a matching file, drop the wrong 3MF
  3966. # so the no-3MF fallback below creates an archive whose name
  3967. # at least reflects the right plate.
  3968. if not retry_succeeded:
  3969. logger.warning(
  3970. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  3971. expected_plate,
  3972. )
  3973. try:
  3974. temp_path.unlink(missing_ok=True)
  3975. except OSError:
  3976. pass
  3977. temp_path = None
  3978. downloaded_filename = None
  3979. # Whatever the sweep's transport did earlier, it is not why
  3980. # this archive ends up empty: a 3MF downloaded fine, it was
  3981. # just the wrong plate. Retrying would re-fetch that same
  3982. # contradicted file under the same stale names and hand it
  3983. # to _recover_fallback_archive, which checks that a
  3984. # candidate is a readable 3MF but not which plate it is --
  3985. # so the row would be filled in with another plate's
  3986. # filament and cost, the exact swap #2957 removed (#3063).
  3987. ftp_transfer_failed = False
  3988. # Override the stale subtask_name so the fallback archive's
  3989. # print_name reflects the correct plate. Prefer the swapped
  3990. # name when we have one; otherwise let filename win.
  3991. if corrected_subtask:
  3992. subtask_name = corrected_subtask
  3993. else:
  3994. subtask_name = ""
  3995. if not downloaded_filename or not temp_path:
  3996. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  3997. # Create a fallback archive without 3MF data so the print is still tracked
  3998. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  3999. try:
  4000. from backend.app.models.archive import PrintArchive
  4001. # Why the card is empty. The two temporary causes outrank the
  4002. # storage verdict because they say the sweep never got a fair
  4003. # answer: a cool-off skipped it at the transport, and a failed
  4004. # transfer reached the printer but never finished. Either way
  4005. # the file is still on the card, so reporting where the printer
  4006. # files its jobs would describe a setting that is not the
  4007. # problem (#2957, #3063).
  4008. if blocked_by_ftps_cooloff:
  4009. no_3mf_reason = REASON_FTPS_COOLOFF
  4010. elif storage.reachable and ftp_transfer_failed:
  4011. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4012. else:
  4013. no_3mf_reason = storage.reason
  4014. # Derive print name from subtask_name or filename
  4015. print_name = subtask_name or filename
  4016. if print_name:
  4017. # Clean up the name (remove extensions, path parts)
  4018. print_name = print_name.split("/")[-1]
  4019. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4020. else:
  4021. print_name = "Unknown Print"
  4022. # Recover estimated print time from MQTT (best-effort for notifications)
  4023. fallback_print_time = None
  4024. mqtt_remaining = data.get("remaining_time")
  4025. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4026. fallback_print_time = int(mqtt_remaining)
  4027. if fallback_print_time is None:
  4028. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4029. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4030. fallback_print_time = int(mc_remaining * 60)
  4031. # Best-effort filament metadata from MQTT — see
  4032. # _extract_filament_data_from_mqtt. Without this the fallback
  4033. # archive's filament fields stayed NULL even though the AMS
  4034. # state at print start was sitting right there in `data`.
  4035. # The slicer's ams_mapping (when present) narrows the result
  4036. # to slots actually used by the print (#1533).
  4037. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4038. # Create minimal archive entry
  4039. fallback_archive = PrintArchive(
  4040. printer_id=printer_id,
  4041. filename=filename or f"{print_name}.3mf",
  4042. file_path="", # Empty - no 3MF file available
  4043. file_size=0,
  4044. print_name=print_name,
  4045. print_time_seconds=fallback_print_time,
  4046. status="printing",
  4047. started_at=datetime.now(timezone.utc),
  4048. subtask_id=subtask_id,
  4049. filament_type=mqtt_filament_meta.get("filament_type"),
  4050. filament_color=mqtt_filament_meta.get("filament_color"),
  4051. extra_data={
  4052. "no_3mf_available": True,
  4053. # Why the card is empty, when we know -- see above. The
  4054. # banner reads this to stop telling H2/P2 owners to
  4055. # switch on a setting that is already on and would not
  4056. # have helped (#2780).
  4057. "no_3mf_reason": no_3mf_reason,
  4058. "original_subtask": subtask_name,
  4059. "_print_data": data,
  4060. },
  4061. )
  4062. db.add(fallback_archive)
  4063. await db.commit()
  4064. await db.refresh(fallback_archive)
  4065. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4066. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4067. # Track as active print
  4068. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4069. if filename:
  4070. _active_prints[(printer_id, filename)] = fallback_archive.id
  4071. if subtask_name:
  4072. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4073. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4074. # Record starting energy if smart plug available (#941: persisted column)
  4075. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4076. # Send WebSocket notification
  4077. await ws_manager.send_archive_created(
  4078. {
  4079. "id": fallback_archive.id,
  4080. "printer_id": fallback_archive.printer_id,
  4081. "filename": fallback_archive.filename,
  4082. "print_name": fallback_archive.print_name,
  4083. "status": fallback_archive.status,
  4084. }
  4085. )
  4086. # MQTT relay - publish archive created
  4087. try:
  4088. await mqtt_relay.on_archive_created(
  4089. archive_id=fallback_archive.id,
  4090. print_name=fallback_archive.print_name,
  4091. printer_name=printer.name,
  4092. status=fallback_archive.status,
  4093. )
  4094. except Exception:
  4095. pass # Don't fail if MQTT fails
  4096. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4097. try:
  4098. await _store_spoolman_print_data(
  4099. printer_id,
  4100. fallback_archive.id,
  4101. fallback_archive.file_path,
  4102. db,
  4103. printer_manager,
  4104. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4105. plate_id=_get_start_plate_id(fallback_archive.id),
  4106. )
  4107. except Exception as e:
  4108. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4109. # Both temporary give-ups are worth coming back for, and for
  4110. # the same reason: the file is on the printer and the last look
  4111. # failed at the transport rather than finding nothing. One waits
  4112. # out the handshake block (#2957), the other waits for the
  4113. # printer to stop being busy (#3063). Deliberately not scheduled
  4114. # for a storage verdict: a file on internal eMMC will not appear
  4115. # at any FTPS path however long we wait, and retrying it is
  4116. # exactly the sweep #2780 removed.
  4117. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4118. # `possible_names`, not the raw MQTT strings: it is the exact
  4119. # list this flow just tried, already stripped of any path
  4120. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4121. # some firmware) and deduped.
  4122. _schedule_fallback_3mf_retry(
  4123. printer_id=printer_id,
  4124. archive_id=fallback_archive.id,
  4125. filenames=list(possible_names),
  4126. reason=no_3mf_reason,
  4127. )
  4128. # Send notification without archive data (file not found)
  4129. if not notification_sent:
  4130. await _send_print_start_notification(printer_id, data, logger=logger)
  4131. # The same baseline the other two on_print_start branches take
  4132. # (#2704), and last for the same reason they are: it lists the
  4133. # printer's timelapse directory, so a slow card must not delay
  4134. # the _active_prints registration, the energy reading, the
  4135. # archive-created event or the start notification above it.
  4136. #
  4137. # This branch never took one, so every no-3MF archive reached
  4138. # completion with no baseline in memory and none on the row, and
  4139. # the completion scan fell into its "snapshot now" fallback --
  4140. # which runs after the printer has written the video, so the new
  4141. # file landed inside the baseline and no diff ever matched
  4142. # (#2957 follow-up).
  4143. #
  4144. # Skipped when the FTPS cool-off is what produced this fallback:
  4145. # the listing needs the same connection that just failed, so it
  4146. # could only record that the card was unreadable. The scan
  4147. # handles that case by refusing to choose between candidates.
  4148. if not blocked_by_ftps_cooloff:
  4149. await _capture_timelapse_baseline_at_start(
  4150. printer, printer_id, logger, archive_id=fallback_archive.id
  4151. )
  4152. return
  4153. except Exception as e:
  4154. logger.error("Failed to create fallback archive: %s", e)
  4155. # Send notification without archive data (file not found)
  4156. if not notification_sent:
  4157. await _send_print_start_notification(printer_id, data, logger=logger)
  4158. return
  4159. try:
  4160. # Archive the file with status "printing"
  4161. service = ArchiveService(db)
  4162. archive = await service.archive_print(
  4163. printer_id=printer_id,
  4164. source_file=temp_path,
  4165. print_data={**data, "status": "printing"},
  4166. subtask_id=subtask_id,
  4167. )
  4168. if archive:
  4169. # Track this active print (use both original filename and downloaded filename)
  4170. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4171. if filename and filename != downloaded_filename:
  4172. _active_prints[(printer_id, filename)] = archive.id
  4173. if subtask_name:
  4174. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4175. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4176. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4177. # Record starting energy from smart plug if available (#941: persisted column)
  4178. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4179. await ws_manager.send_archive_created(
  4180. {
  4181. "id": archive.id,
  4182. "printer_id": archive.printer_id,
  4183. "filename": archive.filename,
  4184. "print_name": archive.print_name,
  4185. "status": archive.status,
  4186. }
  4187. )
  4188. # MQTT relay - publish archive created
  4189. try:
  4190. await mqtt_relay.on_archive_created(
  4191. archive_id=archive.id,
  4192. print_name=archive.print_name,
  4193. printer_name=printer.name,
  4194. status=archive.status,
  4195. )
  4196. except Exception:
  4197. pass # Don't fail if MQTT fails
  4198. # Send notification with archive data (new archive created)
  4199. if not notification_sent:
  4200. archive_data = {
  4201. "print_time_seconds": archive.print_time_seconds,
  4202. "created_by_id": archive.created_by_id,
  4203. }
  4204. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4205. # Extract printable objects for skip object functionality
  4206. try:
  4207. from backend.app.services.archive import extract_printable_objects_from_3mf
  4208. client = printer_manager.get_client(printer_id)
  4209. if client:
  4210. with open(temp_path, "rb") as f:
  4211. threemf_data = f.read()
  4212. # Extract with positions for UI overlay, scoped to the
  4213. # plate that is printing — an all-plates 3MF carries
  4214. # every plate's objects (#2522).
  4215. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4216. threemf_data,
  4217. plate_number=resolve_plate_id(client.state),
  4218. include_positions=True,
  4219. )
  4220. if printable_objects:
  4221. # Store objects in printer state
  4222. client.state.printable_objects = printable_objects
  4223. client.state.printable_objects_bbox_all = bbox_all
  4224. client.state.skipped_objects = [] # Reset skipped objects for new print
  4225. logger.info(
  4226. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4227. )
  4228. except Exception as e:
  4229. logger.debug("Failed to extract printable objects: %s", e)
  4230. # Store Spoolman tracking data for per-filament usage reporting
  4231. try:
  4232. await _store_spoolman_print_data(
  4233. printer_id,
  4234. archive.id,
  4235. archive.file_path,
  4236. db,
  4237. printer_manager,
  4238. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4239. plate_id=_get_start_plate_id(archive.id),
  4240. )
  4241. except Exception as e:
  4242. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4243. # Capture timelapse file baseline for snapshot-diff on completion
  4244. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4245. finally:
  4246. # Keep temp_path around until print completes so the cover endpoint
  4247. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4248. # the file. If the cache entry was evicted early (file vanished),
  4249. # clean up any stragglers here to avoid leaking disk on retries.
  4250. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4251. if temp_path and temp_path.exists() and cached_now != temp_path:
  4252. temp_path.unlink()
  4253. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4254. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4255. # tests can shrink them without waiting out real delays.
  4256. #
  4257. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4258. # looking. Across 247 support bundles the attempt that found the video was #1
  4259. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4260. # decaying one, which is the signature of a budget that expires while files are
  4261. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4262. # prints make big videos and the printer writes them after the print ends, so
  4263. # the poll now runs for minutes and costs one FTP LIST per round.
  4264. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4265. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4266. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4267. def _timelapse_scan_max_attempts() -> int:
  4268. """Round cap for the poll, derived from the wall-clock budget.
  4269. The deadline alone is not a sufficient bound: it assumes each round really
  4270. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4271. and an FTP list that fails immediately would otherwise spin against the
  4272. printer at full speed for the whole window. Whichever bound is reached
  4273. first ends the poll.
  4274. """
  4275. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4276. # A zero interval makes the wall-clock budget meaningless; fall back to
  4277. # the round count the production interval would have given.
  4278. return 32
  4279. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4280. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4281. """Video filenames already attached to some other archive of this printer.
  4282. Used to disambiguate when more than one file is new since the baseline —
  4283. which happens when a previous print's video landed after this print's
  4284. baseline was taken. Ordering the candidates would be the obvious fix and is
  4285. the wrong one: it can only be done on mtime or on the filename timestamp,
  4286. both of which come from the printer's own clock, and a LAN-only printer
  4287. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4288. ``attach_timelapse`` saves the video into the archive directory under the
  4289. printer's original filename, and the later MP4 conversion keeps the stem,
  4290. so the stem of ``timelapse_path`` recovers what was claimed.
  4291. """
  4292. from backend.app.models.archive import PrintArchive
  4293. rows = await db.execute(
  4294. select(PrintArchive.timelapse_path).where(
  4295. PrintArchive.printer_id == printer_id,
  4296. PrintArchive.id != exclude_archive_id,
  4297. PrintArchive.timelapse_path.is_not(None),
  4298. )
  4299. )
  4300. return {Path(p).stem for p in rows.scalars().all() if p}
  4301. def _timelapse_listing_is_trustworthy(printer) -> bool:
  4302. """Whether an *empty* timelapse listing for *printer* can be believed.
  4303. ``list_files_async`` answers ``[]`` when its connect fails rather than
  4304. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  4305. from one holding no videos. Everywhere that only wants to know "is there a
  4306. video yet" the difference does not matter — both mean "not yet, retry".
  4307. It matters where an empty listing is recorded as a *baseline*. Recording
  4308. "the card held nothing" for a card that was never read means every video on
  4309. it counts as new once the cool-off expires, and the completion scan then
  4310. attaches a stale video to this print and deletes it from the printer
  4311. (#2957 follow-up). Those two callers ask this first.
  4312. """
  4313. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  4314. ip_address = getattr(printer, "ip_address", None)
  4315. if not ip_address:
  4316. return True
  4317. return not ftps_handshake_blocked(ip_address)
  4318. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  4319. """List video files from printer's timelapse directory.
  4320. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  4321. Returns (video_files, found_path) where video_files is a list of file dicts
  4322. and found_path is the directory where they were found, or ([], None).
  4323. An empty return does not distinguish "no videos" from "could not read the
  4324. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  4325. baseline callers consult before believing one.
  4326. """
  4327. from backend.app.services.bambu_ftp import list_files_async
  4328. logger = logging.getLogger(__name__)
  4329. # No card in the slot means no /timelapse to walk — four connections that
  4330. # can only fail, on a path whose failures are swallowed and so would go on
  4331. # costing time silently forever (#2780).
  4332. #
  4333. # ``getattr`` rather than ``printer.id``: every dereference below happens
  4334. # inside the loop's own try/except, so a caller that passed something
  4335. # unexpected used to get an empty listing rather than an exception. Keep
  4336. # that, instead of making this gate the first thing that can raise here.
  4337. printer_id = getattr(printer, "id", None)
  4338. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  4339. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  4340. return [], None
  4341. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  4342. try:
  4343. found_files = await list_files_async(
  4344. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  4345. )
  4346. if found_files:
  4347. video_files = [
  4348. f
  4349. for f in found_files
  4350. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  4351. ]
  4352. if video_files:
  4353. return video_files, timelapse_path
  4354. except Exception as e:
  4355. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  4356. continue
  4357. return [], None
  4358. async def _capture_timelapse_baseline_at_start(
  4359. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  4360. ) -> None:
  4361. """Snapshot the printer's timelapse directory at print start so the
  4362. completion-time scan can pick the new file by set-difference.
  4363. Must be called from every on_print_start path that proceeds to a real
  4364. print — both the new-archive branch and the expected-archive branch (which
  4365. queue / VP-dispatched prints take). Without a baseline,
  4366. _scan_for_timelapse_with_retries falls into its "take baseline now"
  4367. fallback that runs AFTER the new MP4 has already landed on the SD card,
  4368. so the new file ends up in the "baseline" set and no diff ever matches.
  4369. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  4370. unreliable — the snapshot-diff approach sidesteps that entirely.
  4371. When ``archive_id`` is known the baseline is also written to the archive
  4372. row, so it survives a restart and the manual "Scan for Timelapse" button
  4373. can run the same diff instead of falling back to clock-based matching
  4374. (#2704). Only baselines taken at print start are persisted — one taken at
  4375. completion already contains the new video and would poison a later scan.
  4376. """
  4377. names: set[str] | None = None
  4378. try:
  4379. if not _timelapse_listing_is_trustworthy(printer):
  4380. # Recorded anyway, deliberately. An empty baseline taken off a card
  4381. # we could not read is not authoritative, but it is still the right
  4382. # *default*: Bambuddy deletes each video from the printer once it is
  4383. # attached, so the usual card holds exactly one video at completion
  4384. # and an empty baseline resolves it correctly. Persisting NULL
  4385. # instead would send completion to take its own snapshot, by which
  4386. # point this print's video is on the card and would be swallowed by
  4387. # it. The ambiguity is handled where it actually bites — see
  4388. # ``require_unambiguous`` in the scan (#2957 follow-up).
  4389. logger.warning(
  4390. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  4391. "handshake cool-off, so the card could not be read — treating it as empty",
  4392. printer_id,
  4393. )
  4394. baseline_files, _ = await _list_timelapse_videos(printer)
  4395. names = {f.get("name", "") for f in baseline_files}
  4396. _timelapse_baselines[printer_id] = names
  4397. logger.info(
  4398. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  4399. len(names),
  4400. printer_id,
  4401. )
  4402. except Exception as e:
  4403. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  4404. if archive_id is None:
  4405. return
  4406. try:
  4407. async with async_session() as db:
  4408. from backend.app.models.archive import PrintArchive
  4409. archive = await db.get(PrintArchive, archive_id)
  4410. if archive is not None:
  4411. # Written even when the listing failed, and then as NULL. A
  4412. # reprint reuses the archive row, so leaving the previous run's
  4413. # baseline in place would have the scan diff this print against
  4414. # the state of the printer before the *last* one — and a stale
  4415. # baseline reads as authoritative, where NULL correctly falls
  4416. # back to a fresh snapshot.
  4417. archive.timelapse_baseline = sorted(names) if names is not None else None
  4418. await db.commit()
  4419. except Exception as e:
  4420. # In-memory baseline still covers the normal completion path.
  4421. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  4422. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  4423. """Poll the printer for this print's timelapse and attach it.
  4424. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  4425. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  4426. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  4427. (#2704). Comparing the current listing against the set of filenames that
  4428. existed when the print started needs no clock at all, because the printer
  4429. writes the video only once the print has ended.
  4430. Baseline precedence: the caller's in-memory set, then the one persisted on
  4431. the archive at print start, then a snapshot taken now. The last of those is
  4432. a poor substitute — by completion the new video may already be on the card,
  4433. in which case it lands in the "baseline" and no diff can ever match — but it
  4434. is all that is available for a print that began before Bambuddy started.
  4435. On success the video is deleted from the printer, which keeps ``/timelapse``
  4436. down to the unclaimed files and makes the next diff unambiguous.
  4437. """
  4438. logger = logging.getLogger(__name__)
  4439. # Cleared when the baseline had to be taken off a card we could not read, so
  4440. # the attach step refuses to choose between several candidates (#2957).
  4441. baseline_trusted = True
  4442. # --- Phase 1: establish the baseline -------------------------------------
  4443. try:
  4444. async with async_session() as db:
  4445. from backend.app.models.printer import Printer
  4446. service = ArchiveService(db)
  4447. archive = await service.get_archive(archive_id)
  4448. if not archive:
  4449. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  4450. return
  4451. if archive.timelapse_path:
  4452. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  4453. return
  4454. if not archive.printer_id:
  4455. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  4456. return
  4457. if baseline_names is not None:
  4458. logger.info(
  4459. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  4460. len(baseline_names),
  4461. archive_id,
  4462. )
  4463. elif archive.timelapse_baseline is not None:
  4464. # Persisted at print start — survives a restart mid-print.
  4465. baseline_names = set(archive.timelapse_baseline)
  4466. logger.info(
  4467. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  4468. len(baseline_names),
  4469. archive_id,
  4470. )
  4471. else:
  4472. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4473. printer = result.scalar_one_or_none()
  4474. if not printer:
  4475. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  4476. return
  4477. if not _timelapse_listing_is_trustworthy(printer):
  4478. # The card is unreadable at the one moment a baseline has to
  4479. # be taken, so the empty listing below means "we never
  4480. # looked", not "these are all new". Carry on with it anyway
  4481. # — the usual card holds exactly one video, which resolves
  4482. # correctly — but stop the poll from *choosing* between
  4483. # several, which is how a stale video got attached to this
  4484. # print and then deleted off the printer (#2957 follow-up).
  4485. baseline_trusted = False
  4486. logger.warning(
  4487. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  4488. "handshake cool-off. A single new video still resolves; several will not be "
  4489. "guessed between — use Scan for Timelapse to pick one by hand",
  4490. archive_id,
  4491. archive.printer_id,
  4492. )
  4493. baseline_files, _ = await _list_timelapse_videos(printer)
  4494. baseline_names = {f.get("name", "") for f in baseline_files}
  4495. logger.info(
  4496. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  4497. len(baseline_names),
  4498. archive_id,
  4499. )
  4500. except Exception as e:
  4501. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  4502. return
  4503. # --- Phase 2: poll for a file that was not there when the print began -----
  4504. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  4505. max_attempts = _timelapse_scan_max_attempts()
  4506. seen_names: set[str] = set()
  4507. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  4508. attempt = 0
  4509. while True:
  4510. await asyncio.sleep(delay)
  4511. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  4512. attempt += 1
  4513. try:
  4514. from backend.app.models.printer import Printer
  4515. # Read phase: fetch archive + printer in a short session and release
  4516. # the pooled connection BEFORE the FTP list/download below. Holding it
  4517. # across the FTP round-trips left one connection idle-in-transaction per
  4518. # in-flight scan (issue #2572).
  4519. async with async_session() as db:
  4520. service = ArchiveService(db)
  4521. archive = await service.get_archive(archive_id)
  4522. if not archive:
  4523. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  4524. return
  4525. if archive.timelapse_path:
  4526. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  4527. return
  4528. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4529. printer = result.scalar_one_or_none()
  4530. if not printer:
  4531. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  4532. return
  4533. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  4534. # I/O phase (no DB connection held): FTP list + download.
  4535. video_files, found_path = await _list_timelapse_videos(printer)
  4536. # The poll can run for dozens of rounds, so only narrate a round
  4537. # that saw something change. Repeating the whole listing every 30 s
  4538. # would bury the one interesting line in the support bundle.
  4539. names_now = {f.get("name", "") for f in video_files}
  4540. changed = attempt == 1 or names_now != seen_names
  4541. seen_names = names_now
  4542. speak = logger.info if changed else logger.debug
  4543. if video_files:
  4544. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  4545. if changed:
  4546. for f in video_files[:5]:
  4547. logger.info("[TIMELAPSE] - %s", f.get("name"))
  4548. attached = await _attach_first_unclaimed_timelapse(
  4549. archive_id,
  4550. printer,
  4551. video_files,
  4552. baseline_names,
  4553. claimed,
  4554. attempt,
  4555. logger,
  4556. quiet=not changed,
  4557. require_unambiguous=not baseline_trusted,
  4558. )
  4559. if attached:
  4560. return
  4561. else:
  4562. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  4563. except Exception as e:
  4564. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  4565. if attempt >= max_attempts or time.monotonic() >= deadline:
  4566. break
  4567. # No name-match fallback: it compared the print name against the filename,
  4568. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  4569. # bundles it fired 159 times and matched zero times, so all it added was a
  4570. # misleading log line before giving up.
  4571. logger.warning(
  4572. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  4573. archive_id,
  4574. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  4575. )
  4576. async def _attach_first_unclaimed_timelapse(
  4577. archive_id: int,
  4578. printer,
  4579. video_files: list[dict],
  4580. baseline_names: set[str],
  4581. claimed: set[str],
  4582. attempt: int,
  4583. logger: logging.Logger,
  4584. *,
  4585. quiet: bool = False,
  4586. require_unambiguous: bool = False,
  4587. ) -> bool:
  4588. """Download and attach the one video that belongs to this print.
  4589. A candidate is any file absent from the print-start baseline. More than one
  4590. can qualify when a previous print's video landed late, after this print's
  4591. baseline was taken — those are filtered out by name, because they are
  4592. already attached to another archive. Sorting the candidates instead would
  4593. mean sorting on mtime or on the filename timestamp, both of which come from
  4594. the printer's unsynced clock.
  4595. Returns True once a video is attached. The printer's copy is deleted only
  4596. after the attach succeeds on bytes whose length matched the listing.
  4597. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  4598. already seen this exact listing — the poll runs for many rounds and only the
  4599. rounds where something changed are worth an INFO line.
  4600. """
  4601. from backend.app.services.bambu_ftp import (
  4602. delete_archived_timelapse,
  4603. download_file_bytes_async,
  4604. remote_file_settled,
  4605. )
  4606. speak = logger.debug if quiet else logger.info
  4607. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  4608. if not new_files:
  4609. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  4610. return False
  4611. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  4612. if not candidates:
  4613. speak(
  4614. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  4615. attempt,
  4616. len(new_files),
  4617. )
  4618. return False
  4619. if len(candidates) > 1:
  4620. if require_unambiguous:
  4621. # The baseline is not evidence -- it was taken off a card that could
  4622. # not be read -- so "new since the baseline" does not narrow these
  4623. # down at all. Taking the first would attach an arbitrary video to
  4624. # this print and then delete it from the printer.
  4625. logger.warning(
  4626. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  4627. "leaving all of them on the printer for manual selection",
  4628. attempt,
  4629. len(candidates),
  4630. ", ".join(str(f.get("name")) for f in candidates),
  4631. )
  4632. return False
  4633. logger.warning(
  4634. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  4635. "the rest stay on the printer for manual selection",
  4636. attempt,
  4637. len(candidates),
  4638. ", ".join(str(f.get("name")) for f in candidates),
  4639. )
  4640. target = candidates[0]
  4641. file_name = target.get("name")
  4642. remote_path = target.get("path") or f"/timelapse/{file_name}"
  4643. logger.info(
  4644. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  4645. attempt,
  4646. file_name,
  4647. archive_id,
  4648. )
  4649. # The listing always carries a size (`list_files` skips entries it can't
  4650. # parse), but read it explicitly: the delete below is destructive and must
  4651. # depend on a size we actually had, not on one we hoped was there.
  4652. expected_size = target.get("size")
  4653. timelapse_data = await download_file_bytes_async(
  4654. printer.ip_address,
  4655. printer.access_code,
  4656. remote_path,
  4657. printer_model=printer.model,
  4658. expected_size=expected_size,
  4659. )
  4660. if not timelapse_data:
  4661. # Short or failed transfer. The printer keeps its copy, so the next
  4662. # round can try again — which is exactly why the delete below is
  4663. # gated on a verified download.
  4664. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  4665. return False
  4666. # The length check above proves we got what the listing said, not that the
  4667. # printer had finished writing. A video still being written can be listed
  4668. # short, served short, and pass — so confirm it has stopped growing before
  4669. # committing to it and deleting the original (#2704).
  4670. if not await remote_file_settled(
  4671. printer.ip_address,
  4672. printer.access_code,
  4673. remote_path,
  4674. len(timelapse_data),
  4675. printer_model=printer.model,
  4676. ):
  4677. return False
  4678. # Write phase: attach in a fresh short-lived session.
  4679. async with async_session() as db:
  4680. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  4681. if not success:
  4682. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  4683. return False
  4684. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  4685. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  4686. await delete_archived_timelapse(
  4687. printer.ip_address,
  4688. printer.access_code,
  4689. remote_path,
  4690. verified=expected_size is not None,
  4691. printer_model=printer.model,
  4692. printer_name=printer.name,
  4693. )
  4694. return True
  4695. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  4696. # module-level so tests can monkeypatch them down to ~0 without timing out.
  4697. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  4698. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  4699. # How long the *background* upgrade keeps waiting after the notification has
  4700. # already gone out (#2704 follow-up). The short bound above exists so a slow
  4701. # printer can't hold up the print-complete notification; this one exists so the
  4702. # archive still ends up with the better frame afterwards.
  4703. #
  4704. # Measured across 261 attaches in the support bundles, the video lands a median
  4705. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  4706. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  4707. # was 546s. Every other model was inside 26s. The long budget is therefore
  4708. # almost entirely for P1-series users; on everything else the short wait already
  4709. # wins and this task never runs.
  4710. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  4711. async def _capture_finish_photo_from_timelapse(
  4712. archive_id: int,
  4713. archive_dir: Path,
  4714. timeout: float | None = None,
  4715. rotation: int = 0,
  4716. ) -> tuple[str | None, bool]:
  4717. """Wait for the per-print timelapse to land on the archive and extract its
  4718. last frame as the finish photo (#1397).
  4719. Bambu firmware stops timelapse recording after the toolhead parks but
  4720. before the bed-drop end-gcode runs, so the last frame frames the finished
  4721. print correctly. A live camera grab at gcode_state=FINISH captures the
  4722. bed already lowered.
  4723. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  4724. ``archive.timelapse_path`` when the file lands. This function polls for
  4725. that field.
  4726. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  4727. the wait ran out with no video on the archive yet — i.e. the video may
  4728. still be coming and a later attempt could succeed. It is False when the
  4729. video landed (whether or not extraction worked), because in that case
  4730. waiting longer changes nothing. The caller uses that to decide between
  4731. falling back permanently and scheduling a background upgrade.
  4732. ``rotation`` is the printer's camera_rotation, applied to the extracted
  4733. still (#2708) so this source agrees with every other finish-photo source.
  4734. The archived video itself is the printer's own file and is left alone —
  4735. rotating it would mean re-encoding it.
  4736. """
  4737. import uuid
  4738. from backend.app.models.archive import PrintArchive
  4739. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  4740. logger = logging.getLogger(__name__)
  4741. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  4742. deadline = asyncio.get_event_loop().time() + budget
  4743. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  4744. while True:
  4745. async with async_session() as db:
  4746. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4747. archive = result.scalar_one_or_none()
  4748. timelapse_relpath = archive.timelapse_path if archive else None
  4749. if timelapse_relpath:
  4750. video_path = app_settings.base_dir / timelapse_relpath
  4751. if video_path.exists() and video_path.stat().st_size > 0:
  4752. photos_dir = archive_dir / "photos"
  4753. photos_dir.mkdir(parents=True, exist_ok=True)
  4754. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4755. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4756. output_path = photos_dir / filename
  4757. if await extract_video_last_frame(video_path, output_path):
  4758. await apply_camera_rotation_to_file(output_path, rotation, logger)
  4759. logger.info(
  4760. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  4761. video_path.name,
  4762. archive_id,
  4763. )
  4764. return filename, False
  4765. logger.warning(
  4766. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  4767. video_path.name,
  4768. archive_id,
  4769. )
  4770. return None, False
  4771. if asyncio.get_event_loop().time() >= deadline:
  4772. logger.info(
  4773. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  4774. archive_id,
  4775. budget,
  4776. )
  4777. return None, True
  4778. await asyncio.sleep(poll_interval)
  4779. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  4780. """Add the timelapse's last frame to an archive after the fact (#2704).
  4781. The print-complete notification waits only ~60s for the video, because
  4782. holding a notification for minutes is worse than sending it with a live
  4783. camera grab. On a P1-series printer the video often lands well after that,
  4784. so the archive used to be stuck with the live grab — which is taken at
  4785. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  4786. the worse photo of the two.
  4787. This keeps waiting in the background and, when the video arrives, extracts
  4788. the frame and puts it *first* in the archive's photo list, so opening the
  4789. gallery shows it. The live grab is deliberately kept: the notification that
  4790. already went out links to that exact file, and deleting it would leave a
  4791. broken image in Discord or Telegram.
  4792. """
  4793. logger = logging.getLogger(__name__)
  4794. filename, _ = await _capture_finish_photo_from_timelapse(
  4795. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  4796. )
  4797. if not filename:
  4798. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  4799. return
  4800. try:
  4801. async with async_session() as db:
  4802. from backend.app.models.archive import PrintArchive
  4803. archive = await db.get(PrintArchive, archive_id)
  4804. if archive is None:
  4805. return
  4806. photos = list(archive.photos or [])
  4807. if filename in photos:
  4808. return
  4809. # Front of the list: PhotoGalleryModal opens at index 0.
  4810. archive.photos = [filename, *photos]
  4811. await db.commit()
  4812. except Exception as e:
  4813. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  4814. return
  4815. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  4816. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  4817. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  4818. """Put the filament-attribution context back after a restart mid-print.
  4819. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  4820. both die with the process. The print keeps running, so at completion the
  4821. tracker would fall back to whatever the printer reports *now* — and AMS
  4822. filament backup makes "now" the substitute tray, charging the whole print
  4823. to the spool that only finished it.
  4824. The persisted row is only trusted when its print name still matches what
  4825. the printer says it is running: a row left behind by a completion we never
  4826. saw must not attach itself to the next print.
  4827. """
  4828. try:
  4829. from backend.app.api.routes.settings import get_setting
  4830. from backend.app.services.usage_tracker import (
  4831. clear_persisted_session,
  4832. get_persisted_print_name,
  4833. restore_session,
  4834. )
  4835. persisted_name = await get_persisted_print_name(db, printer_id)
  4836. current_name = (state.subtask_name or "").strip()
  4837. if persisted_name and current_name and persisted_name.strip() != current_name:
  4838. logger.info(
  4839. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  4840. printer_id,
  4841. persisted_name,
  4842. current_name,
  4843. )
  4844. await clear_persisted_session(db, printer_id)
  4845. # Fall through to seeding: the print on the printer is real, it just
  4846. # isn't the one the row described.
  4847. persisted_log = None
  4848. else:
  4849. # Spoolman users get the tray-change log back but no in-memory
  4850. # session — see ``on_print_start`` on why that dict is load-bearing
  4851. # for the remain%-sync guard.
  4852. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4853. persisted_log = await restore_session(
  4854. db,
  4855. printer_id,
  4856. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  4857. )
  4858. if persisted_log:
  4859. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  4860. # Anything this process already observed goes after the persisted
  4861. # history — the log is ordered by layer, and a fresh process can
  4862. # only have seen changes from later in the print.
  4863. for entry in state.tray_change_log or []:
  4864. if tuple(entry) not in restored:
  4865. restored.append(tuple(entry))
  4866. state.tray_change_log = restored
  4867. tray_now = state.tray_now
  4868. if 0 <= tray_now <= 254:
  4869. if not state.tray_change_log:
  4870. # No persisted history — a print that started before this build,
  4871. # or before the row existed. Seed with the tray feeding right
  4872. # now so the remainder of the print is at least attributable to
  4873. # the right spool.
  4874. state.tray_change_log = [(tray_now, state.layer_num)]
  4875. logger.info(
  4876. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  4877. printer_id,
  4878. tray_now,
  4879. state.layer_num,
  4880. )
  4881. # The tray handler updates ``last_loaded_tray`` on every push
  4882. # regardless of whether it logged a change, so re-align it to avoid
  4883. # a duplicate entry on the next push. Only ever with a real tray:
  4884. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  4885. # 255" fallback, and writing 255 into it would defeat that.
  4886. state.last_loaded_tray = tray_now
  4887. except Exception:
  4888. # Never let attribution recovery cost the caller its timelapse
  4889. # baseline — that capture has to happen before the printer uploads
  4890. # the in-flight MP4 and there is no second chance at it.
  4891. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  4892. async def on_print_running_observed(printer_id: int, data: dict):
  4893. """Restart-recovery for a print that started before Bambuddy came up.
  4894. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  4895. after Bambuddy startup (#1304 guard, prevents duplicate archive
  4896. creation). This hook restores the persisted archive into ``_active_prints``
  4897. and captures the timelapse baseline that normally hangs off print start.
  4898. Fires once per session, in lieu of on_print_start when restart-recovery
  4899. kicks in. The printer doesn't upload the timelapse until after PRINT
  4900. COMPLETE, so a baseline captured any time during the print is still
  4901. pre-upload.
  4902. """
  4903. logger = logging.getLogger(__name__)
  4904. async with async_session() as db:
  4905. from backend.app.models.printer import Printer
  4906. state = printer_manager.get_status(printer_id)
  4907. if state is not None:
  4908. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  4909. if authorization is True:
  4910. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  4911. await _restore_usage_tracking_session(printer_id, state, db, logger)
  4912. await _restore_printable_objects(printer_id, state, db, logger)
  4913. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4914. printer = result.scalar_one_or_none()
  4915. if not printer:
  4916. logger.warning(
  4917. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  4918. printer_id,
  4919. )
  4920. return
  4921. # Avoid double-capture: ownership reconciliation above must still run when
  4922. # a baseline already exists, but the camera work itself is one-shot.
  4923. if printer_id in _timelapse_baselines:
  4924. logger.debug(
  4925. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  4926. printer_id,
  4927. )
  4928. return
  4929. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  4930. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  4931. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  4932. against the printer's current MQTT state.
  4933. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  4934. COMPLETE events, typically a print finishing during an MQTT disconnect
  4935. window followed by a smart-plug power cycle):
  4936. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  4937. provably not running anymore — only branch that should fire under
  4938. normal disconnect-then-reconnect timing.
  4939. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  4940. firmware mints a fresh ``subtask_id`` for each print, including the
  4941. ghost replay it runs after a power cycle from a leftover SD file —
  4942. so a mismatch unambiguously means the in-DB archive is no longer
  4943. the print on the printer.
  4944. 3. Printer is running but ``subtask_name`` is empty. The printer
  4945. doesn't know what it's running; the archive's reference to it is
  4946. already broken.
  4947. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  4948. with matching subtask_id+subtask_name is left alone. The cost of a false
  4949. positive is a duplicate archive on the next real PRINT COMPLETE — the
  4950. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  4951. clears on synthesis, so the real completion creates a fresh row instead
  4952. of overwriting the synthesised one (#1679). The cost of a false negative
  4953. is the ghost-print loop in #1542.
  4954. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  4955. MQTT has connected but the first ``push_status`` response hasn't been
  4956. applied yet — ``PrinterState`` is sitting on its construction defaults.
  4957. The reconcile caller in ``on_printer_status_change`` is already gated
  4958. on a real ``state.state``, so in normal operation this branch is
  4959. unreachable; it's kept as belt-and-braces for future callers and for
  4960. the narrow window where a partial state update could arrive
  4961. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  4962. ``not stale`` on degenerate input is strictly conservative: a real
  4963. stale archive will still be caught by the next push_status arriving
  4964. with terminal state.
  4965. """
  4966. current_state = (state.state or "").upper()
  4967. if current_state in ("", "UNKNOWN"):
  4968. # No real push_status yet — PrinterState defaults are not evidence.
  4969. return False, ""
  4970. if current_state in ("IDLE", "FINISH", "FAILED"):
  4971. return True, f"printer state {current_state}"
  4972. # Below here the printer is in a running / pre-running state (RUNNING /
  4973. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  4974. current_subtask_id = (state.subtask_id or "").strip()
  4975. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  4976. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  4977. current_subtask_name = (state.subtask_name or "").strip()
  4978. if not current_subtask_name:
  4979. return True, "printer subtask_name empty"
  4980. return False, ""
  4981. async def prime_kprofile_table(printer_id: int) -> int:
  4982. """Read the printer's calibration table once per connection.
  4983. The AMS slot card shows a K value per slot (#2854). On the printers whose
  4984. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  4985. report ``cali_idx`` and nothing else -- that number can only come from
  4986. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  4987. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  4988. backup, or the printer answering a query BambuStudio made on the report
  4989. topic we share. A Bambuddy that nobody visited showed a card with no K
  4990. values at all.
  4991. Only the diameters actually fitted are asked for, which is one request on a
  4992. single-nozzle printer and two on a dual. Probing the four sizes blind is
  4993. what the backup does, and it is both wasteful and the thing that used to
  4994. blank the table.
  4995. Returns the number of nozzles whose table was read.
  4996. """
  4997. client = printer_manager.get_client(printer_id)
  4998. state = printer_manager.get_status(printer_id)
  4999. if client is None or state is None or not state.connected:
  5000. return 0
  5001. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5002. # ask once, and both entries are empty until the first push_status lands.
  5003. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5004. if not diameters:
  5005. logging.getLogger(__name__).debug(
  5006. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5007. printer_id,
  5008. )
  5009. return 0
  5010. primed = 0
  5011. for diameter in diameters:
  5012. try:
  5013. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5014. except Exception as exc: # noqa: BLE001
  5015. # A printer that won't answer costs the card its K values, nothing
  5016. # more — never the connection this runs on the back of.
  5017. logging.getLogger(__name__).warning(
  5018. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5019. )
  5020. continue
  5021. primed += 1
  5022. logging.getLogger(__name__).info(
  5023. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5024. )
  5025. return primed
  5026. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5027. """Synthesise ``on_print_complete`` for archives whose print can't be
  5028. running on the printer anymore.
  5029. Called once per MQTT (re)connection (from on_printer_status_change when
  5030. the connected edge flips False → True) and at Bambuddy startup (from
  5031. the FastAPI lifespan). Without this, a print that completes during a
  5032. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5033. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5034. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5035. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5036. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5037. closes the loop by faking the missed PRINT COMPLETE — the existing
  5038. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5039. and notifications.
  5040. Synthesised ``status="aborted"`` is the conservative label: we have no
  5041. proof the print finished successfully (and no progress evidence to
  5042. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5043. fires later, overwrites the status with the correct value.
  5044. Returns the number of archives reconciled.
  5045. """
  5046. state = printer_manager.get_status(printer_id)
  5047. if not state:
  5048. return 0
  5049. # Don't reconcile while disconnected — we'd be making a decision against
  5050. # stale cached state. The connected → reconcile edge handles this.
  5051. if not state.connected:
  5052. return 0
  5053. from backend.app.models.archive import PrintArchive
  5054. reconciled = 0
  5055. async with async_session() as db:
  5056. result = await db.execute(
  5057. select(PrintArchive).where(
  5058. PrintArchive.printer_id == printer_id,
  5059. PrintArchive.status == "printing",
  5060. )
  5061. )
  5062. active = list(result.scalars().all())
  5063. if not active:
  5064. return 0
  5065. logger = logging.getLogger(__name__)
  5066. for archive in active:
  5067. is_stale, reason = _is_active_archive_stale(archive, state)
  5068. if not is_stale:
  5069. continue
  5070. logger.info(
  5071. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5072. printer_id,
  5073. archive.id,
  5074. archive.filename,
  5075. reason,
  5076. )
  5077. # Synthesised payload: minimal fields the on_print_complete chain
  5078. # needs. `_reconciled` marker lets downstream code distinguish this
  5079. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5080. # metrics / debug logging). raw_data is the live printer state so
  5081. # the usage tracker can compare end-of-print remain% against the
  5082. # captured start values.
  5083. try:
  5084. await on_print_complete(
  5085. printer_id,
  5086. {
  5087. "status": "aborted",
  5088. "filename": archive.filename,
  5089. "subtask_name": archive.print_name or "",
  5090. "subtask_id": archive.subtask_id or "",
  5091. "raw_data": state.raw_data or {},
  5092. "_reconciled": True,
  5093. },
  5094. )
  5095. reconciled += 1
  5096. except Exception as e:
  5097. # Catch-all: a reconciliation failure must not block the
  5098. # printer's normal status flow. The archive stays in
  5099. # ``status="printing"`` and the next reconnect retries.
  5100. logger.warning(
  5101. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5102. archive.id,
  5103. e,
  5104. )
  5105. return reconciled
  5106. # #2547: clearance left between the nozzle and the top of the print when the
  5107. # plate is commanded back into camera framing. The nozzle is parked away from
  5108. # the part by then, so this is belt-and-braces against a max_z_height that
  5109. # under-reports (e.g. a slicer that excludes a final Z hop).
  5110. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5111. # How far below the restored position to drop the plate again afterwards, so
  5112. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5113. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5114. # on machines with less headroom.
  5115. _PLATE_PARK_DROP_MM = 100.0
  5116. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5117. # this axis, so it is a proven-safe speed for the full travel.
  5118. _PLATE_RESTORE_FEEDRATE = 600
  5119. # Time allowed for the plate to reach the restored position before the camera
  5120. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5121. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5122. # How long `_background_finish_photo` waits for this producer. Must cover the
  5123. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5124. # notification path's own photo wait so a slow producer degrades to a
  5125. # photo-less notification rather than a missed one.
  5126. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5127. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  5128. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5129. This number becomes the target of a real Z move, so every step here refuses
  5130. rather than guesses. A height belonging to some *other* print is the one
  5131. failure that could drive the nozzle into the model: 20 mm carried onto a
  5132. 200 mm print would command the plate up through the part.
  5133. Two independent things therefore have to agree before a height is returned:
  5134. 1. **Identity.** The archive is matched by the finished print's own
  5135. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  5136. resolve to "Cube v2". Matching on "most recent archive for this printer"
  5137. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  5138. binding concurrently with us, and a print Bambuddy failed to archive
  5139. would silently resolve to its predecessor.
  5140. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5141. match the layer count the printer itself reported over MQTT for the print
  5142. that just ended. These come from genuinely different sources, so a
  5143. mismatch means the row is not this print, whatever its name says.
  5144. ``completed`` is accepted alongside ``printing`` only because
  5145. ``on_print_complete`` may already have flipped the status by the time we
  5146. run; the identity check above is what actually selects the row.
  5147. """
  5148. subtask_name = (data.get("subtask_name") or "").strip()
  5149. if not subtask_name:
  5150. # Nothing to identify the print by — refuse rather than fall back to
  5151. # "whatever ran last on this printer".
  5152. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5153. return None
  5154. try:
  5155. from backend.app.models.archive import PrintArchive
  5156. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5157. async with async_session() as db:
  5158. result = await db.execute(
  5159. select(PrintArchive)
  5160. .where(
  5161. PrintArchive.printer_id == printer_id,
  5162. PrintArchive.status.in_(("printing", "completed")),
  5163. PrintArchive.deleted_at.is_(None),
  5164. or_(
  5165. PrintArchive.print_name == subtask_name,
  5166. PrintArchive.filename == subtask_name,
  5167. PrintArchive.filename == f"{subtask_name}.3mf",
  5168. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  5169. ),
  5170. )
  5171. .order_by(PrintArchive.id.desc())
  5172. .limit(1)
  5173. )
  5174. archive = result.scalar_one_or_none()
  5175. if archive is None or not archive.file_path:
  5176. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  5177. return None
  5178. client = printer_manager.get_client(printer_id)
  5179. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  5180. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  5181. logger.warning(
  5182. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  5183. "— refusing to move the plate on a height that may not be this print's",
  5184. printer_id,
  5185. archive.id,
  5186. archive.total_layers,
  5187. reported_layers,
  5188. )
  5189. return None
  5190. path = Path(archive.file_path)
  5191. if not path.is_absolute():
  5192. path = Path(app_settings.data_dir) / path
  5193. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  5194. except Exception as e:
  5195. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  5196. return None
  5197. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  5198. """Raise the plate back into camera framing before the finish photo (#2547).
  5199. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  5200. the time ``gcode_state`` reaches FINISH the finished print sits far below
  5201. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  5202. This commands an absolute ``G1 Z`` back to just above the last printed
  5203. layer.
  5204. Absolute, not relative, is the whole safety argument. ``max_z_height +
  5205. clearance`` is a height the toolhead was physically at seconds earlier, so
  5206. it is inside the travel limits by construction and leaves the nozzle above
  5207. the part. It is also unambiguous across model families: Z is the
  5208. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  5209. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  5210. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  5211. (#2579).
  5212. Returns True if the move was sent and waited out, False if it was skipped.
  5213. """
  5214. client = printer_manager.get_client(printer_id)
  5215. if client is None:
  5216. return False
  5217. # Re-read state immediately before commanding motion. If the queue has
  5218. # already started the next print, the printer is no longer ours to move.
  5219. state = getattr(client, "state", None)
  5220. if state is None or state.state != "FINISH":
  5221. logger.info(
  5222. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  5223. printer_id,
  5224. getattr(state, "state", "unknown"),
  5225. )
  5226. return False
  5227. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  5228. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  5229. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  5230. return False
  5231. logger.info(
  5232. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  5233. printer_id,
  5234. target_z,
  5235. max_z_height,
  5236. _PLATE_RESTORE_CLEARANCE_MM,
  5237. _PLATE_RESTORE_SETTLE_SECONDS,
  5238. )
  5239. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  5240. return True
  5241. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  5242. """Drop the plate again after the finish photo (#2547).
  5243. Without this the user walks up to a finished print sitting just under the
  5244. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  5245. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  5246. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  5247. print homes anyway.
  5248. """
  5249. client = printer_manager.get_client(printer_id)
  5250. state = getattr(client, "state", None) if client else None
  5251. if client is None or state is None or state.state != "FINISH":
  5252. return
  5253. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  5254. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  5255. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  5256. """True if a queue item is about to take this printer (#2547).
  5257. The scheduler dispatches the next job the moment a print completes, and a
  5258. plate move interleaved with a print start is not a race worth having. The
  5259. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  5260. this window; this closes the head of it.
  5261. """
  5262. try:
  5263. from backend.app.models.print_queue import PrintQueueItem
  5264. async with async_session() as db:
  5265. result = await db.execute(
  5266. select(PrintQueueItem.id)
  5267. .where(
  5268. PrintQueueItem.printer_id == printer_id,
  5269. PrintQueueItem.status.in_(("pending", "printing")),
  5270. )
  5271. .limit(1)
  5272. )
  5273. return result.scalar_one_or_none() is not None
  5274. except Exception as e:
  5275. # Fail closed: if we can't tell, don't move the plate.
  5276. logging.getLogger(__name__).debug(
  5277. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  5278. )
  5279. return True
  5280. async def on_finish_photo_moment(printer_id: int, data: dict):
  5281. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  5282. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  5283. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  5284. fallback for prints that skip stage 22 (cancel, external-spool-only,
  5285. HMS halt, firmware variants). Grabs one frame via the same
  5286. external-camera / RTSP path the post-completion fallback uses, stores
  5287. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  5288. ``_background_finish_photo`` consume the cached bytes when it runs.
  5289. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  5290. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  5291. set to Smooth (#1721). No force-on now means the user's explicit
  5292. timelapse=off in the slicer send dialog is respected.
  5293. """
  5294. logger = logging.getLogger(__name__)
  5295. trigger = data.get("trigger", "unknown")
  5296. timelapse_was_active = bool(data.get("timelapse_was_active"))
  5297. logger.info(
  5298. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  5299. printer_id,
  5300. trigger,
  5301. timelapse_was_active,
  5302. )
  5303. # If a timelapse is actively recording, skip the pre-capture — the
  5304. # post-completion path will extract the last frame from the recorded
  5305. # video, which still provides the best framing (toolhead parked,
  5306. # before bed drop) without the per-layer parking side effects.
  5307. if timelapse_was_active:
  5308. logger.info(
  5309. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  5310. printer_id,
  5311. )
  5312. return
  5313. # #1790: register the producer-done event BEFORE the first await so the
  5314. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  5315. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  5316. # The `finally` below guarantees `set()` runs on every exit, including
  5317. # early returns and exceptions, so the consumer's bounded wait can't hang.
  5318. producer_done = asyncio.Event()
  5319. _stage22_finish_in_flight[printer_id] = producer_done
  5320. # #2547: set once the plate has actually been raised, and read by the
  5321. # `finally` below. Declared out here so a failure anywhere after the move —
  5322. # a camera timeout, a DB error — still lowers the plate again.
  5323. restore_max_z: float | None = None
  5324. try:
  5325. async with async_session() as db:
  5326. from backend.app.api.routes.settings import get_setting
  5327. from backend.app.models.printer import Printer
  5328. capture_setting = await get_setting(db, "capture_finish_photo")
  5329. if capture_setting is not None and capture_setting.lower() != "true":
  5330. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  5331. return
  5332. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  5333. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  5334. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5335. printer = result.scalar_one_or_none()
  5336. if printer is None:
  5337. logger.warning(
  5338. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  5339. printer_id,
  5340. )
  5341. return
  5342. frame_bytes: bytes | None = None
  5343. # #2708: the banked frame arrives already rotated — it comes from
  5344. # `_capture_snapshot_for_notification`, which rotates before returning.
  5345. # Every other source below is a raw grab. Tracking which lets us store
  5346. # exactly one rotation in `_stage22_finish_frames` either way.
  5347. frame_already_rotated = False
  5348. # On the FINISH-state path the End G-code has already run, and two very
  5349. # different situations arrive here needing opposite answers.
  5350. #
  5351. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  5352. # snippet may have ejected the plate — the scene in front of the camera
  5353. # is no longer the finished print, and no amount of moving the plate
  5354. # brings it back. Use the banked in-print frame instead.
  5355. #
  5356. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  5357. # than the camera frames well, and the toolhead is parked out of the
  5358. # way. That is the *best* moment available on firmware that never emits
  5359. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  5360. # back. Preferring the bank here unconditionally, as this code used to,
  5361. # is what shipped a mid-print photo with the toolhead over the part.
  5362. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  5363. banked = _inprint_frame_bank.get(printer_id)
  5364. if banked:
  5365. frame_bytes = banked
  5366. frame_already_rotated = True
  5367. logger.info(
  5368. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  5369. "frame (%d bytes) instead of a post-swap live grab",
  5370. len(banked),
  5371. )
  5372. else:
  5373. logger.warning(
  5374. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  5375. "in-print bank is empty — falling back to a live grab, which may show a "
  5376. "swapped or empty plate",
  5377. printer_id,
  5378. )
  5379. # `restore_max_z` is set only once the plate is actually up, because the
  5380. # `finally` reads it to decide whether it owes a move back down.
  5381. #
  5382. # Never on a print whose End G-code Bambuddy injected, even when the bank
  5383. # came up empty above: that machine may have just ejected its plate, and
  5384. # driving Z into whatever a swap mechanism is doing is not a risk worth
  5385. # taking for a photo of a bed we already know may be bare.
  5386. if (
  5387. frame_bytes is None
  5388. and trigger == "finish_state"
  5389. and restore_plate_enabled
  5390. and not print_dispatch_context.end_gcode_injected(printer_id)
  5391. ):
  5392. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  5393. if wants_restore is None:
  5394. logger.info(
  5395. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  5396. printer_id,
  5397. )
  5398. elif await _plate_restore_is_blocked_by_queue(printer_id):
  5399. logger.info(
  5400. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  5401. printer_id,
  5402. )
  5403. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  5404. restore_max_z = wants_restore
  5405. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  5406. from backend.app.api.routes.camera import live_frame_for_capture
  5407. from backend.app.services.external_camera import capture_frame
  5408. # #2707: this used to collide with the live view and fail, which is
  5409. # how finish-photo notifications went out with no image attached.
  5410. # Leaving frame_bytes None keeps the rest of the fallback chain.
  5411. defer, buffered = live_frame_for_capture(printer_id)
  5412. if defer:
  5413. frame_bytes = buffered
  5414. else:
  5415. frame_bytes = await capture_frame(
  5416. printer.external_camera_url,
  5417. printer.external_camera_type or "mjpeg",
  5418. snapshot_url=printer.external_camera_snapshot_url,
  5419. )
  5420. if frame_bytes:
  5421. logger.info(
  5422. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  5423. len(frame_bytes),
  5424. )
  5425. elif frame_bytes is None:
  5426. from backend.app.api.routes.camera import get_buffered_frame
  5427. buffered = get_buffered_frame(printer_id)
  5428. if buffered:
  5429. frame_bytes = buffered
  5430. logger.info(
  5431. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  5432. len(frame_bytes),
  5433. )
  5434. else:
  5435. from backend.app.services.camera import capture_camera_frame_bytes
  5436. frame_bytes = await capture_camera_frame_bytes(
  5437. ip_address=printer.ip_address,
  5438. access_code=printer.access_code,
  5439. model=printer.model,
  5440. timeout=15,
  5441. )
  5442. if frame_bytes:
  5443. logger.info(
  5444. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  5445. len(frame_bytes),
  5446. )
  5447. if frame_bytes:
  5448. if not frame_already_rotated:
  5449. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  5450. _stage22_finish_frames[printer_id] = frame_bytes
  5451. else:
  5452. logger.warning(
  5453. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  5454. printer_id,
  5455. )
  5456. except Exception as e:
  5457. logger.warning(
  5458. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  5459. printer_id,
  5460. e,
  5461. )
  5462. finally:
  5463. # #2547: we raised the plate, so we own lowering it — including when the
  5464. # capture above failed or threw partway through.
  5465. if restore_max_z is not None:
  5466. try:
  5467. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  5468. except Exception as e:
  5469. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  5470. # #1790: always unblock the consumer's bounded wait — whether we stored
  5471. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  5472. # dict entry by the consumer doesn't affect signalling.
  5473. producer_done.set()
  5474. def _subtask_name_from_filename(filename: str) -> str:
  5475. """Recover the subtask name a print command would have carried for *filename*.
  5476. The dispatcher derives the printer-facing subtask name from the archive's
  5477. file name, so stripping the extensions back off gives the value MQTT echoes
  5478. on completion. Only the two extensions Bambuddy actually stores are removed,
  5479. and in the order they nest (``.gcode.3mf``), so a model whose own name
  5480. contains a dot -- ``My.Model.3mf`` -- keeps it.
  5481. """
  5482. name = PurePosixPath(filename).name
  5483. for suffix in (".3mf", ".gcode"):
  5484. if name.lower().endswith(suffix):
  5485. name = name[: -len(suffix)]
  5486. return name
  5487. # How the printer marks a subtask name it had to cut short. Observed on real
  5488. # hardware at ~100 characters, but the cut-off is not a fixed character count
  5489. # (a name with multibyte characters came back at 98), so match the marker
  5490. # rather than a length.
  5491. _SUBTASK_TRUNCATION_MARKER = "..."
  5492. def _normalise_subtask_name(name: str) -> str:
  5493. """Canonical form for comparing a dispatched name against MQTT's echo.
  5494. The printer does not echo the name back verbatim: it substitutes
  5495. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  5496. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  5497. The 3MF lookup in this module has always known that -- it builds
  5498. space-to-underscore variants of every candidate filename, and its
  5499. directory search normalises both sides before comparing. This exists so
  5500. the completion check reads the same rule from the same place instead of
  5501. growing its own, which is exactly how it came to disagree (#2829).
  5502. """
  5503. return name.strip().replace(" ", "_").casefold()
  5504. def _subtask_names_match(expected: str, observed: str) -> bool:
  5505. """Whether two subtask names describe the same print.
  5506. Beyond the space/underscore substitution, the printer truncates long names
  5507. and marks the cut with ``...``. A truncated echo has to count as a match or
  5508. every print with a long name strands its queue item the same way.
  5509. """
  5510. expected_n = _normalise_subtask_name(expected)
  5511. observed_n = _normalise_subtask_name(observed)
  5512. if expected_n == observed_n:
  5513. return True
  5514. # Either side can be the truncated one: the printer truncates what it
  5515. # echoes, and an archive whose own filename was recorded from a previous
  5516. # truncated echo carries the marker too.
  5517. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  5518. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  5519. return True
  5520. return False
  5521. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  5522. """Whether this completion event is plausibly about *item*'s print.
  5523. The caller finds its queue row by printer and ``status='printing'`` alone,
  5524. which is all a completion event gives it -- there is no run identifier in
  5525. the MQTT payload to match on. That makes the lookup indiscriminate: any
  5526. completion delivered for this printer closes whichever row happens to be
  5527. printing, however unrelated. Comparing the subtask name against the archive
  5528. the row was dispatched with costs one primary-key load and rules that out.
  5529. Deliberately permissive: it answers False only on a positive disagreement
  5530. between two names we actually have. A row with no archive, an archive with
  5531. no file name, or an event with no subtask name is unverifiable rather than
  5532. wrong, and refusing those would strand the item in ``printing`` and wedge
  5533. the printer's queue -- a worse failure than the one being prevented.
  5534. """
  5535. observed = (data.get("subtask_name") or "").strip()
  5536. if not observed or item.archive_id is None:
  5537. return True
  5538. from backend.app.models.archive import PrintArchive
  5539. archive = await db.get(PrintArchive, item.archive_id)
  5540. if archive is None or not archive.filename:
  5541. return True
  5542. expected = _subtask_name_from_filename(archive.filename)
  5543. if not expected or _subtask_names_match(expected, observed):
  5544. return True
  5545. logging.getLogger(__name__).warning(
  5546. "Ignoring print completion for queue item %s: it was dispatched as %r "
  5547. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  5548. "printing rather than closing a run this event is not about.",
  5549. item.id,
  5550. expected,
  5551. archive.id,
  5552. archive.filename,
  5553. observed,
  5554. )
  5555. return False
  5556. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  5557. """Spend the 3MF download cache on a still-empty fallback archive.
  5558. ``on_print_complete`` drops the cache as its first act, which deletes the
  5559. file. If the cover endpoint (or anything else) pulled the 3MF while the
  5560. print ran and the archive never got one, this is the last moment those bytes
  5561. exist (#2957).
  5562. """
  5563. logger = logging.getLogger(__name__)
  5564. names = [
  5565. n
  5566. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  5567. if n
  5568. ]
  5569. for name in names:
  5570. try:
  5571. cached = get_cached_3mf(printer_id, name)
  5572. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  5573. return
  5574. except Exception as e:
  5575. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  5576. async def on_print_complete(printer_id: int, data: dict):
  5577. """Handle print completion - update the archive status."""
  5578. import time
  5579. logger = logging.getLogger(__name__)
  5580. start_time = time.time()
  5581. def log_timing(section: str):
  5582. elapsed = time.time() - start_time
  5583. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  5584. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  5585. # A kill-switch stop sends its provider notification immediately. Keep the
  5586. # task so the later notification path can await it and avoid a duplicate;
  5587. # if that immediate attempt failed, the regular completion path retries.
  5588. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  5589. # Last chance before the bytes go: if this print's archive is still an empty
  5590. # fallback and something downloaded the 3MF while it ran, fill the archive in
  5591. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  5592. # below deletes the file (#2957).
  5593. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  5594. # A pending cool-off retry has nothing left to recover for — the cache is
  5595. # about to be dropped and the print is over.
  5596. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  5597. if retry_task and not retry_task.done():
  5598. retry_task.cancel()
  5599. # Drop the 3MF download cache for this printer (#972). The print is over,
  5600. # nothing else legitimately needs the bytes; keeping them would only risk
  5601. # handing a stale file to the next print if it reuses the same name.
  5602. clear_3mf_cache(printer_id)
  5603. try:
  5604. ws_data = {
  5605. "status": data.get("status"),
  5606. "filename": data.get("filename"),
  5607. "subtask_name": data.get("subtask_name"),
  5608. "timelapse_was_active": data.get("timelapse_was_active"),
  5609. }
  5610. await ws_manager.send_print_complete(printer_id, ws_data)
  5611. log_timing("WebSocket send_print_complete")
  5612. except Exception as e:
  5613. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  5614. # Capture user info before clearing (needed for print log entry)
  5615. _print_user_info = printer_manager.get_current_print_user(printer_id)
  5616. # Clear current print user tracking (Issue #206)
  5617. printer_manager.clear_current_print_user(printer_id)
  5618. # If the user explicitly stopped this print from the queue UI the printer will
  5619. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  5620. # correct "print stopped" notification/email is sent instead of a failure alert.
  5621. _raw_status = data.get("status", "completed")
  5622. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  5623. logger.info(
  5624. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  5625. _raw_status,
  5626. printer_id,
  5627. )
  5628. data = {**data, "status": "cancelled"}
  5629. _user_stopped_printers.discard(printer_id)
  5630. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  5631. # may have left material on the bed: a user can cancel ten hours into a
  5632. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  5633. # touchscreen-stop reports `aborted` rather than `cancelled` because
  5634. # `_user_stopped_printers` is only populated when the user stops via the
  5635. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  5636. # which auto-dispatched the next queued print onto a fouled bed two seconds
  5637. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  5638. # Auto Off power cycles and Bambuddy restarts.
  5639. _final_status = data.get("status", "completed")
  5640. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  5641. printer_manager.set_awaiting_plate_clear(printer_id, True)
  5642. # MQTT relay - publish print complete
  5643. try:
  5644. printer_info = printer_manager.get_printer(printer_id)
  5645. if printer_info:
  5646. await mqtt_relay.on_print_complete(
  5647. printer_id,
  5648. printer_info.name,
  5649. printer_info.serial_number,
  5650. data.get("filename", ""),
  5651. data.get("subtask_name", ""),
  5652. data.get("status", "completed"),
  5653. )
  5654. except Exception:
  5655. pass # Don't fail print complete callback if MQTT fails
  5656. filename = data.get("filename", "")
  5657. subtask_name = data.get("subtask_name", "")
  5658. if not filename and not subtask_name:
  5659. logger.warning("Print complete without filename or subtask_name")
  5660. return
  5661. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  5662. # Build list of possible keys to try (matching how they were registered in on_print_start)
  5663. possible_keys = []
  5664. # Try subtask_name variations first (most reliable for matching)
  5665. if subtask_name:
  5666. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5667. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5668. possible_keys.append((printer_id, subtask_name))
  5669. # Try filename variations
  5670. if filename:
  5671. # Extract just the filename if it's a path
  5672. fname = filename.split("/")[-1] if "/" in filename else filename
  5673. if fname.endswith(".3mf"):
  5674. possible_keys.append((printer_id, fname))
  5675. elif fname.endswith(".gcode"):
  5676. base_name = fname.rsplit(".", 1)[0]
  5677. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5678. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5679. possible_keys.append((printer_id, fname))
  5680. else:
  5681. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5682. possible_keys.append((printer_id, f"{fname}.3mf"))
  5683. possible_keys.append((printer_id, fname))
  5684. # Also try full path versions
  5685. if filename.endswith(".3mf"):
  5686. possible_keys.append((printer_id, filename))
  5687. elif filename.endswith(".gcode"):
  5688. base_name = filename.rsplit(".", 1)[0]
  5689. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5690. possible_keys.append((printer_id, filename))
  5691. else:
  5692. possible_keys.append((printer_id, f"{filename}.3mf"))
  5693. possible_keys.append((printer_id, filename))
  5694. # Find the archive for this print
  5695. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  5696. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  5697. archive_id = None
  5698. for key in possible_keys:
  5699. archive_id = _active_prints.pop(key, None)
  5700. if archive_id:
  5701. logger.info("Found archive %s with key %s", archive_id, key)
  5702. # Also clean up any other keys pointing to this archive
  5703. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  5704. for k in keys_to_remove:
  5705. _active_prints.pop(k, None)
  5706. break
  5707. if not archive_id:
  5708. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  5709. async with async_session() as db:
  5710. from backend.app.models.archive import PrintArchive
  5711. # Try matching by subtask_name (stored as print_name) first
  5712. if subtask_name:
  5713. result = await db.execute(
  5714. select(PrintArchive)
  5715. .where(PrintArchive.printer_id == printer_id)
  5716. .where(PrintArchive.status == "printing")
  5717. .where(
  5718. or_(
  5719. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  5720. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  5721. )
  5722. )
  5723. .order_by(PrintArchive.created_at.desc())
  5724. .limit(1)
  5725. )
  5726. archive = result.scalar_one_or_none()
  5727. if archive:
  5728. archive_id = archive.id
  5729. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  5730. # Also try by filename
  5731. if not archive_id and filename:
  5732. result = await db.execute(
  5733. select(PrintArchive)
  5734. .where(PrintArchive.printer_id == printer_id)
  5735. .where(PrintArchive.filename == filename)
  5736. .where(PrintArchive.status == "printing")
  5737. .order_by(PrintArchive.created_at.desc())
  5738. .limit(1)
  5739. )
  5740. archive = result.scalar_one_or_none()
  5741. if archive:
  5742. archive_id = archive.id
  5743. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  5744. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  5745. # auto-start files found in root on power cycle, causing ghost prints.
  5746. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  5747. try:
  5748. if subtask_name:
  5749. archive_filename: str | None = None
  5750. async with async_session() as db:
  5751. from backend.app.models.archive import PrintArchive
  5752. from backend.app.models.printer import Printer
  5753. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5754. printer = result.scalar_one_or_none()
  5755. if archive_id:
  5756. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  5757. archive_filename = archive_row.scalar_one_or_none()
  5758. if printer:
  5759. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  5760. from backend.app.utils.filename import derive_remote_filename
  5761. # Primary candidate: the exact path the dispatcher uploaded to
  5762. # (derived from archive.filename via the same rule as upload).
  5763. # Without it, a library row that ended up with a doubled
  5764. # .gcode.3mf (#1542) leaves the real file behind because the
  5765. # subtask_name + ext fallbacks below don't match what's on the
  5766. # SD card. Fallbacks remain for archive-less prints (subtask
  5767. # never resolved to an archive) and for older naming variants.
  5768. candidate_paths: list[str] = []
  5769. if archive_filename:
  5770. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  5771. for ext in (".3mf", ".gcode"):
  5772. fallback = f"/{subtask_name}{ext}"
  5773. if fallback not in candidate_paths:
  5774. candidate_paths.append(fallback)
  5775. # Three outcomes track across all candidates so the final log
  5776. # line reflects what actually happened. The A1 in #1721 always
  5777. # ends here with ``any_not_found=True`` and the others False
  5778. # — its firmware auto-cleans the SD card before our cleanup
  5779. # runs, every candidate FTP-DELE returns 550, and the old
  5780. # code burned 3 retries × 2 s × 3 candidates per print
  5781. # logging a misleading "may linger" WARNING on a successful
  5782. # print.
  5783. any_deleted = False
  5784. any_real_failure = False
  5785. any_not_found = False
  5786. for remote_path in candidate_paths:
  5787. # Retry only the FAILED case — 550 NOT_FOUND will never
  5788. # recover by waiting, so a "file isn't here" answer
  5789. # advances immediately to the next candidate without
  5790. # consuming the retry budget.
  5791. for attempt in range(1, 4):
  5792. try:
  5793. delete_result = await delete_file_async(
  5794. printer.ip_address,
  5795. printer.access_code,
  5796. remote_path,
  5797. printer_model=printer.model,
  5798. )
  5799. except Exception as e:
  5800. delete_result = DeleteResult.FAILED
  5801. logger.warning(
  5802. "SD card cleanup attempt %d/3 raised for %s: %s",
  5803. attempt,
  5804. remote_path,
  5805. e,
  5806. )
  5807. if delete_result == DeleteResult.DELETED:
  5808. any_deleted = True
  5809. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  5810. break
  5811. if delete_result == DeleteResult.NOT_FOUND:
  5812. any_not_found = True
  5813. break # 550 will not recover; try next candidate
  5814. # FAILED: real error — retry with backoff, then give up
  5815. if attempt < 3:
  5816. await asyncio.sleep(2)
  5817. else:
  5818. any_real_failure = True
  5819. logger.warning(
  5820. "SD card cleanup failed after 3 attempts for %s "
  5821. "(network/auth/transient error — file may linger on SD card)",
  5822. remote_path,
  5823. )
  5824. if not any_deleted and not any_real_failure and any_not_found:
  5825. # Every candidate said "not here." Either the printer
  5826. # firmware swept the SD card itself (common on A1) or the
  5827. # dispatcher's upload path doesn't match our candidate
  5828. # rule. Either way: nothing to clean up, no warning.
  5829. logger.debug(
  5830. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  5831. "(printer likely self-cleaned)",
  5832. printer.name,
  5833. )
  5834. except Exception as e:
  5835. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  5836. log_timing("SD card cleanup")
  5837. # Update queue item status early — must run before the archive_id early-return
  5838. # so queue items don't get stuck in "printing" when archive lookup fails.
  5839. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  5840. queue_item_id = None
  5841. billing_run_id: str | None = None
  5842. billing_user_id: int | None = None
  5843. billing_cost_center_id: int | None = None
  5844. billing_plate_id: int | None = None
  5845. queue_status = None
  5846. queue_auto_off = False
  5847. try:
  5848. from backend.app.core.database import run_with_retry
  5849. from backend.app.models.print_queue import PrintQueueItem
  5850. async def _update_queue_status(db):
  5851. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  5852. nonlocal queue_item_id, queue_status, queue_auto_off
  5853. result = await db.execute(
  5854. select(PrintQueueItem)
  5855. .where(PrintQueueItem.printer_id == printer_id)
  5856. .where(PrintQueueItem.status == "printing")
  5857. )
  5858. printing_items = list(result.scalars().all())
  5859. if len(printing_items) > 1:
  5860. logger.warning(
  5861. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  5862. printer_id,
  5863. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  5864. )
  5865. item = printing_items[0] if printing_items else None
  5866. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  5867. return
  5868. if item:
  5869. queue_status = data.get("status", "completed")
  5870. # MQTT sends "aborted" for cancelled prints; normalise to
  5871. # "cancelled" so it matches the queue schema Literal.
  5872. if queue_status == "aborted":
  5873. queue_status = "cancelled"
  5874. item.status = queue_status
  5875. item.completed_at = datetime.now(timezone.utc)
  5876. if queue_status == "failed" and not item.error_message:
  5877. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  5878. # Bump usage counters on the source library file so admins can
  5879. # sort by "last printed" and (eventually) auto-purge stale
  5880. # files — #1008.
  5881. await _bump_library_file_usage_if_completed(db, item, queue_status)
  5882. await db.commit()
  5883. queue_item_id = item.id
  5884. billing_run_id = item.billing_run_id
  5885. billing_user_id = item.created_by_id
  5886. billing_cost_center_id = item.cost_center_id
  5887. billing_plate_id = item.plate_id
  5888. queue_auto_off = item.auto_off_after
  5889. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  5890. await run_with_retry(_update_queue_status, label="queue status update")
  5891. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  5892. # their own sessions and have their own error handling — no retry needed.
  5893. if queue_item_id is not None:
  5894. # Batch orders (#342): this run may have been the last one an order
  5895. # owed. Re-evaluate here rather than lazily on read, so a finished
  5896. # order reports itself complete without someone opening the page.
  5897. try:
  5898. from backend.app.services.print_batch import refresh_batch_status_for_item
  5899. async with async_session() as db:
  5900. await refresh_batch_status_for_item(db, queue_item_id)
  5901. await db.commit()
  5902. except Exception as e:
  5903. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  5904. # MQTT relay - publish queue job completed
  5905. try:
  5906. printer_info = printer_manager.get_printer(printer_id)
  5907. await mqtt_relay.on_queue_job_completed(
  5908. job_id=queue_item_id,
  5909. filename=filename or subtask_name,
  5910. printer_id=printer_id,
  5911. printer_name=printer_info.name if printer_info else "Unknown",
  5912. status=queue_status,
  5913. )
  5914. except Exception:
  5915. pass # Don't fail if MQTT fails
  5916. # Check if queue is now empty and send notification
  5917. try:
  5918. from sqlalchemy import func as sa_func
  5919. async with async_session() as db:
  5920. count_result = await db.execute(
  5921. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  5922. )
  5923. pending_count = count_result.scalar() or 0
  5924. if pending_count == 0:
  5925. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  5926. completed_result = await db.execute(
  5927. select(sa_func.count(PrintQueueItem.id)).where(
  5928. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  5929. PrintQueueItem.completed_at >= today_start,
  5930. )
  5931. )
  5932. completed_count = completed_result.scalar() or 1
  5933. await notification_service.on_queue_completed(
  5934. completed_count=completed_count,
  5935. db=db,
  5936. )
  5937. except Exception:
  5938. pass # Don't fail if notification fails
  5939. # Handle auto_off_after - power off printer if the queue item opted
  5940. # in. Delegates to the smart-plug manager so the off honours each
  5941. # plug's configured strategy (time delay or temperature threshold),
  5942. # is cancelled if the printer starts printing again, and never cuts
  5943. # power on a loaded print (#1890). Previously an inline block here
  5944. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  5945. # timeout regardless of print state — cutting a touchscreen reprint.
  5946. if queue_auto_off:
  5947. try:
  5948. async with async_session() as db:
  5949. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  5950. except Exception as e:
  5951. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  5952. except Exception as e:
  5953. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  5954. log_timing("Queue item update")
  5955. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  5956. # Must run before archive_id early-return so it fires for all prints (including
  5957. # prints started from BambuStudio/touchscreen that have no archive).
  5958. if data.get("status") == "completed":
  5959. try:
  5960. from backend.app.api.routes.settings import get_setting
  5961. async with async_session() as db:
  5962. threshold_str = await get_setting(db, "bed_cooled_threshold")
  5963. threshold = float(threshold_str) if threshold_str else 35.0
  5964. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  5965. async with async_session() as db:
  5966. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  5967. if providers:
  5968. _bed_cool_waiters[printer_id] = {
  5969. "threshold": threshold,
  5970. "filename": filename or subtask_name or "",
  5971. "registered_at": time.time(),
  5972. }
  5973. logger.info(
  5974. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  5975. printer_id,
  5976. threshold,
  5977. )
  5978. else:
  5979. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  5980. except Exception as e:
  5981. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  5982. # Capture the slicer estimate before usage tracking runs. The tracker may
  5983. # update archive.cost with this run's measured cost; billing partial runs
  5984. # against that already-partial value would discount the charge twice.
  5985. billing_planned_grams: float | None = None
  5986. billing_base_cost: float | None = None
  5987. if archive_id:
  5988. try:
  5989. async with async_session() as db:
  5990. from backend.app.models.archive import PrintArchive
  5991. billing_archive = await db.get(PrintArchive, archive_id)
  5992. if billing_archive:
  5993. billing_path = (
  5994. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  5995. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5996. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  5997. billing_archive,
  5998. billing_path,
  5999. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6000. )
  6001. except Exception as e:
  6002. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6003. # --- Track filament consumption (must run before archive_id early-return so usage
  6004. # is recorded even when auto-archive is disabled) ---
  6005. usage_results: list[dict] = []
  6006. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6007. stored_ams_mapping = data.get("ams_mapping")
  6008. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6009. if not stored_ams_mapping and archive_id:
  6010. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6011. # Always drain the plate_id register on completion — the session already
  6012. # consumed it at print-start injection; leaving it would leak into the next
  6013. # print on the same archive_id (rare but possible with reprints) (#1697).
  6014. # Capture the popped value so the completion notification can scope the
  6015. # archive-level (summed-across-plates per #1593) filament + time totals
  6016. # down to the single plate that was actually printed (#1785).
  6017. notify_plate_id: int | None = None
  6018. if archive_id:
  6019. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6020. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6021. try:
  6022. async with async_session() as db:
  6023. from backend.app.api.routes.settings import get_setting
  6024. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6025. if not _spoolman_on or _spoolman_on.lower() != "true":
  6026. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6027. async with async_session() as db:
  6028. usage_results = await usage_on_print_complete(
  6029. printer_id,
  6030. data,
  6031. printer_manager,
  6032. db,
  6033. archive_id=archive_id,
  6034. ams_mapping=stored_ams_mapping,
  6035. )
  6036. if usage_results:
  6037. await ws_manager.broadcast(
  6038. {
  6039. "type": "spool_usage_logged",
  6040. "printer_id": printer_id,
  6041. "usage": usage_results,
  6042. }
  6043. )
  6044. log_timing("Usage tracker")
  6045. except Exception as e:
  6046. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6047. # Drop the print-start context unconditionally — the Spoolman branch above
  6048. # skips the internal tracker entirely, so nothing else would clear what
  6049. # print start captured, and a row surviving its print would be restored
  6050. # onto the next one after a restart.
  6051. try:
  6052. from backend.app.services.usage_tracker import discard_session
  6053. async with async_session() as db:
  6054. await discard_session(db, printer_id)
  6055. except Exception as e:
  6056. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6057. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6058. if archive_id:
  6059. if data.get("status") == "completed":
  6060. try:
  6061. await _report_spoolman_usage(printer_id, archive_id)
  6062. log_timing("Spoolman usage report")
  6063. except Exception as e:
  6064. logger.warning("Spoolman usage reporting failed: %s", e)
  6065. else:
  6066. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6067. try:
  6068. async with async_session() as db:
  6069. await _cleanup_spoolman_tracking(
  6070. printer_id,
  6071. archive_id,
  6072. db,
  6073. last_layer_num=data.get("last_layer_num"),
  6074. last_progress=data.get("last_progress"),
  6075. )
  6076. except Exception as e:
  6077. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6078. log_timing("Filament usage tracking")
  6079. if not archive_id:
  6080. # The printer's own calibration run has no archive by design, so this
  6081. # arrives here every time one finishes. Returning before the no-archive
  6082. # notification is not just noise control: that path attributes an
  6083. # unmatched completion to any queue item this printer finished in the
  6084. # last five minutes, which for a calibration that runs alongside a real
  6085. # print means emailing its owner that their print is done, twice and
  6086. # early. Everything above this point has already run — the plate-clear
  6087. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6088. # notification is skipped.
  6089. if is_internal_printer_job(filename, subtask_name):
  6090. logger.info(
  6091. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6092. filename,
  6093. subtask_name,
  6094. )
  6095. return
  6096. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6097. # Still send print-complete/failed/stopped notifications even without an archive.
  6098. # Try to enrich with queue/library-file data so user-specific emails work too.
  6099. async def _notify_no_archive():
  6100. try:
  6101. async with async_session() as db:
  6102. from backend.app.models.library import LibraryFile
  6103. from backend.app.models.print_queue import PrintQueueItem
  6104. from backend.app.models.printer import Printer
  6105. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6106. printer_obj = result.scalar_one_or_none()
  6107. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  6108. # Try to find the most-recent queue item for this printer so we can
  6109. # recover created_by_id and estimated print time.
  6110. # NOTE: By the time this task runs the queue item status has already
  6111. # been updated to a terminal state (completed/failed/cancelled), so
  6112. # we look for recently-completed items (within the last 5 minutes).
  6113. no_archive_data: dict | None = None
  6114. try:
  6115. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  6116. q_result = await db.execute(
  6117. select(PrintQueueItem)
  6118. .where(PrintQueueItem.printer_id == printer_id)
  6119. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  6120. .where(PrintQueueItem.completed_at >= cutoff)
  6121. .order_by(PrintQueueItem.completed_at.desc())
  6122. .limit(1)
  6123. )
  6124. queue_item = q_result.scalar_one_or_none()
  6125. if queue_item:
  6126. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6127. # Pull estimated time from library file when available
  6128. if queue_item.library_file_id:
  6129. lib_result = await db.execute(
  6130. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6131. )
  6132. lib_file = lib_result.scalar_one_or_none()
  6133. if lib_file and lib_file.print_time_seconds:
  6134. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6135. except Exception as lookup_err:
  6136. logger.debug(
  6137. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6138. )
  6139. # Enrich with usage tracker results (captured in enclosing scope)
  6140. if usage_results:
  6141. if no_archive_data is None:
  6142. no_archive_data = {}
  6143. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6144. if total_from_usage > 0:
  6145. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6146. no_archive_data["usage_results"] = usage_results
  6147. # Try MQTT remaining_time for print duration when no queue/library data
  6148. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  6149. mqtt_remaining = data.get("remaining_time")
  6150. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  6151. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  6152. ps = data.get("status", "completed")
  6153. logger.info(
  6154. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  6155. )
  6156. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6157. await notification_service.on_print_complete(
  6158. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  6159. )
  6160. else:
  6161. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6162. # Send user-specific email if we have a created_by_id
  6163. if no_archive_data and no_archive_data.get("created_by_id"):
  6164. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6165. await _dispatch_user_print_email(
  6166. ps,
  6167. no_archive_data["created_by_id"],
  6168. p_name,
  6169. raw_filename,
  6170. db,
  6171. )
  6172. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  6173. except Exception as e:
  6174. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  6175. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  6176. return
  6177. log_timing("Archive lookup")
  6178. # Update archive status
  6179. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  6180. try:
  6181. async with async_session() as db:
  6182. service = ArchiveService(db)
  6183. status = data.get("status", "completed")
  6184. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  6185. if hms_errors:
  6186. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  6187. failure_reason = derive_failure_reason(status, hms_errors)
  6188. if data.get("_reconciled"):
  6189. # A reconciled completion closes out a stale archive at
  6190. # reconnect — it is not a user action, so don't mislabel it
  6191. # "userCancelled". It shares the stale-cleanup path's key
  6192. # (issue #2974) and records that the real end time is unknown,
  6193. # which is also why its logged duration is 0 (#2592).
  6194. failure_reason = "noStatusUpdate"
  6195. if failure_reason:
  6196. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  6197. elif status == "failed" and hms_errors:
  6198. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  6199. await service.update_archive_status(
  6200. archive_id,
  6201. status=status,
  6202. completed_at=(
  6203. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  6204. ),
  6205. failure_reason=failure_reason,
  6206. )
  6207. logger.info(
  6208. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  6209. )
  6210. await ws_manager.send_archive_updated(
  6211. {
  6212. "id": archive_id,
  6213. "status": status,
  6214. }
  6215. )
  6216. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  6217. # MQTT relay - publish archive updated
  6218. try:
  6219. await mqtt_relay.on_archive_updated(
  6220. archive_id=archive_id,
  6221. print_name=filename or subtask_name,
  6222. status=status,
  6223. )
  6224. except Exception:
  6225. pass # Don't fail if MQTT fails
  6226. except Exception as e:
  6227. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  6228. # Continue with other operations even if archive update fails
  6229. log_timing("Archive status update")
  6230. # Apply finance wallet charge or release reservations once. For all partial
  6231. # terminal states (failed, aborted at the printer display, or cancelled via
  6232. # Bambuddy) use this run's measured spool delta, falling back to the last
  6233. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  6234. # estimate and therefore cannot represent an interrupted run.
  6235. try:
  6236. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  6237. async with async_session() as db:
  6238. from backend.app.models.archive import PrintArchive
  6239. from backend.app.services.finance_billing import apply_print_charge_for_archive
  6240. archive = await db.get(PrintArchive, archive_id)
  6241. if archive and billing_run_id is None:
  6242. billing_run_id = getattr(archive, "billing_run_id", None)
  6243. if archive and archive.created_by_id is None and _print_user_info:
  6244. archive.created_by_id = _print_user_info.get("user_id")
  6245. await db.flush()
  6246. run_status = data.get("status", "completed")
  6247. last_progress = data.get("last_progress")
  6248. if last_progress is None:
  6249. last_progress = data.get("progress")
  6250. actual_run_grams = _compute_run_filament_grams(
  6251. run_status,
  6252. billing_planned_grams,
  6253. last_progress,
  6254. usage_results,
  6255. )
  6256. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  6257. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  6258. charged = await apply_print_charge_for_archive(
  6259. db,
  6260. archive_id,
  6261. charged_user_id=billing_user_id,
  6262. cost_center_id=(
  6263. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  6264. ),
  6265. print_queue_id=queue_item_id,
  6266. print_run_id=billing_run_id,
  6267. base_cost_override=billing_base_cost,
  6268. filament_usage=filament_usage,
  6269. )
  6270. await db.commit()
  6271. if charged:
  6272. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  6273. except Exception as e:
  6274. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  6275. printer_info = printer_manager.get_printer(printer_id)
  6276. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  6277. billing_filename = filename or subtask_name or "Unknown"
  6278. billing_error = str(e)
  6279. try:
  6280. await ws_manager.broadcast(
  6281. {
  6282. "type": "billing_charge_failed",
  6283. "printer_id": printer_id,
  6284. "printer_name": billing_printer_name,
  6285. "filename": billing_filename,
  6286. "archive_id": archive_id,
  6287. }
  6288. )
  6289. except Exception as notification_error:
  6290. logger.error(
  6291. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  6292. archive_id,
  6293. notification_error,
  6294. )
  6295. async def _notify_billing_charge_failed() -> None:
  6296. try:
  6297. async with async_session() as notification_db:
  6298. await notification_service.on_billing_charge_failed(
  6299. printer_id,
  6300. billing_printer_name,
  6301. billing_filename,
  6302. archive_id,
  6303. billing_error,
  6304. notification_db,
  6305. )
  6306. except Exception as provider_error:
  6307. logger.error(
  6308. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  6309. archive_id,
  6310. provider_error,
  6311. exc_info=True,
  6312. )
  6313. spawn_background_task(
  6314. _notify_billing_charge_failed(),
  6315. name=f"billing-charge-failed-{archive_id}",
  6316. )
  6317. log_timing("Finance charge update")
  6318. # Write independent print log entry (separate table, never touches archives)
  6319. try:
  6320. async with async_session() as db:
  6321. from backend.app.models.archive import PrintArchive
  6322. from backend.app.services.print_log import write_log_entry
  6323. archive = await db.get(PrintArchive, archive_id)
  6324. if archive:
  6325. # Back-fill created_by_id on reprint (#730): reprint reuses the
  6326. # source archive row rather than creating a new one, so an
  6327. # archive that was auto-created from a printer-initiated
  6328. # print (created_by_id=NULL) would otherwise stay unattributed
  6329. # forever. When we have a print-session user AND the archive
  6330. # has no attribution yet, credit the current user. Never
  6331. # overwrite an existing attribution — the original uploader
  6332. # keeps ownership.
  6333. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  6334. if archive.created_by_id is None and _print_user_id is not None:
  6335. archive.created_by_id = _print_user_id
  6336. p_info = printer_manager.get_printer(printer_id)
  6337. # Per-run actuals — written to PrintLogEntry so stats reflect
  6338. # what THIS print actually used, not the source archive's
  6339. # first-run values (#1378). Helper handles the partial-print
  6340. # math (failed / cancelled / stopped get scaled to progress
  6341. # or to tracked spool deltas).
  6342. _run_status = data.get("status", "completed")
  6343. # #2614: scope the per-run estimate to the printed plate. For a
  6344. # multi-plate 3MF dispatched one plate at a time, the archive's
  6345. # filament/cost are the whole-file totals; the PrintLogEntry must
  6346. # reflect only this plate. No effect on single-plate archives (the
  6347. # plate estimate equals the whole-file value) or on the tracker
  6348. # path (measured spool deltas win in _compute_run_filament_grams).
  6349. _est_full_path = (
  6350. app_settings.base_dir / archive.file_path if archive.file_path else None
  6351. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6352. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  6353. _run_grams = _compute_run_filament_grams(
  6354. _run_status,
  6355. _est_grams,
  6356. data.get("last_progress", data.get("progress")),
  6357. usage_results,
  6358. )
  6359. # Per-run cost — prefer usage_results sum. For partial prints
  6360. # we deliberately skip the topup-to-estimate logic in
  6361. # usage_tracker (which assumes the print completed); the raw
  6362. # tracked-spool sum is closer to what THIS run actually cost.
  6363. _run_cost: float | None = None
  6364. if usage_results:
  6365. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  6366. if _run_cost is None and _run_status == "completed":
  6367. _run_cost = _est_cost
  6368. await write_log_entry(
  6369. db,
  6370. archive_id=archive.id,
  6371. # Captured by _update_queue_status above; None for
  6372. # printer-initiated prints with no queue row. Batch
  6373. # cost/energy roll-up joins on it (#342).
  6374. queue_item_id=queue_item_id,
  6375. status=_run_status,
  6376. print_name=archive.print_name,
  6377. printer_name=p_info.name if p_info else None,
  6378. printer_id=printer_id,
  6379. started_at=archive.started_at,
  6380. completed_at=archive.completed_at,
  6381. filament_type=archive.filament_type,
  6382. filament_color=archive.filament_color,
  6383. filament_used_grams=_run_grams,
  6384. cost=_run_cost,
  6385. failure_reason=archive.failure_reason,
  6386. thumbnail_path=archive.thumbnail_path,
  6387. created_by_id=archive.created_by_id,
  6388. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  6389. # Reconciled completions have an unknown real end time —
  6390. # log 0 duration instead of the whole disconnect gap (#2592).
  6391. reconciled=bool(data.get("_reconciled")),
  6392. )
  6393. await db.commit()
  6394. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  6395. except Exception as e:
  6396. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  6397. log_timing("Print log entry")
  6398. # Run slow operations as background tasks to avoid blocking the event loop
  6399. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  6400. async def _background_energy_calculation():
  6401. """Calculate and save energy usage in background.
  6402. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  6403. backend restart no longer loses per-print energy data).
  6404. """
  6405. try:
  6406. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  6407. async with async_session() as db:
  6408. from backend.app.models.archive import PrintArchive
  6409. archive = await db.get(PrintArchive, archive_id)
  6410. if archive is None:
  6411. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  6412. return
  6413. starting_kwh = archive.energy_start_kwh
  6414. if starting_kwh is None:
  6415. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  6416. return
  6417. candidates = await energy_plug_candidates(db, printer_id)
  6418. if not candidates:
  6419. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  6420. return
  6421. # Same ordering as the start reading, so the delta below is
  6422. # against the counter that produced `starting_kwh` (#2859).
  6423. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  6424. if selected is None:
  6425. logger.warning(
  6426. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  6427. printer_id,
  6428. ", ".join(plug.name for plug in candidates),
  6429. )
  6430. return
  6431. plug, energy = selected
  6432. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  6433. energy_used = round(energy["total"] - starting_kwh, 4)
  6434. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  6435. if energy_used < 0:
  6436. logger.warning(
  6437. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  6438. archive_id,
  6439. starting_kwh,
  6440. energy["total"],
  6441. )
  6442. return
  6443. from backend.app.api.routes.settings import get_setting
  6444. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  6445. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  6446. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  6447. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  6448. # reprint doesn't visually clobber the source archive's energy data
  6449. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  6450. from sqlalchemy import func
  6451. from backend.app.models.print_log import PrintLogEntry
  6452. existing_runs = await db.scalar(
  6453. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  6454. )
  6455. if (existing_runs or 0) <= 1:
  6456. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  6457. # we just wrote for THIS print. Either way it's the first run.
  6458. archive.energy_kwh = energy_used
  6459. archive.energy_cost = energy_cost_value
  6460. # Backfill the latest PrintLogEntry for this archive with energy
  6461. # (write_log_entry above ran before this background task completed,
  6462. # so energy fields are still NULL on that row).
  6463. latest_run = await db.execute(
  6464. select(PrintLogEntry)
  6465. .where(PrintLogEntry.archive_id == archive_id)
  6466. .order_by(PrintLogEntry.id.desc())
  6467. .limit(1)
  6468. )
  6469. run_row = latest_run.scalar_one_or_none()
  6470. if run_row is not None:
  6471. run_row.energy_kwh = energy_used
  6472. run_row.energy_cost = energy_cost_value
  6473. await db.commit()
  6474. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  6475. except Exception as e:
  6476. logger.warning("[ENERGY-BG] Failed: %s", e)
  6477. async def _background_finish_photo() -> str | None:
  6478. """Capture finish photo in background. Returns photo filename if captured."""
  6479. # #2547: set once this function has raised the plate itself (the
  6480. # timelapse path, where the moment producer returned without doing it).
  6481. # Declared out here so the `finally` can lower it again no matter where
  6482. # the capture below fails.
  6483. plate_restored_z: float | None = None
  6484. try:
  6485. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  6486. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  6487. # Read phase: settings + printer + archive in a short session, released
  6488. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  6489. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  6490. # tens of seconds; holding this session across it pinned one pooled
  6491. # connection idle-in-transaction per finishing print (issue #2572).
  6492. async with async_session() as db:
  6493. from backend.app.api.routes.settings import get_setting
  6494. from backend.app.models.archive import PrintArchive
  6495. from backend.app.models.printer import Printer
  6496. capture_enabled = await get_setting(db, "capture_finish_photo")
  6497. if capture_enabled is not None and capture_enabled.lower() != "true":
  6498. return None
  6499. if not archive_id:
  6500. return None
  6501. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  6502. archive = (
  6503. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6504. ).scalar_one_or_none()
  6505. if not printer or not archive:
  6506. return None
  6507. import uuid
  6508. from datetime import datetime
  6509. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  6510. if not archive.file_path:
  6511. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  6512. archive_dir = resolve_archive_dir(archive)
  6513. photo_filename = None
  6514. # Prefer the timelapse last-frame source when a timelapse was
  6515. # recording — it captures the moment after the toolhead parks
  6516. # but before the bed drops, which the live-camera grab below
  6517. # would miss (#1397). Skipped for external cameras (those have
  6518. # their own framing and don't see a Bambu timelapse). Only
  6519. # runs when the USER explicitly enabled timelapse for this
  6520. # print — #1721 removed Bambuddy's force-on at dispatch
  6521. # because it caused per-layer nozzle parking on Smooth-mode
  6522. # slicer profiles.
  6523. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  6524. printer.external_camera_enabled and printer.external_camera_url
  6525. )
  6526. timelapse_still_pending = False
  6527. if prefer_timelapse_source:
  6528. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  6529. archive_id=archive_id,
  6530. archive_dir=archive_dir,
  6531. rotation=getattr(printer, "camera_rotation", 0),
  6532. )
  6533. # #1721: replacement framing path — on_finish_photo_moment
  6534. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  6535. # parked, bed not yet dropped) and cached the JPEG bytes in
  6536. # _stage22_finish_frames. Consume them now so the saved photo
  6537. # has the better framing instead of the post-bed-drop angle
  6538. # the live-camera fallback below would give.
  6539. if not photo_filename:
  6540. # #1790: on the FINISH-state fallback path the producer
  6541. # task is dispatched back-to-back with this consumer, so
  6542. # a bare pop would race past with an empty result and
  6543. # the RTSP fallback below would collide with the
  6544. # producer's still-in-flight grab (single-client RTSP
  6545. # on Bambu printers). Wait for the producer to finish
  6546. # or give up before touching the cache.
  6547. #
  6548. # #2547: 20s was enough when the producer only ever grabbed a
  6549. # frame. It now also raises the plate first, which costs the
  6550. # settle window before the grab even starts — so the budget has
  6551. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  6552. # under the notification's own photo wait below.
  6553. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  6554. if in_flight is not None:
  6555. try:
  6556. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  6557. except asyncio.TimeoutError:
  6558. logger.warning(
  6559. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  6560. printer_id,
  6561. )
  6562. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  6563. if cached_frame:
  6564. # Already rotated by the producer (#2708) — rotating again
  6565. # here would undo the fix on the banked-frame path, whose
  6566. # bytes reach the cache having been rotated once already.
  6567. photos_dir = archive_dir / "photos"
  6568. photos_dir.mkdir(parents=True, exist_ok=True)
  6569. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6570. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6571. photo_path = photos_dir / photo_filename
  6572. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  6573. logger.info(
  6574. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  6575. photo_filename,
  6576. len(cached_frame),
  6577. )
  6578. # #2547: the timelapse path reaches the live grab below whenever the
  6579. # video hasn't landed in time — the documented usual outcome on
  6580. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  6581. # returned early for those prints without raising the plate, so
  6582. # without this the photo that actually ships in the notification is
  6583. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  6584. # asked us to fix. The archive still gets the better video frame
  6585. # later; this is about the image the user is sent.
  6586. #
  6587. # Gated on `timelapse_was_active` precisely because that is the
  6588. # condition under which the producer skipped. On every other path it
  6589. # has already raised and lowered the plate, and repeating that here
  6590. # would be a second pointless round trip.
  6591. if (
  6592. not photo_filename
  6593. and data.get("timelapse_was_active")
  6594. and not print_dispatch_context.end_gcode_injected(printer_id)
  6595. ):
  6596. try:
  6597. async with async_session() as db:
  6598. from backend.app.api.routes.settings import get_setting
  6599. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6600. if restore_setting is None or restore_setting.lower() == "true":
  6601. max_z = await _max_z_for_current_print(printer_id, data, logger)
  6602. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  6603. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  6604. plate_restored_z = max_z
  6605. except Exception as e:
  6606. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  6607. # Fallback chain: external camera → buffered live frame →
  6608. # fresh RTSP capture. Only runs if the timelapse path above
  6609. # didn't already produce a photo.
  6610. if not photo_filename:
  6611. if printer.external_camera_enabled and printer.external_camera_url:
  6612. logger.info("[PHOTO-BG] Using external camera")
  6613. from backend.app.api.routes.camera import live_frame_for_capture
  6614. from backend.app.services.external_camera import capture_frame
  6615. # #2707: the second half of the finish-photo failure — the
  6616. # pre-capture and this fallback both collided with the live
  6617. # view. None here continues down the fallback chain.
  6618. defer, buffered = live_frame_for_capture(printer_id)
  6619. if defer:
  6620. frame_data = buffered
  6621. else:
  6622. frame_data = await capture_frame(
  6623. printer.external_camera_url,
  6624. printer.external_camera_type or "mjpeg",
  6625. snapshot_url=printer.external_camera_snapshot_url,
  6626. )
  6627. if frame_data:
  6628. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  6629. photos_dir = archive_dir / "photos"
  6630. photos_dir.mkdir(parents=True, exist_ok=True)
  6631. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6632. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6633. photo_path = photos_dir / photo_filename
  6634. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  6635. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  6636. else:
  6637. # Check if camera stream is active - use buffered frame to avoid freeze
  6638. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  6639. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  6640. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  6641. buffered_frame = get_buffered_frame(printer_id)
  6642. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  6643. # Use frame from active stream
  6644. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  6645. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  6646. photos_dir = archive_dir / "photos"
  6647. photos_dir.mkdir(parents=True, exist_ok=True)
  6648. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6649. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6650. photo_path = photos_dir / photo_filename
  6651. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  6652. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  6653. else:
  6654. # No active stream - capture new frame
  6655. from backend.app.services.camera import capture_finish_photo
  6656. photo_filename = await capture_finish_photo(
  6657. printer_id=printer_id,
  6658. ip_address=printer.ip_address,
  6659. access_code=printer.access_code,
  6660. model=printer.model,
  6661. archive_dir=archive_dir,
  6662. rotation=getattr(printer, "camera_rotation", 0),
  6663. )
  6664. # Write phase: attach the photo in a fresh short-lived session.
  6665. if photo_filename:
  6666. async with async_session() as db:
  6667. from backend.app.models.archive import PrintArchive
  6668. arch = await db.get(PrintArchive, archive_id)
  6669. if arch is not None:
  6670. photos = arch.photos or []
  6671. photos.append(photo_filename)
  6672. arch.photos = photos
  6673. await db.commit()
  6674. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  6675. # The short wait above is bounded so a slow printer can't hold up
  6676. # the print-complete notification, which is what the caller is
  6677. # blocking on. When it ran out with the video still on its way,
  6678. # keep waiting off to the side and add the better frame to the
  6679. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  6680. # users, whose videos routinely take minutes to transfer, never get
  6681. # the pre-bed-drop framing this path exists to provide.
  6682. #
  6683. # Spawned here rather than at the point the wait gave up: both this
  6684. # function and the upgrade do a read-modify-write on `photos`, and
  6685. # the live-camera fallback above can take tens of seconds. Starting
  6686. # the upgrade before that write means the two can interleave and one
  6687. # silently drops the other's entry, leaving a JPEG on disk that the
  6688. # gallery never lists.
  6689. if timelapse_still_pending:
  6690. spawn_background_task(
  6691. _upgrade_finish_photo_from_timelapse(
  6692. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  6693. ),
  6694. name=f"finish-photo-upgrade-{archive_id}",
  6695. )
  6696. return photo_filename
  6697. except Exception as e:
  6698. logger.warning("[PHOTO-BG] Failed: %s", e)
  6699. return None
  6700. finally:
  6701. # #2547: we raised the plate, so we owe the move back down — even if
  6702. # the capture in between threw. Otherwise the user finds the print
  6703. # pinned under the nozzle.
  6704. if plate_restored_z is not None:
  6705. try:
  6706. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  6707. except Exception as e:
  6708. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6709. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  6710. # Photo capture task - result will be used by notifications
  6711. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  6712. log_timing("Background tasks scheduled (energy, photo)")
  6713. # Also run smart plug, notifications, and maintenance as background tasks
  6714. print_status = data.get("status", "completed")
  6715. async def _background_smart_plug():
  6716. """Handle smart plug automation in background."""
  6717. try:
  6718. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  6719. async with async_session() as db:
  6720. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  6721. logger.info("[AUTO-OFF-BG] Completed")
  6722. except Exception as e:
  6723. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  6724. async def _background_notifications(finish_photo_filename: str | None = None):
  6725. """Send print complete notifications in background."""
  6726. try:
  6727. logger.info(
  6728. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  6729. )
  6730. async with async_session() as db:
  6731. from backend.app.models.archive import PrintArchive
  6732. from backend.app.models.printer import Printer
  6733. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6734. printer = result.scalar_one_or_none()
  6735. printer_name = printer.name if printer else f"Printer {printer_id}"
  6736. archive_data = None
  6737. if archive_id:
  6738. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6739. archive = archive_result.scalar_one_or_none()
  6740. if archive:
  6741. # Actual elapsed time from started_at/completed_at when both are
  6742. # populated (every terminal status sets completed_at after #1198).
  6743. # Falls back to None so the notification path can decide whether to
  6744. # render the slicer estimate as a last resort.
  6745. actual_time_seconds = None
  6746. if archive.started_at and archive.completed_at:
  6747. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  6748. if elapsed > 0:
  6749. actual_time_seconds = int(elapsed)
  6750. archive_data = {
  6751. "print_time_seconds": archive.print_time_seconds,
  6752. "actual_time_seconds": actual_time_seconds,
  6753. "actual_filament_grams": archive.filament_used_grams,
  6754. "failure_reason": archive.failure_reason,
  6755. "created_by_id": archive.created_by_id,
  6756. }
  6757. # Scale filament usage for partial prints
  6758. if print_status != "completed" and archive.filament_used_grams:
  6759. progress = data.get("progress") or 0
  6760. scale = _partial_progress_scale(progress)
  6761. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  6762. archive_data["progress"] = progress
  6763. # Pass per-slot data from archive.extra_data
  6764. if archive.extra_data and archive.extra_data.get("filament_slots"):
  6765. slots = archive.extra_data["filament_slots"]
  6766. if print_status != "completed":
  6767. scale = _partial_progress_scale(data.get("progress"))
  6768. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  6769. archive_data["filament_slots"] = slots
  6770. # Scope project-summed totals down to the plate that was
  6771. # actually printed — see _scope_notification_archive_data_to_plate
  6772. # for the why (#1785).
  6773. archive_data = _scope_notification_archive_data_to_plate(
  6774. archive_data,
  6775. archive.file_path,
  6776. notify_plate_id,
  6777. print_status,
  6778. data.get("progress"),
  6779. app_settings.base_dir,
  6780. )
  6781. # Enrich filament_grams from usage_results when archive has no 3MF data
  6782. if not archive_data.get("actual_filament_grams") and usage_results:
  6783. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6784. if total_from_usage > 0:
  6785. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6786. # Pass usage tracker results for AMS slot info in notifications
  6787. if usage_results:
  6788. archive_data["usage_results"] = usage_results
  6789. # Add finish photo URL and image bytes if available
  6790. if finish_photo_filename:
  6791. from backend.app.api.routes.settings import get_setting
  6792. external_url = await get_setting(db, "external_url")
  6793. if external_url:
  6794. external_url = external_url.rstrip("/")
  6795. archive_data["finish_photo_url"] = (
  6796. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6797. )
  6798. else:
  6799. # Fallback to relative URL (won't work for external services)
  6800. archive_data["finish_photo_url"] = (
  6801. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6802. )
  6803. # Read finish photo bytes for image attachment (e.g. Pushover)
  6804. try:
  6805. from backend.app.utils.archive_paths import find_archive_photo
  6806. photo_path = find_archive_photo(archive, finish_photo_filename)
  6807. if photo_path is not None:
  6808. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  6809. if len(photo_bytes) <= 2_500_000:
  6810. archive_data["image_data"] = photo_bytes
  6811. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  6812. else:
  6813. logger.warning(
  6814. f"[NOTIFY-BG] Finish photo too large for attachment: "
  6815. f"{len(photo_bytes)} bytes"
  6816. )
  6817. except Exception as e:
  6818. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  6819. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6820. await notification_service.on_print_complete(
  6821. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  6822. )
  6823. else:
  6824. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6825. # Send user-specific email notification
  6826. if archive_data:
  6827. created_by_id = archive_data.get("created_by_id")
  6828. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6829. await _dispatch_user_print_email(
  6830. print_status,
  6831. created_by_id,
  6832. printer_name,
  6833. raw_filename,
  6834. db,
  6835. )
  6836. logger.info("[NOTIFY-BG] Completed")
  6837. except Exception as e:
  6838. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  6839. async def _background_maintenance_check():
  6840. """Check for maintenance due in background."""
  6841. if print_status != "completed":
  6842. return
  6843. try:
  6844. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  6845. async with async_session() as db:
  6846. from backend.app.models.printer import Printer
  6847. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6848. printer = result.scalar_one_or_none()
  6849. printer_name = printer.name if printer else f"Printer {printer_id}"
  6850. await ensure_default_types(db)
  6851. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  6852. items_needing_attention = [
  6853. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  6854. for item in overview.maintenance_items
  6855. if item.enabled and (item.is_due or item.is_warning)
  6856. ]
  6857. if items_needing_attention:
  6858. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  6859. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  6860. # MQTT relay - publish maintenance alerts
  6861. for item in items_needing_attention:
  6862. try:
  6863. await mqtt_relay.on_maintenance_alert(
  6864. printer_id=printer_id,
  6865. printer_name=printer_name,
  6866. maintenance_type=item["name"],
  6867. current_value=0, # Not easily available here
  6868. threshold=0, # Not easily available here
  6869. )
  6870. except Exception:
  6871. pass # Don't fail if MQTT fails
  6872. else:
  6873. logger.info("[MAINT-BG] Completed (no items need attention)")
  6874. except Exception as e:
  6875. logger.warning("[MAINT-BG] Failed: %s", e)
  6876. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  6877. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  6878. # Notification task waits for photo capture to complete first (with timeout).
  6879. # When a timelapse was recording, photo sourcing polls the per-print
  6880. # timelapse for up to 60s (#1397) — extend the budget so the notification
  6881. # carries the correct bed-up photo instead of falling through to the
  6882. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  6883. #
  6884. # #2547: both budgets now have to cover a plate restore as well.
  6885. #
  6886. # Without timelapse, the wait is on the moment producer, which raises the
  6887. # plate before its grab — so this has to outlast that producer's own budget.
  6888. #
  6889. # With timelapse, the capture polls up to
  6890. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  6891. # falls back to a live grab, which is the case that raises the plate. At the
  6892. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  6893. # restore would have moved the plate for a photo nobody waited for.
  6894. photo_wait_timeout = (
  6895. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  6896. if data.get("timelapse_was_active")
  6897. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  6898. )
  6899. async def _photo_then_notify():
  6900. """Wait for photo capture, then send notification with photo URL."""
  6901. finish_photo = None
  6902. try:
  6903. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  6904. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  6905. except TimeoutError:
  6906. logger.warning(
  6907. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  6908. photo_wait_timeout,
  6909. )
  6910. except Exception as e:
  6911. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  6912. try:
  6913. await _background_notifications(finish_photo)
  6914. except Exception as e:
  6915. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  6916. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  6917. # Stitch external camera layer timelapse if session was active
  6918. print_status = data.get("status", "completed")
  6919. async def _background_layer_timelapse():
  6920. """Stitch layer timelapse and attach to archive."""
  6921. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  6922. try:
  6923. if print_status == "completed":
  6924. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  6925. timelapse_path = await tl_complete(printer_id)
  6926. if timelapse_path and archive_id:
  6927. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6928. async with async_session() as db:
  6929. service = ArchiveService(db)
  6930. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6931. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  6932. # Clean up the temp file
  6933. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6934. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6935. elif timelapse_path:
  6936. # Timelapse created but no archive - just clean up
  6937. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6938. else:
  6939. # Print failed or cancelled - cancel timelapse session
  6940. cancel_session(printer_id)
  6941. logger.info(
  6942. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  6943. )
  6944. except Exception as e:
  6945. logger.warning("[LAYER-TL] Failed: %s", e)
  6946. # Try to cancel session on error
  6947. try:
  6948. cancel_session(printer_id)
  6949. except Exception:
  6950. pass # Best-effort timelapse session cancellation on error
  6951. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  6952. log_timing("All background tasks scheduled")
  6953. # Auto-scan for timelapse if recording was active during the print
  6954. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  6955. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  6956. # Schedule timelapse scan as background task with retries
  6957. # The printer needs time to encode the video after print completion
  6958. baseline = _timelapse_baselines.pop(printer_id, None)
  6959. spawn_background_task(
  6960. _scan_for_timelapse_with_retries(archive_id, baseline),
  6961. name=f"scan-timelapse-{archive_id}",
  6962. )
  6963. log_timing("Timelapse scan scheduled")
  6964. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  6965. # AMS sensor history recording
  6966. _ams_history_task: asyncio.Task | None = None
  6967. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  6968. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  6969. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  6970. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  6971. _ams_alarm_cooldown: dict[str, datetime] = {}
  6972. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  6973. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  6974. """Temperature at which the AMS alarm fires, falling back to the display band.
  6975. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  6976. when a notification was sent as well, which is why a room above it made the
  6977. alarm fire once an hour for as long as the weather lasted -- and the only way
  6978. to stop that was to raise the display band and lose the colour that says the
  6979. unit is warm (#2905).
  6980. Unset resolves to the fair threshold, so an install that never sets one is
  6981. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  6982. so that arrives here as a string and is handled by the same branch as any
  6983. other unparseable value -- there is no separate sentinel to keep in sync.
  6984. A non-positive value is refused rather than honoured: zero would alarm
  6985. permanently, and it is far more likely to be a cleared field than a
  6986. deliberate choice.
  6987. """
  6988. if raw_alarm_value is None:
  6989. return fair_threshold
  6990. try:
  6991. value = float(raw_alarm_value)
  6992. except (TypeError, ValueError):
  6993. return fair_threshold
  6994. if not math.isfinite(value) or value <= 0:
  6995. return fair_threshold
  6996. return value
  6997. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  6998. # through a cycle and the cool-down after it (#1802). Stored in the settings
  6999. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7000. # partway through a cool-down would otherwise resume alarming about heat the
  7001. # user asked for — the same internal-timestamp-row pattern as
  7002. # support.py's debug_logging_enabled_at.
  7003. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7004. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7005. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7006. # matters when it never does.
  7007. AMS_DRYING_GRACE_MINUTES = 120
  7008. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7009. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7010. Anything older than the grace cap would expire on its next visit anyway, so
  7011. discarding it here costs nothing and stops rows for deleted printers from
  7012. accumulating.
  7013. Stamps ahead of now get two defences, because a box whose clock jumps
  7014. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7015. ones are discarded outright, and the rest are clamped to now. Without the
  7016. clamp the cap would measure from a moment that has not happened yet and hold
  7017. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7018. after a clock jump is a far better failure than an alarm silently disabled
  7019. for hours.
  7020. """
  7021. from backend.app.models.settings import Settings
  7022. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7023. setting = result.scalar_one_or_none()
  7024. if not setting or not setting.value:
  7025. return {}
  7026. try:
  7027. raw = json.loads(setting.value)
  7028. except (ValueError, TypeError):
  7029. return {} # Corrupted row → no latch, alarms behave as they did before
  7030. if not isinstance(raw, dict):
  7031. return {}
  7032. now = datetime.now(timezone.utc)
  7033. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7034. latch: dict[str, datetime] = {}
  7035. for key, value in raw.items():
  7036. try:
  7037. stamp = datetime.fromisoformat(str(value))
  7038. except (ValueError, TypeError):
  7039. continue
  7040. if stamp.tzinfo is None:
  7041. stamp = stamp.replace(tzinfo=timezone.utc)
  7042. if not (now - window <= stamp <= now + window):
  7043. continue
  7044. # Nothing may sit in the future: suppression is measured as now minus
  7045. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7046. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7047. latch[str(key)] = min(stamp, now)
  7048. return latch
  7049. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7050. """Persist the latch, writing only when it actually changed.
  7051. Adds the session change but does not commit — the caller's own commit
  7052. carries it, so the latch lands in the same transaction as the sensor rows
  7053. that produced it.
  7054. """
  7055. from backend.app.models.settings import Settings
  7056. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7057. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7058. setting = result.scalar_one_or_none()
  7059. if setting is None:
  7060. # Don't create the row on installs that never dry anything.
  7061. if payload != "{}":
  7062. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7063. elif setting.value != payload:
  7064. setting.value = payload
  7065. def _ams_has_filament(ams_data: dict) -> bool:
  7066. """True if this AMS unit has at least one tray slot holding filament.
  7067. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7068. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7069. still report sensor readings, but those readings are ambient and not
  7070. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7071. humidity/temperature alarms on this check so empty units don't generate
  7072. hourly noise. Sensor history still records regardless so the UI charts
  7073. stay continuous.
  7074. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7075. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7076. """
  7077. bits = ams_data.get("tray_exist_bits")
  7078. if isinstance(bits, str) and bits.strip():
  7079. try:
  7080. return int(bits, 16) > 0
  7081. except ValueError:
  7082. pass
  7083. trays = ams_data.get("tray")
  7084. if isinstance(trays, list):
  7085. return any(
  7086. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  7087. )
  7088. return False
  7089. async def record_ams_history():
  7090. """Background task to record AMS humidity and temperature data."""
  7091. logger = logging.getLogger(__name__)
  7092. # Wait a short time for MQTT connections to establish on startup
  7093. await asyncio.sleep(10)
  7094. while True:
  7095. try:
  7096. from backend.app.models.ams_history import AMSSensorHistory
  7097. from backend.app.models.printer import Printer
  7098. from backend.app.models.settings import Settings
  7099. async with async_session() as db:
  7100. # Get all active printers
  7101. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7102. printers = result.scalars().all()
  7103. # Get alarm thresholds from settings
  7104. humidity_threshold = 60.0 # Default: fair threshold
  7105. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  7106. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  7107. setting = result.scalar_one_or_none()
  7108. if setting:
  7109. try:
  7110. humidity_threshold = float(setting.value)
  7111. except (ValueError, TypeError):
  7112. pass # Keep default threshold if stored value is invalid
  7113. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  7114. setting = result.scalar_one_or_none()
  7115. if setting:
  7116. try:
  7117. temp_fair_threshold = float(setting.value)
  7118. except (ValueError, TypeError):
  7119. pass # Keep default threshold if stored value is invalid
  7120. # The alarm gets its own threshold, seeded from the resolved fair
  7121. # value so an install that has never set one behaves exactly as
  7122. # it did before (#2905). ams_temp_fair decides when the card turns
  7123. # amber; 35 C is a reasonable place to change a colour and not a
  7124. # reasonable place to page someone. A room above it makes the
  7125. # alarm fire once an hour for as long as the weather lasts, and
  7126. # the only way to stop it was to raise the display band and lose
  7127. # the colour that says the unit is warm.
  7128. #
  7129. # An unset value is stored as the literal "None", which the except
  7130. # below swallows the same way it swallows garbage -- so the
  7131. # fallback costs nothing and needs no sentinel of its own.
  7132. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  7133. setting = result.scalar_one_or_none()
  7134. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  7135. temp_fair_threshold, setting.value if setting else None
  7136. )
  7137. # Per-filament humidity threshold overrides (#1605) — resolved
  7138. # per-AMS below from the loaded tray types. Reuses the same
  7139. # resolver as the auto-drying scheduler so behavior stays in
  7140. # lockstep across both consumers.
  7141. from backend.app.services.print_scheduler import PrintScheduler
  7142. per_type_humidity_thresholds: dict[str, int] = {}
  7143. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  7144. setting = result.scalar_one_or_none()
  7145. if setting and setting.value:
  7146. try:
  7147. raw = json.loads(setting.value)
  7148. if isinstance(raw, dict):
  7149. for k, v in raw.items():
  7150. try:
  7151. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  7152. v
  7153. )
  7154. except (TypeError, ValueError):
  7155. continue
  7156. except (ValueError, TypeError):
  7157. pass # Invalid JSON → no overrides, fall through to global threshold
  7158. # Per-AMS drying latch (#1802), loaded once per pass and written
  7159. # back below only if a unit changed it.
  7160. drying_latch = await _load_ams_drying_latch(db)
  7161. drying_latch_before = dict(drying_latch)
  7162. recorded_count = 0
  7163. for printer in printers:
  7164. # Get current state from printer manager
  7165. state = printer_manager.get_status(printer.id)
  7166. if not state or not state.connected or not state.raw_data:
  7167. continue # Skip disconnected printers - don't use stale data
  7168. raw_data = state.raw_data
  7169. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  7170. continue
  7171. # Record data for each AMS unit
  7172. for ams_data in raw_data["ams"]:
  7173. ams_id = int(ams_data.get("id", 0))
  7174. # Get humidity (prefer humidity_raw)
  7175. humidity_raw = ams_data.get("humidity_raw")
  7176. humidity_idx = ams_data.get("humidity")
  7177. humidity = None
  7178. if humidity_raw is not None:
  7179. try:
  7180. humidity = float(humidity_raw)
  7181. except (ValueError, TypeError):
  7182. pass # Skip unparseable humidity; will try fallback
  7183. if humidity is None and humidity_idx is not None:
  7184. try:
  7185. humidity = float(humidity_idx)
  7186. except (ValueError, TypeError):
  7187. pass # Skip unparseable humidity index value
  7188. # Get temperature
  7189. temperature = None
  7190. temp_str = ams_data.get("temp")
  7191. if temp_str is not None:
  7192. try:
  7193. temperature = float(temp_str)
  7194. except (ValueError, TypeError):
  7195. pass # Skip unparseable temperature value
  7196. # Skip if no data
  7197. if humidity is None and temperature is None:
  7198. continue
  7199. # Record the data point
  7200. history = AMSSensorHistory(
  7201. printer_id=printer.id,
  7202. ams_id=ams_id,
  7203. humidity=humidity,
  7204. humidity_raw=float(humidity_raw) if humidity_raw else None,
  7205. temperature=temperature,
  7206. )
  7207. db.add(history)
  7208. recorded_count += 1
  7209. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  7210. is_ams_ht = ams_id >= 128
  7211. if is_ams_ht:
  7212. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  7213. else:
  7214. ams_label = f"AMS-{chr(65 + ams_id)}"
  7215. # Skip alarm dispatch for empty AMS units — humidity /
  7216. # temperature readings are ambient with no filament to
  7217. # protect, and the hourly notification just becomes
  7218. # noise. Sensor history was already recorded above so
  7219. # the UI charts stay continuous (#1619). Per-AMS check
  7220. # so a multi-AMS setup with one loaded + one empty
  7221. # still alarms on the loaded unit.
  7222. if not _ams_has_filament(ams_data):
  7223. continue
  7224. # Resolve per-filament humidity threshold for this AMS
  7225. # unit (#1605). Falls back to the global ams_humidity_fair
  7226. # when no per-type overrides are configured.
  7227. trays = ams_data.get("tray", []) or []
  7228. effective_humidity_threshold = float(
  7229. PrintScheduler.resolve_humidity_threshold(
  7230. trays, per_type_humidity_thresholds, int(humidity_threshold)
  7231. )
  7232. )
  7233. # Check humidity alarm (only if above threshold)
  7234. if humidity is not None and humidity > effective_humidity_threshold:
  7235. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  7236. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7237. now = datetime.now(timezone.utc)
  7238. if (
  7239. last_alarm is None
  7240. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7241. ):
  7242. _ams_alarm_cooldown[cooldown_key] = now
  7243. logger.info(
  7244. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  7245. )
  7246. try:
  7247. # Call different notification method based on AMS type
  7248. if is_ams_ht:
  7249. await notification_service.on_ams_ht_humidity_high(
  7250. printer.id,
  7251. printer.name,
  7252. ams_label,
  7253. humidity,
  7254. effective_humidity_threshold,
  7255. db,
  7256. )
  7257. else:
  7258. await notification_service.on_ams_humidity_high(
  7259. printer.id,
  7260. printer.name,
  7261. ams_label,
  7262. humidity,
  7263. effective_humidity_threshold,
  7264. db,
  7265. )
  7266. except Exception as e:
  7267. logger.warning("Failed to send humidity alarm: %s", e)
  7268. # A drying cycle heats the unit far past ams_temp_fair on
  7269. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  7270. # AMS-HT, against a 35 C default — so the alarm fired
  7271. # once an hour for the whole cycle and kept firing while
  7272. # the unit cooled back down (#1802). Latch on the
  7273. # firmware's own drying state and hold until the reading
  7274. # returns to normal. Humidity is deliberately left alone:
  7275. # it falls during drying, which is the whole point.
  7276. latch_key = f"{printer.id}:{ams_id}"
  7277. # The latch releases at `threshold`, so it takes the alarm
  7278. # number too. Handing it the display band would strand the
  7279. # latch on any unit that settles back above it -- a room
  7280. # where the AMS rests at 37.7 C never returns under a 35 C
  7281. # band, so the latch could only expire on the grace cap
  7282. # rather than releasing when the unit had actually cooled.
  7283. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  7284. drying_active=is_drying_active(ams_data),
  7285. temperature=temperature,
  7286. threshold=temp_alarm_threshold,
  7287. latched_at=drying_latch.get(latch_key),
  7288. now=datetime.now(timezone.utc),
  7289. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  7290. )
  7291. if new_latch is None:
  7292. drying_latch.pop(latch_key, None)
  7293. else:
  7294. drying_latch[latch_key] = new_latch
  7295. # Check temperature alarm (only if above threshold)
  7296. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  7297. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  7298. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7299. now = datetime.now(timezone.utc)
  7300. if (
  7301. last_alarm is None
  7302. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7303. ):
  7304. _ams_alarm_cooldown[cooldown_key] = now
  7305. logger.info(
  7306. f"Sending temperature alarm for {printer.name} {ams_label}: "
  7307. f"{temperature}°C > {temp_alarm_threshold}°C"
  7308. )
  7309. try:
  7310. # Call different notification method based on AMS type
  7311. if is_ams_ht:
  7312. # The reported threshold has to be the one
  7313. # that fired, or the message says "> 35 °C"
  7314. # while firing at 45.
  7315. await notification_service.on_ams_ht_temperature_high(
  7316. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7317. )
  7318. else:
  7319. await notification_service.on_ams_temperature_high(
  7320. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7321. )
  7322. except Exception as e:
  7323. logger.warning("Failed to send temperature alarm: %s", e)
  7324. if drying_latch != drying_latch_before:
  7325. await _save_ams_drying_latch(db, drying_latch)
  7326. await db.commit()
  7327. if recorded_count > 0:
  7328. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  7329. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  7330. global _ams_cleanup_counter
  7331. _ams_cleanup_counter += 1
  7332. if _ams_cleanup_counter >= 288:
  7333. _ams_cleanup_counter = 0
  7334. # Get retention days from settings
  7335. from backend.app.models.settings import Settings
  7336. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  7337. setting = result.scalar_one_or_none()
  7338. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  7339. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7340. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  7341. await db.commit()
  7342. if result.rowcount > 0:
  7343. logger.info(
  7344. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  7345. )
  7346. # Wait until next recording interval
  7347. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  7348. except asyncio.CancelledError:
  7349. break
  7350. except Exception as e:
  7351. logger.warning("AMS history recording failed: %s", e)
  7352. await asyncio.sleep(60) # Wait a bit before retrying
  7353. def start_ams_history_recording():
  7354. """Start the AMS history recording background task."""
  7355. global _ams_history_task
  7356. if _ams_history_task is None:
  7357. _ams_history_task = asyncio.create_task(record_ams_history())
  7358. logging.getLogger(__name__).info("AMS history recording started")
  7359. def stop_ams_history_recording():
  7360. """Stop the AMS history recording background task."""
  7361. global _ams_history_task
  7362. if _ams_history_task:
  7363. _ams_history_task.cancel()
  7364. _ams_history_task = None
  7365. logging.getLogger(__name__).info("AMS history recording stopped")
  7366. # Printer sensor history recording (nozzle / bed / chamber)
  7367. _printer_sensor_history_task: asyncio.Task | None = None
  7368. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  7369. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  7370. _printer_sensor_cleanup_counter = 0
  7371. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  7372. # MQTT parser writes, so we don't need to handle per-model field aliases here
  7373. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  7374. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  7375. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  7376. _SENSOR_TARGET_KEYS = {
  7377. "nozzle": "nozzle_target",
  7378. "nozzle_2": "nozzle_2_target",
  7379. "bed": "bed_target",
  7380. "chamber": "chamber_target",
  7381. }
  7382. async def record_printer_sensor_history():
  7383. """Background task to record nozzle / bed / chamber readings.
  7384. Pulls from `state.temperatures` (already normalised across all printer
  7385. models by the MQTT parser) rather than re-parsing raw_data, so we get
  7386. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  7387. """
  7388. logger = logging.getLogger(__name__)
  7389. await asyncio.sleep(10)
  7390. while True:
  7391. try:
  7392. from backend.app.models.printer import Printer
  7393. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  7394. from backend.app.models.settings import Settings
  7395. async with async_session() as db:
  7396. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7397. printers = result.scalars().all()
  7398. recorded_count = 0
  7399. for printer in printers:
  7400. state = printer_manager.get_status(printer.id)
  7401. if not state or not state.connected:
  7402. continue
  7403. temps = getattr(state, "temperatures", None) or {}
  7404. if not isinstance(temps, dict):
  7405. continue
  7406. for kind in _SENSOR_KINDS:
  7407. if kind not in temps:
  7408. continue
  7409. try:
  7410. value = float(temps[kind])
  7411. except (ValueError, TypeError):
  7412. continue
  7413. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  7414. target_val: float | None = None
  7415. if target_raw is not None:
  7416. try:
  7417. target_val = float(target_raw)
  7418. except (ValueError, TypeError):
  7419. target_val = None
  7420. db.add(
  7421. PrinterSensorHistory(
  7422. printer_id=printer.id,
  7423. sensor_kind=kind,
  7424. value=value,
  7425. target=target_val,
  7426. )
  7427. )
  7428. recorded_count += 1
  7429. await db.commit()
  7430. if recorded_count > 0:
  7431. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  7432. # Periodic cleanup — once every ~24h at this interval.
  7433. global _printer_sensor_cleanup_counter
  7434. _printer_sensor_cleanup_counter += 1
  7435. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  7436. if _printer_sensor_cleanup_counter >= cleanup_every:
  7437. _printer_sensor_cleanup_counter = 0
  7438. result = await db.execute(
  7439. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  7440. )
  7441. setting = result.scalar_one_or_none()
  7442. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  7443. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7444. cleanup = await db.execute(
  7445. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  7446. )
  7447. await db.commit()
  7448. if cleanup.rowcount > 0:
  7449. logger.info(
  7450. "Cleaned up %s old printer sensor history entries (older than %s days)",
  7451. cleanup.rowcount,
  7452. retention_days,
  7453. )
  7454. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  7455. except asyncio.CancelledError:
  7456. break
  7457. except Exception as e:
  7458. logger.warning("Printer sensor history recording failed: %s", e)
  7459. await asyncio.sleep(60)
  7460. def start_printer_sensor_history_recording():
  7461. global _printer_sensor_history_task
  7462. if _printer_sensor_history_task is None:
  7463. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  7464. logging.getLogger(__name__).info("Printer sensor history recording started")
  7465. def stop_printer_sensor_history_recording():
  7466. global _printer_sensor_history_task
  7467. if _printer_sensor_history_task:
  7468. _printer_sensor_history_task.cancel()
  7469. _printer_sensor_history_task = None
  7470. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  7471. # Printer runtime tracking
  7472. _runtime_tracking_task: asyncio.Task | None = None
  7473. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  7474. async def track_printer_runtime():
  7475. """Background task to track printer active runtime (RUNNING state only).
  7476. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  7477. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  7478. which track mechanical wear. Pause time has no motion and no wear, so
  7479. counting it inflates maintenance warnings (#1521).
  7480. """
  7481. logger = logging.getLogger(__name__)
  7482. # Wait for MQTT connections to establish on startup
  7483. await asyncio.sleep(15)
  7484. while True:
  7485. try:
  7486. from backend.app.models.printer import Printer
  7487. # Fetch printer IDs in a short-lived read-only session
  7488. async with async_session() as db:
  7489. result = await db.execute(
  7490. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  7491. Printer.is_active.is_(True)
  7492. )
  7493. )
  7494. printer_rows = result.all()
  7495. now = datetime.now(timezone.utc)
  7496. updated_count = 0
  7497. # Update each printer in its own short session to minimise write-lock
  7498. # hold time and avoid blocking critical commits like queue status
  7499. # updates (#897).
  7500. for pid, pname, runtime_secs, last_update in printer_rows:
  7501. state = printer_manager.get_status(pid)
  7502. if not state:
  7503. logger.debug("[%s] Runtime tracking: no state available", pname)
  7504. continue
  7505. if not state.connected:
  7506. logger.debug("[%s] Runtime tracking: not connected", pname)
  7507. continue
  7508. needs_commit = False
  7509. new_runtime = runtime_secs
  7510. new_last_update = last_update
  7511. if state.state == "RUNNING":
  7512. if last_update:
  7513. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  7514. elapsed = (now - lu).total_seconds()
  7515. if elapsed > 0:
  7516. new_runtime = runtime_secs + int(elapsed)
  7517. updated_count += 1
  7518. needs_commit = True
  7519. logger.debug(
  7520. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  7521. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  7522. )
  7523. else:
  7524. needs_commit = True
  7525. logger.debug("[%s] Runtime tracking: first active detection", pname)
  7526. new_last_update = now
  7527. else:
  7528. if last_update is not None:
  7529. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  7530. new_last_update = None
  7531. needs_commit = True
  7532. if needs_commit:
  7533. try:
  7534. async with async_session() as db:
  7535. result = await db.execute(select(Printer).where(Printer.id == pid))
  7536. printer = result.scalar_one_or_none()
  7537. if printer:
  7538. printer.runtime_seconds = new_runtime
  7539. printer.last_runtime_update = new_last_update
  7540. await db.commit()
  7541. except Exception as e:
  7542. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  7543. if updated_count > 0:
  7544. logger.debug("Updated runtime for %s printer(s)", updated_count)
  7545. except asyncio.CancelledError:
  7546. logger.info("Runtime tracking cancelled")
  7547. break
  7548. except Exception as e:
  7549. logger.warning("Runtime tracking failed: %s", e)
  7550. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  7551. def start_runtime_tracking():
  7552. """Start the printer runtime tracking background task."""
  7553. global _runtime_tracking_task
  7554. if _runtime_tracking_task is None:
  7555. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  7556. logging.getLogger(__name__).info("Printer runtime tracking started")
  7557. def stop_runtime_tracking():
  7558. """Stop the printer runtime tracking background task."""
  7559. global _runtime_tracking_task
  7560. if _runtime_tracking_task:
  7561. _runtime_tracking_task.cancel()
  7562. _runtime_tracking_task = None
  7563. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  7564. # SpoolBuddy device watchdog
  7565. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  7566. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  7567. async def _spoolbuddy_watchdog_loop():
  7568. """Periodic check for SpoolBuddy devices that have gone offline."""
  7569. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  7570. while True:
  7571. try:
  7572. await spoolbuddy_watchdog()
  7573. except asyncio.CancelledError:
  7574. break
  7575. except Exception as e:
  7576. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  7577. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  7578. def start_spoolbuddy_watchdog():
  7579. global _spoolbuddy_watchdog_task
  7580. if _spoolbuddy_watchdog_task is None:
  7581. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  7582. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  7583. def stop_spoolbuddy_watchdog():
  7584. global _spoolbuddy_watchdog_task
  7585. if _spoolbuddy_watchdog_task:
  7586. _spoolbuddy_watchdog_task.cancel()
  7587. _spoolbuddy_watchdog_task = None
  7588. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  7589. # Dead-MQTT-session recovery
  7590. #
  7591. # check_staleness() covers the "connected but silent" half-broken session. It
  7592. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  7593. # is the only thing left watching at that point. When paho stops making
  7594. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  7595. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  7596. # offline with the UI open the whole time, recovered only when something
  7597. # happened to nudge it.
  7598. #
  7599. # This loop is that backstop. It only touches printers that had a working
  7600. # session and lost it, and only when the MQTT port still answers — a printer
  7601. # that is simply switched off is left to paho, since rebuilding a client
  7602. # against an unreachable host achieves nothing and would fill the log every
  7603. # night.
  7604. _connection_watchdog_task: asyncio.Task | None = None
  7605. CONNECTION_WATCHDOG_INTERVAL = 60
  7606. # How long a printer must have been silent before we stop trusting paho.
  7607. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  7608. # so a session that is recovering on its own is never interrupted.
  7609. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  7610. # Per-printer floor between rebuild attempts.
  7611. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  7612. _connection_watchdog_last_attempt: dict[int, float] = {}
  7613. async def _recover_dead_printer_sessions() -> int:
  7614. """Rebuild MQTT clients that have been offline too long to still be trying.
  7615. Returns the number of printers a rebuild was attempted for (for tests and
  7616. for the caller's logging). Never raises: one unreachable printer must not
  7617. stop the sweep for the rest of the farm.
  7618. """
  7619. logger = logging.getLogger(__name__)
  7620. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  7621. now = time.monotonic()
  7622. recovered = 0
  7623. for printer_id, client in list(printer_manager._clients.items()):
  7624. try:
  7625. if client.state.connected:
  7626. _connection_watchdog_last_attempt.pop(printer_id, None)
  7627. continue
  7628. # Time since the last inbound message is the age of the last known
  7629. # good session — no extra bookkeeping needed, and it is the same
  7630. # clock is_stale() reads. 0 means this client has never had one:
  7631. # that is the initial-connect path, where paho retrying is the
  7632. # correct and only behaviour, so leave it be.
  7633. last_msg = client._last_message_time
  7634. if not last_msg:
  7635. continue
  7636. offline_for = time.time() - last_msg
  7637. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  7638. continue
  7639. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  7640. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  7641. continue
  7642. if not await check_port(client.ip_address, PORT_MQTT):
  7643. # Switched off, unplugged, or off the network. Paho's retry is
  7644. # the right handler; say so at debug level and move on.
  7645. logger.debug(
  7646. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  7647. "— leaving the reconnect to paho",
  7648. printer_id,
  7649. offline_for,
  7650. )
  7651. _connection_watchdog_last_attempt[printer_id] = now
  7652. continue
  7653. _connection_watchdog_last_attempt[printer_id] = now
  7654. recovered += 1
  7655. logger.warning(
  7656. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  7657. "rebuilding the client with a fresh session (last connect error: %s)",
  7658. printer_id,
  7659. offline_for,
  7660. PORT_MQTT,
  7661. client.last_connect_error or "none recorded",
  7662. )
  7663. # Async context, so this takes the hard-reset path: fresh client_id,
  7664. # paho's QoS 1 queue dropped. That matters — a project_file left
  7665. # unacked on the dead session would otherwise replay into the new
  7666. # one and trip 0500_4003 on the printer (#1136).
  7667. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  7668. except Exception as e:
  7669. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  7670. return recovered
  7671. async def _connection_watchdog_loop():
  7672. logger = logging.getLogger(__name__)
  7673. # Let the initial connects settle before judging anyone offline.
  7674. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  7675. while True:
  7676. try:
  7677. await _recover_dead_printer_sessions()
  7678. except asyncio.CancelledError:
  7679. break
  7680. except Exception as e:
  7681. logger.warning("Connection watchdog sweep failed: %s", e)
  7682. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  7683. def start_connection_watchdog():
  7684. global _connection_watchdog_task
  7685. if _connection_watchdog_task is None:
  7686. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  7687. logging.getLogger(__name__).info("Printer connection watchdog started")
  7688. def stop_connection_watchdog():
  7689. global _connection_watchdog_task
  7690. if _connection_watchdog_task:
  7691. _connection_watchdog_task.cancel()
  7692. _connection_watchdog_task = None
  7693. _connection_watchdog_last_attempt.clear()
  7694. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  7695. # Camera stream orphan cleanup
  7696. _camera_cleanup_task: asyncio.Task | None = None
  7697. CAMERA_CLEANUP_INTERVAL = 60
  7698. async def _camera_cleanup_loop():
  7699. """Periodically clean up orphaned ffmpeg processes."""
  7700. from backend.app.api.routes.camera import cleanup_orphaned_streams
  7701. while True:
  7702. try:
  7703. await cleanup_orphaned_streams()
  7704. except asyncio.CancelledError:
  7705. break
  7706. except Exception as e:
  7707. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  7708. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  7709. def start_camera_cleanup():
  7710. global _camera_cleanup_task
  7711. if _camera_cleanup_task is None:
  7712. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  7713. logging.getLogger(__name__).info("Camera stream cleanup started")
  7714. def stop_camera_cleanup():
  7715. global _camera_cleanup_task
  7716. if _camera_cleanup_task:
  7717. _camera_cleanup_task.cancel()
  7718. _camera_cleanup_task = None
  7719. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  7720. # ---------------------------------------------------------------------------
  7721. # Expected-print TTL eviction
  7722. # ---------------------------------------------------------------------------
  7723. def _evict_stale_expected_prints() -> None:
  7724. """Remove entries from _expected_prints / _expected_print_creators that are
  7725. older than _EXPECTED_PRINT_TTL_SECONDS.
  7726. This prevents unbounded growth when a print is registered (via
  7727. register_expected_print) but on_print_start never fires — e.g. because the
  7728. printer disconnects, the app restarts, or the print is started directly from
  7729. the printer panel without going through the queue.
  7730. """
  7731. # Use monotonic time so the TTL is unaffected by system clock adjustments
  7732. # (e.g. NTP sync, DST changes).
  7733. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  7734. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  7735. if not stale_keys:
  7736. return
  7737. evicted_archive_ids: set[int] = set()
  7738. for key in stale_keys:
  7739. archive_id = _expected_prints.pop(key, None)
  7740. if archive_id is not None:
  7741. evicted_archive_ids.add(archive_id)
  7742. _expected_print_creators.pop(key, None)
  7743. _expected_print_registered_at.pop(key, None)
  7744. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  7745. # that have no remaining live keys in _expected_prints (all variants
  7746. # were just evicted).
  7747. live_archive_ids = set(_expected_prints.values())
  7748. for archive_id in evicted_archive_ids:
  7749. if archive_id not in live_archive_ids:
  7750. _print_ams_mappings.pop(archive_id, None)
  7751. _print_cost_center_ids.pop(archive_id, None)
  7752. _print_plate_ids.pop(archive_id, None)
  7753. logging.getLogger(__name__).info(
  7754. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  7755. )
  7756. async def _expected_prints_cleanup_loop() -> None:
  7757. """Background task: periodically evict stale expected-print entries."""
  7758. while True:
  7759. try:
  7760. _evict_stale_expected_prints()
  7761. except asyncio.CancelledError:
  7762. raise
  7763. except Exception as e:
  7764. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  7765. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  7766. def start_expected_prints_cleanup() -> None:
  7767. global _expected_prints_cleanup_task
  7768. if _expected_prints_cleanup_task is None:
  7769. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  7770. logging.getLogger(__name__).info("Expected prints cleanup started")
  7771. def stop_expected_prints_cleanup() -> None:
  7772. global _expected_prints_cleanup_task
  7773. if _expected_prints_cleanup_task:
  7774. _expected_prints_cleanup_task.cancel()
  7775. _expected_prints_cleanup_task = None
  7776. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  7777. # ---------------------------------------------------------------------------
  7778. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  7779. # ---------------------------------------------------------------------------
  7780. _auth_cleanup_task: asyncio.Task | None = None
  7781. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  7782. async def _run_auth_cleanup() -> None:
  7783. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  7784. from backend.app.core.database import async_session
  7785. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  7786. from backend.app.models.user_totp import UserTOTP
  7787. now = datetime.now(timezone.utc)
  7788. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  7789. try:
  7790. async with async_session() as db:
  7791. stale_cutoff = now - timedelta(hours=1)
  7792. result = await db.execute(
  7793. select(UserTOTP).where(
  7794. UserTOTP.is_enabled.is_(False),
  7795. UserTOTP.created_at < stale_cutoff,
  7796. )
  7797. )
  7798. stale_records = result.scalars().all()
  7799. if stale_records:
  7800. for rec in stale_records:
  7801. await db.delete(rec)
  7802. await db.commit()
  7803. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  7804. except Exception as e:
  7805. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  7806. # Remove expired revoked-JTI entries (they are no longer needed once the
  7807. # original token's exp has passed — the token would be rejected by JWT
  7808. # signature verification regardless).
  7809. try:
  7810. async with async_session() as db:
  7811. await db.execute(
  7812. delete(AuthEphemeralToken).where(
  7813. AuthEphemeralToken.token_type == "revoked_jti",
  7814. AuthEphemeralToken.expires_at < now,
  7815. )
  7816. )
  7817. await db.commit()
  7818. except Exception as e:
  7819. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  7820. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  7821. # Events outside this window can never affect rate-limit decisions — they only
  7822. # consume DB space. Use the same window constant as the rate limiter so the
  7823. # two are always in sync.
  7824. try:
  7825. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  7826. async with async_session() as db:
  7827. await db.execute(
  7828. delete(AuthRateLimitEvent).where(
  7829. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  7830. )
  7831. )
  7832. await db.commit()
  7833. except Exception as e:
  7834. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  7835. async def _auth_cleanup_loop() -> None:
  7836. """Periodic background task: run auth cleanup every hour."""
  7837. while True:
  7838. try:
  7839. await _run_auth_cleanup()
  7840. except asyncio.CancelledError:
  7841. break
  7842. except Exception as e:
  7843. logging.warning("Auth cleanup loop error: %s", e)
  7844. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  7845. def start_auth_cleanup() -> None:
  7846. global _auth_cleanup_task
  7847. if _auth_cleanup_task is None:
  7848. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  7849. logging.getLogger(__name__).info("Auth periodic cleanup started")
  7850. def stop_auth_cleanup() -> None:
  7851. global _auth_cleanup_task
  7852. if _auth_cleanup_task:
  7853. _auth_cleanup_task.cancel()
  7854. _auth_cleanup_task = None
  7855. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  7856. @asynccontextmanager
  7857. async def lifespan(app: FastAPI):
  7858. # Startup
  7859. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  7860. # anything else can spawn tasks that might trip it.
  7861. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  7862. install_proactor_reset_filter()
  7863. # Before init_db, so the warning is near the top of the log rather than
  7864. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  7865. warn_if_running_on_uvloop()
  7866. await init_db()
  7867. # Browser download tokens expire after five minutes. Remove abandoned
  7868. # prepared ZIPs at startup as well as before each new preparation so a
  7869. # quiet appliance cannot retain an unusable bundle indefinitely.
  7870. try:
  7871. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  7872. await prune_stale_printer_file_bundles()
  7873. except Exception as exc:
  7874. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  7875. # After migrations, so the is_env_managed column exists. Never raises --
  7876. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  7877. # startup (see apply_env_oidc_provider).
  7878. from backend.app.core.oidc_env import apply_env_oidc_provider
  7879. async with async_session() as oidc_db:
  7880. await apply_env_oidc_provider(oidc_db)
  7881. # Close out batches that finished before `completed` was a reachable status
  7882. # (#342). Without this the Batches tab opens on every batch created since
  7883. # the feature shipped, all still marked active. Never blocks startup.
  7884. try:
  7885. from backend.app.services.print_batch import backfill_batch_statuses
  7886. async with async_session() as batch_db:
  7887. await backfill_batch_statuses(batch_db)
  7888. except Exception as exc:
  7889. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  7890. # Register an app-scoped httpx client for Bambu Cloud services so
  7891. # per-request BambuCloudService instances reuse the same connection pool
  7892. # (important for routes like /cloud/filament-info that chain many
  7893. # get_setting_detail calls). The shared client stores no region/token
  7894. # state, so the per-request ownership pattern that fixed the region-bleed
  7895. # bug is preserved.
  7896. import httpx as _httpx
  7897. from backend.app.services.bambu_cloud import set_shared_http_client
  7898. from backend.app.services.makerworld import (
  7899. set_shared_http_client as set_shared_makerworld_http_client,
  7900. )
  7901. from backend.app.services.orca_cloud import (
  7902. set_shared_http_client as set_shared_orca_http_client,
  7903. )
  7904. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  7905. set_shared_http_client(_shared_cloud_http_client)
  7906. # Reuse the same connection pool for MakerWorld — different host, same
  7907. # keep-alive pool saves a TLS handshake per request.
  7908. set_shared_makerworld_http_client(_shared_cloud_http_client)
  7909. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  7910. # each spun up (and never closed) its own client, leaking sockets.
  7911. set_shared_orca_http_client(_shared_cloud_http_client)
  7912. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  7913. # This can happen when a print was cancelled mid-print on versions before this fix.
  7914. try:
  7915. async with async_session() as db:
  7916. from backend.app.models.print_queue import PrintQueueItem
  7917. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  7918. aborted_items = result.scalars().all()
  7919. if aborted_items:
  7920. for item in aborted_items:
  7921. item.status = "cancelled"
  7922. await db.commit()
  7923. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  7924. except Exception as e:
  7925. logging.warning("Failed to fix aborted queue items: %s", e)
  7926. # Restore debug logging state from previous session
  7927. await init_debug_logging()
  7928. # Set up printer manager callbacks
  7929. loop = asyncio.get_event_loop()
  7930. printer_manager.set_event_loop(loop)
  7931. printer_manager.set_status_change_callback(on_printer_status_change)
  7932. printer_manager.set_print_start_callback(on_print_start)
  7933. printer_manager.set_print_complete_callback(on_print_complete)
  7934. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  7935. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  7936. printer_manager.set_ams_change_callback(on_ams_change)
  7937. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  7938. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  7939. await printer_manager.load_awaiting_plate_clear_from_db()
  7940. # Layer change callback for external camera timelapse
  7941. async def on_layer_change(printer_id: int, layer_num: int):
  7942. """Capture timelapse frame on layer change + first layer notification."""
  7943. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  7944. await tl_layer_change(printer_id, layer_num)
  7945. # #1867: bank a recent in-print frame so the finish-photo path has a
  7946. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  7947. # #2547 added `on_print_progress` as a second driver — this one alone
  7948. # stops firing once the final layer begins.
  7949. await _maybe_bank_inprint_frame(printer_id, layer_num)
  7950. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  7951. # Gate on actual printing state — Bambu firmware ticks layer_num during
  7952. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  7953. # nozzle clean), so a bare layer_num check can fire minutes before the
  7954. # first real extrusion. We require gcode_state == RUNNING and
  7955. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  7956. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  7957. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  7958. # edge fires later; _first_layer_notified stays clear until we actually send
  7959. # so a deferred re-evaluation can win. See issue #1837.
  7960. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  7961. client = printer_manager.get_client(printer_id)
  7962. state = client.state if client else None
  7963. if not state or state.state != "RUNNING":
  7964. return
  7965. if state.mc_print_sub_stage not in (None, 0):
  7966. return
  7967. _first_layer_notified[printer_id] = True
  7968. try:
  7969. async with async_session() as db:
  7970. from backend.app.models.printer import Printer
  7971. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7972. printer = result.scalar_one_or_none()
  7973. if not printer:
  7974. return
  7975. printer_name = printer.name
  7976. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  7977. total_layers = state.total_layers if state else 0
  7978. image_data = await _capture_snapshot_for_notification(
  7979. printer_id, printer, logging.getLogger(__name__)
  7980. )
  7981. await notification_service.on_first_layer_complete(
  7982. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  7983. )
  7984. except Exception as e:
  7985. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  7986. printer_manager.set_layer_change_callback(on_layer_change)
  7987. async def on_print_progress(printer_id: int, percent: int):
  7988. """#2547: keep the in-print frame bank fresh through the final layer.
  7989. `on_layer_change` stops the moment the last layer starts, which on the
  7990. H2C capture that closed #2547 left the bank stale for the three minutes
  7991. that layer took. Progress is the only field that keeps advancing there,
  7992. and it freezes before the End G-code runs — so banking on it stays
  7993. inside the print and never sees a swapped plate.
  7994. """
  7995. client = printer_manager.get_client(printer_id)
  7996. state = client.state if client else None
  7997. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  7998. printer_manager.set_print_progress_callback(on_print_progress)
  7999. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8000. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8001. waiter = _bed_cool_waiters.get(printer_id)
  8002. if not waiter:
  8003. return
  8004. threshold = waiter["threshold"]
  8005. if bed_temp > threshold:
  8006. return
  8007. # Bed is at or below threshold — fire notification and remove waiter
  8008. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8009. if not waiter_info:
  8010. return # Another callback already handled it
  8011. bed_cool_logger = logging.getLogger(__name__)
  8012. bed_cool_logger.info(
  8013. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8014. bed_temp,
  8015. printer_id,
  8016. threshold,
  8017. )
  8018. try:
  8019. printer_info = printer_manager.get_printer(printer_id)
  8020. p_name = printer_info.name if printer_info else "Unknown"
  8021. async with async_session() as db:
  8022. await notification_service.on_bed_cooled(
  8023. printer_id=printer_id,
  8024. printer_name=p_name,
  8025. bed_temp=bed_temp,
  8026. threshold=threshold,
  8027. filename=waiter_info["filename"],
  8028. db=db,
  8029. )
  8030. except Exception as e:
  8031. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8032. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8033. async def on_drying_complete(printer_id: int, ams_id: int):
  8034. """Smart-plug auto-off-after-drying trigger (#1349).
  8035. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8036. manager walks all plugs linked to this printer and turns off only
  8037. the ones with ``auto_off_after_drying`` enabled, after their
  8038. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8039. dual-AMS dry that ends within the same MQTT push) call this once
  8040. per unit — the manager's ``_cancel_pending_off`` collapses
  8041. repeated scheduling on the same plug to one timer, so duplicate
  8042. fires are safe.
  8043. """
  8044. try:
  8045. async with async_session() as db:
  8046. await smart_plug_manager.on_drying_complete(printer_id, db)
  8047. except Exception as e:
  8048. logging.getLogger(__name__).warning(
  8049. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8050. printer_id,
  8051. ams_id,
  8052. e,
  8053. )
  8054. printer_manager.set_drying_complete_callback(on_drying_complete)
  8055. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  8056. """Surface the read-back result of a spool assignment to the UI (#2582).
  8057. The MQTT client confirms (or fails to confirm) that the tray telemetry
  8058. echoed back the filament id we pushed. We relay that as a websocket
  8059. event so the frontend can toast "loaded" / "assignment didn't take"
  8060. instead of the historic silent fire-and-forget, which made the
  8061. AMS→Studio hand-off feel random to users.
  8062. """
  8063. try:
  8064. from backend.app.services.spool_assignment_notifications import (
  8065. _slot_label_from_global_tray,
  8066. )
  8067. if ams_id == 255:
  8068. global_id = 254 + tray_id
  8069. elif ams_id >= 128:
  8070. global_id = ams_id
  8071. else:
  8072. global_id = ams_id * 4 + tray_id
  8073. slot_label = _slot_label_from_global_tray(global_id)
  8074. printer_info = printer_manager.get_printer(printer_id)
  8075. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8076. await ws_manager.broadcast(
  8077. {
  8078. "type": "spool_assignment_verified",
  8079. "printer_id": printer_id,
  8080. "printer_name": printer_name,
  8081. "ams_id": ams_id,
  8082. "tray_id": tray_id,
  8083. "slot": slot_label,
  8084. "verified": verified,
  8085. # Present on success: False means the filament setting landed
  8086. # but the K-profile (cali_idx) did not — the reporter's exact
  8087. # "loaded but no flow profile" symptom.
  8088. "kprofile_applied": detail.get("kprofile_applied", True),
  8089. # Present on failure: whether any tray telemetry was seen in
  8090. # the window (distinguishes "printer silent" from "printer
  8091. # stored something else").
  8092. "saw_tray": detail.get("saw_tray", False),
  8093. }
  8094. )
  8095. except Exception as e:
  8096. logging.getLogger(__name__).warning(
  8097. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  8098. printer_id,
  8099. ams_id,
  8100. tray_id,
  8101. e,
  8102. )
  8103. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  8104. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  8105. """Persist a mid-print tray change for completion-time attribution.
  8106. AMS filament backup switches trays without telling the slicer, so the
  8107. tray-change log is the only record of which spool fed which layers.
  8108. Keeping it only in memory meant a restart mid-print charged everything
  8109. to the tray that finished the job.
  8110. """
  8111. try:
  8112. from backend.app.services.usage_tracker import record_tray_change
  8113. async with async_session() as db:
  8114. await record_tray_change(db, printer_id, tray_global, layer_num)
  8115. except Exception as e:
  8116. logging.getLogger(__name__).warning(
  8117. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  8118. printer_id,
  8119. tray_global,
  8120. layer_num,
  8121. e,
  8122. )
  8123. printer_manager.set_tray_change_callback(on_tray_change)
  8124. # Initialize MQTT relay from settings
  8125. async with async_session() as db:
  8126. from backend.app.api.routes.settings import get_setting
  8127. mqtt_settings = {
  8128. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  8129. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  8130. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  8131. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  8132. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  8133. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  8134. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  8135. }
  8136. await mqtt_relay.configure(mqtt_settings)
  8137. # Restore MQTT smart plug subscriptions
  8138. if mqtt_settings.get("mqtt_enabled"):
  8139. from backend.app.models.smart_plug import SmartPlug
  8140. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  8141. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  8142. mqtt_plugs = result.scalars().all()
  8143. restored = 0
  8144. for plug in mqtt_plugs:
  8145. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  8146. restored += 1
  8147. if restored:
  8148. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  8149. # Connect to all active printers
  8150. async with async_session() as db:
  8151. await init_printer_connections(db)
  8152. # Auto-connect to Spoolman if enabled
  8153. async with async_session() as db:
  8154. from backend.app.api.routes.settings import get_setting
  8155. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  8156. spoolman_url = await get_setting(db, "spoolman_url")
  8157. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  8158. try:
  8159. client = await init_spoolman_client(spoolman_url)
  8160. if await client.health_check():
  8161. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  8162. # Ensure the 'tag' extra field exists for RFID/UUID storage
  8163. field_ok = await client.ensure_tag_extra_field()
  8164. if not field_ok:
  8165. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  8166. # Register the BambuStudio slicer-preset fields used by the
  8167. # spool-edit / assign flow. Spoolman rejects PATCHes with
  8168. # unknown extra keys, so these must exist before any update
  8169. # that touches them.
  8170. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  8171. if not await client.ensure_extra_field(field_name):
  8172. logging.warning(
  8173. "Spoolman extra field %r registration failed — "
  8174. "spool slicer-preset edits will return 502",
  8175. field_name,
  8176. )
  8177. else:
  8178. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  8179. except Exception as e:
  8180. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  8181. # Start the print scheduler
  8182. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  8183. # Start the smart plug scheduler for time-based on/off
  8184. smart_plug_manager.start_scheduler()
  8185. # Start the Home Assistant sensor poller (#1148)
  8186. ha_sensor_manager.start()
  8187. location_ha_sensor_manager.start()
  8188. # Resume any pending auto-offs that were interrupted by restart
  8189. await smart_plug_manager.resume_pending_auto_offs()
  8190. # Start the notification digest scheduler
  8191. notification_service.start_digest_scheduler()
  8192. # Start the GitHub backup scheduler
  8193. await github_backup_service.start_scheduler()
  8194. # Start the local backup scheduler
  8195. await local_backup_service.start_scheduler()
  8196. await obico_detection_service.start()
  8197. # Start the library trash sweeper (#1008)
  8198. await library_trash_service.start_scheduler()
  8199. # Start the archive auto-purge sweeper (#1008 follow-up)
  8200. await archive_purge_service.start_scheduler()
  8201. # Start AMS history recording
  8202. start_ams_history_recording()
  8203. # Start printer sensor (nozzle / bed / chamber) history recording
  8204. start_printer_sensor_history_recording()
  8205. # Start printer runtime tracking
  8206. start_runtime_tracking()
  8207. # Start SpoolBuddy device watchdog
  8208. start_spoolbuddy_watchdog()
  8209. # Start camera stream orphan cleanup
  8210. start_camera_cleanup()
  8211. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  8212. start_connection_watchdog()
  8213. # One-shot sweep for timelapse session directories orphaned by a crash
  8214. # or restart that happened mid-print (in-memory session tracking can't
  8215. # survive that, and nothing else reaps the leftover frames/output file)
  8216. try:
  8217. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  8218. removed = cleanup_orphaned_timelapse_sessions()
  8219. if removed:
  8220. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  8221. except Exception as e:
  8222. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  8223. # Start expected-print TTL eviction (prevents memory leak when prints are
  8224. # registered but on_print_start never fires)
  8225. start_expected_prints_cleanup()
  8226. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  8227. start_auth_cleanup()
  8228. from backend.app.services.printer_media import start_printer_download_cleanup
  8229. start_printer_download_cleanup()
  8230. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  8231. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  8232. from backend.app.services.loop_watchdog import start_loop_watchdog
  8233. start_loop_watchdog()
  8234. # Initialize virtual printer manager and sync from DB
  8235. from backend.app.services.virtual_printer import virtual_printer_manager
  8236. virtual_printer_manager.set_session_factory(async_session)
  8237. virtual_printer_manager.set_printer_manager(printer_manager)
  8238. try:
  8239. await virtual_printer_manager.sync_from_db()
  8240. logging.info("Virtual printer manager synced from database")
  8241. except Exception as e:
  8242. logging.warning("Failed to sync virtual printers: %s", e)
  8243. yield
  8244. # Shutdown
  8245. print_scheduler.stop()
  8246. smart_plug_manager.stop_scheduler()
  8247. ha_sensor_manager.stop()
  8248. location_ha_sensor_manager.stop()
  8249. notification_service.stop_digest_scheduler()
  8250. github_backup_service.stop_scheduler()
  8251. local_backup_service.stop_scheduler()
  8252. library_trash_service.stop_scheduler()
  8253. archive_purge_service.stop_scheduler()
  8254. obico_detection_service.stop()
  8255. stop_ams_history_recording()
  8256. stop_printer_sensor_history_recording()
  8257. stop_runtime_tracking()
  8258. stop_spoolbuddy_watchdog()
  8259. stop_camera_cleanup()
  8260. stop_connection_watchdog()
  8261. from backend.app.services.loop_watchdog import stop_loop_watchdog
  8262. stop_loop_watchdog()
  8263. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  8264. # cleanly rather than waiting on a queue that nothing will ever fill.
  8265. try:
  8266. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  8267. await shutdown_all_broadcasters()
  8268. except Exception as e:
  8269. logging.warning("Failed to shut down camera broadcasters: %s", e)
  8270. stop_expected_prints_cleanup()
  8271. stop_auth_cleanup()
  8272. from backend.app.services.printer_media import stop_printer_download_cleanup
  8273. await stop_printer_download_cleanup()
  8274. printer_manager.disconnect_all()
  8275. await close_spoolman_client()
  8276. # Stop all virtual printer services
  8277. await virtual_printer_manager.stop_all()
  8278. await mqtt_smart_plug_service.disconnect(timeout=2)
  8279. await mqtt_relay.disconnect(timeout=2)
  8280. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  8281. set_shared_http_client(None)
  8282. set_shared_makerworld_http_client(None)
  8283. set_shared_orca_http_client(None)
  8284. await _shared_cloud_http_client.aclose()
  8285. # Checkpoint WAL (SQLite only) and close all database connections
  8286. from backend.app.core.db_dialect import is_sqlite
  8287. if is_sqlite():
  8288. try:
  8289. async with engine.begin() as conn:
  8290. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  8291. logging.info("WAL checkpoint completed")
  8292. except Exception as e:
  8293. logging.warning("WAL checkpoint failed: %s", e)
  8294. await engine.dispose()
  8295. app = FastAPI(
  8296. title=app_settings.app_name,
  8297. description="Archive and manage Bambu Lab 3MF files",
  8298. version=APP_VERSION,
  8299. lifespan=lifespan,
  8300. )
  8301. # =============================================================================
  8302. # Authentication Middleware - Secures ALL API routes by default
  8303. # =============================================================================
  8304. # Public routes that don't require authentication even when auth is enabled
  8305. PUBLIC_API_ROUTES = {
  8306. # Auth routes needed before/during login
  8307. "/api/v1/auth/status",
  8308. "/api/v1/auth/login",
  8309. "/api/v1/auth/setup", # Needed for initial setup and recovery
  8310. # Advanced auth status needed for login page
  8311. "/api/v1/auth/advanced-auth/status",
  8312. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  8313. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  8314. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  8315. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  8316. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  8317. # OIDC routes that must be reachable without a JWT
  8318. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  8319. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  8320. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  8321. # Version check for updates (no sensitive data)
  8322. "/api/v1/updates/version",
  8323. # Metrics endpoint handles its own prometheus_token authentication
  8324. "/api/v1/metrics",
  8325. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  8326. # this BEFORE a JWT is available to pick up the firstboot wizard's
  8327. # hostname / timezone / locale and the chrony NTP-gate state. The
  8328. # response contains user-set defaults and a public sync flag — no
  8329. # secrets. Without this entry the global auth middleware returns 401
  8330. # before the route handler runs, regardless of the route's own
  8331. # "no auth required" intent.
  8332. "/api/v1/system/appliance",
  8333. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  8334. # authenticates with a long-lived ``camwall``-scoped token in the query
  8335. # string — exactly like the camera streams two lists below, and for the same
  8336. # reason (no header to put a JWT in). "Public" here only means the middleware
  8337. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  8338. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  8339. # plain ``camera_stream`` token does NOT open this door.
  8340. "/api/v1/camwall/printers",
  8341. }
  8342. # Route prefixes that are public (for routes with dynamic segments)
  8343. PUBLIC_API_PREFIXES = [
  8344. # WebSocket connections handle their own auth
  8345. "/api/v1/ws",
  8346. # OIDC authorize redirects — include provider_id in path
  8347. "/api/v1/auth/oidc/authorize/",
  8348. ]
  8349. # Route patterns that are public (read-only display data)
  8350. # These are checked with "in path" - needed because browsers load images/videos
  8351. # via <img src> and <video src> which don't include Authorization headers
  8352. PUBLIC_API_PATTERNS = [
  8353. # Thumbnails
  8354. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  8355. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  8356. # Images and media
  8357. "/photos/", # /archives/{id}/photos/{filename}
  8358. "/project-image/", # /archives/{id}/project-image/{path}
  8359. "/qrcode", # /archives/{id}/qrcode
  8360. "/timelapse", # /archives/{id}/timelapse (video)
  8361. "/cover", # /printers/{id}/cover
  8362. "/icon", # /external-links/{id}/icon
  8363. # Camera (streams loaded via <img> tag)
  8364. "/camera/stream", # /printers/{id}/camera/stream
  8365. "/camera/snapshot", # /printers/{id}/camera/snapshot
  8366. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  8367. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  8368. # string (same reasoning as the camera streams above — no header to carry a
  8369. # JWT). "Public" only means the middleware steps aside; the route still runs
  8370. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  8371. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  8372. "/overlay-status", # /printers/{id}/overlay-status
  8373. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  8374. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  8375. # download token in the URL path instead.
  8376. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  8377. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  8378. # and these patterns match by substring. Without its own entry the middleware
  8379. # 401s the slicer's header-less request before the route's token check runs,
  8380. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  8381. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  8382. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  8383. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  8384. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  8385. ]
  8386. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  8387. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  8388. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  8389. Format: comma-separated list of ``scheme://host[:port]`` origins.
  8390. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  8391. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  8392. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  8393. Invalid entries are dropped with a warning rather than failing startup, so
  8394. a typo in one origin doesn't take the whole deployment down.
  8395. """
  8396. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  8397. if not raw:
  8398. return ()
  8399. valid: list[str] = []
  8400. for item in raw.split(","):
  8401. candidate = item.strip()
  8402. if not candidate:
  8403. continue
  8404. try:
  8405. parsed = urlparse(candidate)
  8406. except ValueError as e:
  8407. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  8408. continue
  8409. if parsed.scheme not in ("http", "https"):
  8410. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  8411. continue
  8412. if not parsed.netloc:
  8413. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  8414. continue
  8415. if parsed.path and parsed.path != "/":
  8416. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  8417. continue
  8418. if parsed.query or parsed.fragment:
  8419. _security_headers_logger.warning(
  8420. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  8421. )
  8422. continue
  8423. if "*" in parsed.netloc:
  8424. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  8425. continue
  8426. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  8427. if valid:
  8428. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  8429. return tuple(valid)
  8430. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  8431. def _frame_ancestors(default_value: str) -> str:
  8432. """Compose the ``frame-ancestors`` CSP directive (#1191).
  8433. ``default_value`` is the strict directive used when the operator has not
  8434. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  8435. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  8436. Settings URL builder's preview). When trusted origins
  8437. are configured, ``'self'`` is always included so same-origin embedding never
  8438. breaks even if an operator forgets to add their own origin to the list.
  8439. """
  8440. if _TRUSTED_FRAME_ORIGINS:
  8441. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  8442. return f"frame-ancestors {default_value};"
  8443. @app.middleware("http")
  8444. async def security_headers_middleware(request, call_next):
  8445. """Add standard HTTP security headers to every response."""
  8446. # Per-request nonce stamped into `script-src` (#1460). On its own this
  8447. # changes nothing for Bambuddy's own pages — index.html has no inline
  8448. # scripts since the SW registration moved to /sw-register.js. The reason
  8449. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  8450. # script injected into the HTML on the edge, with a fresh hash on every
  8451. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  8452. # it clones the same nonce onto its injected <script>, and the inline
  8453. # script passes the policy without us needing 'unsafe-inline'. See
  8454. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  8455. csp_nonce = secrets.token_urlsafe(16)
  8456. response = await call_next(request)
  8457. response.headers["X-Content-Type-Options"] = "nosniff"
  8458. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  8459. # browsers honour CSP frame-ancestors instead, and the legacy
  8460. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  8461. # When operators have explicitly allowlisted trusted frame origins (#1191
  8462. # — typically Home Assistant on a different port), drop X-Frame-Options
  8463. # and let the CSP-side frame-ancestors directive govern embedding.
  8464. if not _TRUSTED_FRAME_ORIGINS:
  8465. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  8466. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  8467. # Content-Security-Policy for the React SPA.
  8468. # Notes:
  8469. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  8470. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  8471. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  8472. # - media-src blob:: timelapse video player uses Blob URLs.
  8473. # - font-src data:: some icon fonts are embedded as data URIs.
  8474. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  8475. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  8476. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  8477. # default CSP would render a blank page.
  8478. response.headers["Content-Security-Policy"] = (
  8479. "default-src 'self'; "
  8480. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  8481. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  8482. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  8483. "connect-src 'self'; "
  8484. "font-src 'self' data: https://fonts.gstatic.com; "
  8485. "worker-src 'self' blob:; "
  8486. "object-src 'none'; "
  8487. "base-uri 'self'; " + _frame_ancestors("'none'")
  8488. )
  8489. else:
  8490. # The streaming overlay is embedded same-origin by the URL builder's
  8491. # preview in Settings (#1422), so this branch allows 'self'.
  8492. # Embedding from anywhere else is still refused: 'self'
  8493. # only permits a framer on this origin, which is Bambuddy's own UI, so
  8494. # a clickjacking page on another host is blocked exactly as before.
  8495. # (The overlay draws status over a camera feed and its only interactive
  8496. # element is the logo link, so there is nothing to bait a click into
  8497. # even from a same-origin framer.) Cross-origin embedding of the
  8498. # overlay — Home Assistant on another port — remains what
  8499. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  8500. # allowlist in.
  8501. embeddable_same_origin = request.url.path.startswith("/overlay/")
  8502. response.headers["Content-Security-Policy"] = (
  8503. "default-src 'self'; "
  8504. f"script-src 'self' 'nonce-{csp_nonce}'; "
  8505. "style-src 'self' 'unsafe-inline'; "
  8506. "img-src 'self' data: blob:; "
  8507. "media-src 'self' blob:; "
  8508. "connect-src 'self' ws: wss:; "
  8509. "font-src 'self' data:; "
  8510. "object-src 'none'; "
  8511. "base-uri 'self'; "
  8512. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  8513. )
  8514. if request.url.scheme == "https":
  8515. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  8516. return response
  8517. @app.middleware("http")
  8518. async def auth_middleware(request, call_next):
  8519. """Enforce authentication on all API routes when auth is enabled.
  8520. This middleware provides defense-in-depth by checking auth at the API gateway level,
  8521. regardless of whether individual routes have auth dependencies.
  8522. """
  8523. from starlette.responses import JSONResponse
  8524. path = request.url.path
  8525. # Only apply to API routes
  8526. if not path.startswith("/api/"):
  8527. return await call_next(request)
  8528. # Allow public routes
  8529. if path in PUBLIC_API_ROUTES:
  8530. return await call_next(request)
  8531. # Allow public prefixes
  8532. for prefix in PUBLIC_API_PREFIXES:
  8533. if path.startswith(prefix):
  8534. return await call_next(request)
  8535. # Allow public patterns (read-only display data like thumbnails)
  8536. for pattern in PUBLIC_API_PATTERNS:
  8537. if pattern in path:
  8538. return await call_next(request)
  8539. # Check if auth is enabled. Fail CLOSED on any exception during the
  8540. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  8541. # an attacker who could force a DB exception (e.g. file-descriptor
  8542. # exhaustion via login flood) bypass auth on every protected endpoint.
  8543. try:
  8544. async with async_session() as db:
  8545. from backend.app.core.auth import is_auth_enabled
  8546. auth_enabled = await is_auth_enabled(db)
  8547. if not auth_enabled:
  8548. # Auth disabled, allow all requests
  8549. return await call_next(request)
  8550. except Exception:
  8551. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  8552. return JSONResponse(
  8553. status_code=503,
  8554. content={"detail": "Authentication service temporarily unavailable"},
  8555. )
  8556. # Auth is enabled - require valid token
  8557. auth_header = request.headers.get("Authorization")
  8558. x_api_key = request.headers.get("X-API-Key")
  8559. # Check for API key auth first
  8560. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  8561. # API key authentication - let the request through to be validated by route handler
  8562. # API keys are validated per-route since they have different permission levels
  8563. return await call_next(request)
  8564. # Check for JWT auth
  8565. if not auth_header or not auth_header.startswith("Bearer "):
  8566. return JSONResponse(
  8567. status_code=401,
  8568. content={"detail": "Authentication required"},
  8569. headers={"WWW-Authenticate": "Bearer"},
  8570. )
  8571. # Validate JWT token
  8572. import jwt
  8573. try:
  8574. from backend.app.core.auth import (
  8575. ALGORITHM,
  8576. SECRET_KEY,
  8577. _is_token_fresh,
  8578. get_user_by_username,
  8579. is_jti_revoked,
  8580. )
  8581. token = auth_header.replace("Bearer ", "")
  8582. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  8583. username = payload.get("sub")
  8584. if not username:
  8585. raise ValueError("No username in token")
  8586. jti = payload.get("jti")
  8587. if not jti:
  8588. raise ValueError("No jti in token")
  8589. iat = payload.get("iat")
  8590. # Verify user exists, is active, and token is still fresh (L-R8-A).
  8591. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  8592. # this session so the gateway adds a single pooled checkout, not two (#2572).
  8593. async with async_session() as db:
  8594. if await is_jti_revoked(jti, db):
  8595. return JSONResponse(
  8596. status_code=401,
  8597. content={"detail": "Token has been revoked"},
  8598. headers={"WWW-Authenticate": "Bearer"},
  8599. )
  8600. user = await get_user_by_username(db, username)
  8601. if not user or not user.is_active:
  8602. return JSONResponse(
  8603. status_code=401,
  8604. content={"detail": "User not found or inactive"},
  8605. headers={"WWW-Authenticate": "Bearer"},
  8606. )
  8607. if not _is_token_fresh(iat, user):
  8608. return JSONResponse(
  8609. status_code=401,
  8610. content={"detail": "Token no longer valid"},
  8611. headers={"WWW-Authenticate": "Bearer"},
  8612. )
  8613. except jwt.ExpiredSignatureError:
  8614. return JSONResponse(
  8615. status_code=401,
  8616. content={"detail": "Token has expired"},
  8617. headers={"WWW-Authenticate": "Bearer"},
  8618. )
  8619. except (jwt.InvalidTokenError, ValueError, Exception):
  8620. return JSONResponse(
  8621. status_code=401,
  8622. content={"detail": "Invalid token"},
  8623. headers={"WWW-Authenticate": "Bearer"},
  8624. )
  8625. return await call_next(request)
  8626. @app.middleware("http")
  8627. async def trace_id_middleware(request, call_next):
  8628. """Stamp every HTTP request with a trace ID and echo it back.
  8629. Decorated AFTER auth_middleware on purpose: Starlette stacks
  8630. @app.middleware decorators LIFO, so the last-decorated runs first
  8631. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  8632. which means auth-middleware log lines (and every line emitted on the
  8633. way down to and back from the route handler) all carry the same
  8634. trace ID. If we put it before auth, auth's logs would be stamped
  8635. with the *previous* request's ID — useless for correlation.
  8636. Honours an inbound ``X-Trace-Id`` header so callers running their
  8637. own tracing can correlate their span IDs with our log lines, but
  8638. only if the value passes the whitelist gate in
  8639. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  8640. rejected (too long, contains control chars, etc.) silently triggers
  8641. a freshly minted server-side ID rather than failing the request.
  8642. The minted (or echoed) ID is set on a ContextVar so that every log
  8643. record emitted during the request — application logs *and* uvicorn's
  8644. access log — carries it via TraceIDFilter, and is also written to
  8645. the ``X-Trace-Id`` response header so clients can pin a server-side
  8646. log search to the exact request they made.
  8647. """
  8648. from backend.app.core.trace import (
  8649. generate_trace_id,
  8650. normalise_inbound_trace_id,
  8651. trace_id_var,
  8652. )
  8653. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  8654. trace_id = inbound if inbound is not None else generate_trace_id()
  8655. token = trace_id_var.set(trace_id)
  8656. try:
  8657. response = await call_next(request)
  8658. finally:
  8659. # Reset the ContextVar so a record emitted in a totally
  8660. # unrelated background task that just happens to inherit this
  8661. # context doesn't keep referencing this request's ID forever.
  8662. # In practice ContextVar.reset is best-effort under asyncio
  8663. # task-spawn semantics, but the cost is one attribute write so
  8664. # we may as well do it.
  8665. trace_id_var.reset(token)
  8666. response.headers["X-Trace-Id"] = trace_id
  8667. return response
  8668. # API routes
  8669. app.include_router(auth.router, prefix=app_settings.api_prefix)
  8670. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  8671. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  8672. app.include_router(users.router, prefix=app_settings.api_prefix)
  8673. app.include_router(groups.router, prefix=app_settings.api_prefix)
  8674. app.include_router(printers.router, prefix=app_settings.api_prefix)
  8675. app.include_router(archives.router, prefix=app_settings.api_prefix)
  8676. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  8677. app.include_router(finance.router, prefix=app_settings.api_prefix)
  8678. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  8679. app.include_router(labels.router, prefix=app_settings.api_prefix)
  8680. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  8681. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  8682. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  8683. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  8684. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  8685. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  8686. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  8687. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  8688. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  8689. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  8690. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  8691. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  8692. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  8693. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  8694. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  8695. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  8696. app.include_router(updates.router, prefix=app_settings.api_prefix)
  8697. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  8698. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  8699. app.include_router(camera.router, prefix=app_settings.api_prefix)
  8700. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  8701. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  8702. app.include_router(projects.router, prefix=app_settings.api_prefix)
  8703. app.include_router(library.router, prefix=app_settings.api_prefix)
  8704. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  8705. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  8706. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  8707. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  8708. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  8709. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  8710. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  8711. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  8712. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  8713. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  8714. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  8715. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  8716. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  8717. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  8718. app.include_router(system.router, prefix=app_settings.api_prefix)
  8719. app.include_router(support.router, prefix=app_settings.api_prefix)
  8720. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  8721. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  8722. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  8723. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  8724. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  8725. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  8726. app.include_router(obico.router, prefix=app_settings.api_prefix)
  8727. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  8728. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  8729. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  8730. # Serve static files (React build)
  8731. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  8732. app.mount(
  8733. "/assets",
  8734. StaticFiles(directory=app_settings.static_dir / "assets"),
  8735. name="assets",
  8736. )
  8737. if (app_settings.static_dir / "img").exists():
  8738. app.mount(
  8739. "/img",
  8740. StaticFiles(directory=app_settings.static_dir / "img"),
  8741. name="img",
  8742. )
  8743. if (app_settings.static_dir / "icons").exists():
  8744. app.mount(
  8745. "/icons",
  8746. StaticFiles(directory=app_settings.static_dir / "icons"),
  8747. name="icons",
  8748. )
  8749. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  8750. # falls through to the SPA catch-all and returns index.html, which the
  8751. # browser's font sanitizer rejects ("downloadable font: rejected by
  8752. # sanitizer").
  8753. if (app_settings.static_dir / "fonts").exists():
  8754. app.mount(
  8755. "/fonts",
  8756. StaticFiles(directory=app_settings.static_dir / "fonts"),
  8757. name="fonts",
  8758. )
  8759. @app.get("/")
  8760. async def serve_frontend():
  8761. """Serve the React frontend."""
  8762. index_file = app_settings.static_dir / "index.html"
  8763. if index_file.exists():
  8764. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8765. return {
  8766. "message": "Bambuddy API",
  8767. "docs": "/docs",
  8768. "frontend": "Build and place React app in /static directory",
  8769. }
  8770. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  8771. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  8772. # forever, but the HTML wrapping it is the only file that knows which hash
  8773. # is current. Without explicit cache-control headers Chromium decides
  8774. # heuristically (typically 10% of the time since Last-Modified) and on
  8775. # long-running kiosks happily serves stale HTML across browser restarts.
  8776. # That stale HTML references an old bundle hash, the old bundle is also
  8777. # in the disk cache, and the user ends up running pre-update JS forever
  8778. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  8779. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  8780. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  8781. @app.get("/health")
  8782. async def health_check():
  8783. """Health check endpoint."""
  8784. return {"status": "healthy"}
  8785. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  8786. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  8787. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  8788. # in deployment debugging.
  8789. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  8790. async def serve_manifest():
  8791. """Serve PWA manifest."""
  8792. manifest_file = app_settings.static_dir / "manifest.json"
  8793. if manifest_file.exists():
  8794. return FileResponse(manifest_file, media_type="application/manifest+json")
  8795. return {"error": "Manifest not found"}
  8796. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  8797. async def serve_service_worker():
  8798. """Serve service worker."""
  8799. sw_file = app_settings.static_dir / "sw.js"
  8800. if sw_file.exists():
  8801. return FileResponse(
  8802. sw_file,
  8803. media_type="application/javascript",
  8804. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  8805. )
  8806. return {"error": "Service worker not found"}
  8807. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  8808. async def serve_sw_register():
  8809. """Serve the service-worker registration bootstrap script.
  8810. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  8811. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  8812. """
  8813. reg_file = app_settings.static_dir / "sw-register.js"
  8814. if reg_file.exists():
  8815. return FileResponse(reg_file, media_type="application/javascript")
  8816. return {"error": "sw-register.js not found"}
  8817. # ── GCode viewer static files ────────────────────────────────────────────────
  8818. # Catch-all route for React Router (must be last)
  8819. @app.get("/{full_path:path}")
  8820. async def serve_spa(full_path: str):
  8821. """Serve React app for client-side routing."""
  8822. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  8823. if full_path.startswith("api/"):
  8824. from fastapi import HTTPException
  8825. raise HTTPException(status_code=404, detail="Not found")
  8826. index_file = app_settings.static_dir / "index.html"
  8827. if index_file.exists():
  8828. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8829. return {"error": "Frontend not built"}