main.py 432 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. import posixpath
  6. import secrets
  7. import time
  8. from contextlib import asynccontextmanager
  9. from datetime import datetime, timedelta, timezone
  10. from logging.handlers import RotatingFileHandler
  11. from pathlib import Path, PurePosixPath
  12. from urllib.parse import urlparse
  13. from fastapi import FastAPI
  14. from fastapi.responses import FileResponse
  15. from fastapi.staticfiles import StaticFiles
  16. from sqlalchemy import delete, or_, select, text
  17. from backend.app.api.routes import (
  18. ams_history,
  19. api_keys,
  20. archive_purge,
  21. archives,
  22. auth,
  23. bug_report,
  24. camera,
  25. camwall,
  26. cloud,
  27. discovery,
  28. external_links,
  29. filaments,
  30. finance,
  31. firmware,
  32. github_backup,
  33. groups,
  34. ha_sensors,
  35. inventory,
  36. kprofiles,
  37. labels,
  38. library,
  39. library_tags,
  40. library_trash,
  41. library_variants,
  42. local_backup,
  43. local_presets,
  44. maintenance,
  45. makerworld,
  46. metrics,
  47. mfa,
  48. notification_templates,
  49. notifications,
  50. obico,
  51. orca_cloud,
  52. pending_uploads,
  53. pipeline_runs,
  54. print_log,
  55. print_queue,
  56. printer_sensor_history,
  57. printers,
  58. projects,
  59. scheduled_dryings,
  60. settings as settings_routes,
  61. slice_jobs,
  62. slicer_pipelines,
  63. slicer_presets,
  64. smart_plugs,
  65. sponsor_prompt,
  66. spoolbuddy,
  67. spoolman,
  68. spoolman_inventory,
  69. support,
  70. system,
  71. updates,
  72. user_notifications,
  73. users,
  74. virtual_printers,
  75. webhook,
  76. websocket,
  77. )
  78. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  79. from backend.app.api.routes.support import init_debug_logging
  80. from backend.app.core.config import APP_VERSION, settings as app_settings
  81. from backend.app.core.database import async_session, engine, init_db
  82. from backend.app.core.tasks import spawn_background_task
  83. from backend.app.core.websocket import ws_manager
  84. from backend.app.models.smart_plug import SmartPlug
  85. from backend.app.services import print_dispatch_context
  86. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  87. from backend.app.services.archive_purge import archive_purge_service
  88. from backend.app.services.bambu_ftp import (
  89. FileNotOnPrinterError,
  90. cache_3mf_download,
  91. clear_3mf_cache,
  92. download_file_async,
  93. ftps_handshake_blocked,
  94. get_cached_3mf,
  95. get_ftp_retry_settings,
  96. with_ftp_retry,
  97. )
  98. from backend.app.services.bambu_mqtt import PrinterState
  99. from backend.app.services.github_backup import github_backup_service
  100. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  101. from backend.app.services.homeassistant import homeassistant_service
  102. from backend.app.services.library_trash import library_trash_service
  103. from backend.app.services.local_backup import local_backup_service
  104. from backend.app.services.mqtt_relay import mqtt_relay
  105. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  106. from backend.app.services.notification_service import notification_service
  107. from backend.app.services.obico_detection import obico_detection_service
  108. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  109. from backend.app.services.print_scheduler import scheduler as print_scheduler
  110. from backend.app.services.print_storage import external_storage_present, print_file_reachable_over_ftp
  111. from backend.app.services.printer_manager import (
  112. init_printer_connections,
  113. parse_plate_id,
  114. printer_manager,
  115. printer_state_to_dict,
  116. resolve_plate_id,
  117. )
  118. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  119. from backend.app.services.smart_plug_manager import smart_plug_manager
  120. from backend.app.services.spool_assignment_notifications import (
  121. notify_missing_spool_assignments_on_print_start,
  122. )
  123. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  124. from backend.app.services.spoolman_tracking import (
  125. cleanup_tracking as _cleanup_spoolman_tracking,
  126. report_usage as _report_spoolman_usage,
  127. store_print_data as _store_spoolman_print_data,
  128. )
  129. from backend.app.services.tasmota import tasmota_service
  130. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  131. from backend.app.utils.fts_routing import extruder_for_inlet, slot_extruder as resolve_slot_extruder
  132. from backend.app.utils.print_jobs import is_internal_printer_job
  133. # =============================================================================
  134. # Dependency Check - runs before other imports to give helpful error messages
  135. # =============================================================================
  136. def _start_error_server(missing_packages: list):
  137. """Start a minimal HTTP server to display dependency errors in browser."""
  138. import os
  139. import signal
  140. from http.server import BaseHTTPRequestHandler, HTTPServer
  141. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  142. html = f"""<!DOCTYPE html>
  143. <html>
  144. <head>
  145. <title>Bambuddy - Setup Required</title>
  146. <style>
  147. body {{
  148. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  149. background: #0f172a; color: #e2e8f0;
  150. display: flex; justify-content: center; align-items: center;
  151. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  152. }}
  153. .container {{
  154. background: #1e293b; border-radius: 12px; padding: 40px;
  155. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  156. }}
  157. h1 {{ color: #f87171; margin-bottom: 10px; }}
  158. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  159. .packages {{
  160. background: #0f172a; border-radius: 8px; padding: 20px;
  161. margin: 20px 0; text-align: left;
  162. }}
  163. .packages ul {{ margin: 0; padding-left: 20px; }}
  164. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  165. .command {{
  166. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  167. margin: 15px 0; font-family: monospace; color: #4ade80;
  168. text-align: left; overflow-x: auto;
  169. }}
  170. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  171. </style>
  172. </head>
  173. <body>
  174. <div class="container">
  175. <h1>Setup Required</h1>
  176. <h2>Missing Python packages</h2>
  177. <div class="packages"><ul>{packages_html}</ul></div>
  178. <p>To fix, run this command on your server:</p>
  179. <div class="command">pip install -r requirements.txt</div>
  180. <p>Or if using a virtual environment:</p>
  181. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  182. <p class="note">After installing, restart Bambuddy:<br>
  183. <code>sudo systemctl restart bambuddy</code></p>
  184. </div>
  185. </body>
  186. </html>"""
  187. class ErrorHandler(BaseHTTPRequestHandler):
  188. def do_GET(self):
  189. self.send_response(503)
  190. self.send_header("Content-type", "text/html")
  191. self.end_headers()
  192. self.wfile.write(html.encode())
  193. def log_message(self, format, *args):
  194. print(f"[Error Server] {args[0]}")
  195. port = int(os.environ.get("PORT", 8000))
  196. print(f"\nStarting error server on http://0.0.0.0:{port}")
  197. print("Visit this URL in your browser to see the error details.\n")
  198. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  199. def shutdown(signum, frame):
  200. print("\nShutting down error server...")
  201. raise SystemExit(0)
  202. signal.signal(signal.SIGTERM, shutdown)
  203. signal.signal(signal.SIGINT, shutdown)
  204. server.serve_forever()
  205. def check_dependencies():
  206. """Check that all required packages are installed."""
  207. missing = []
  208. # Map of import name -> package name (for pip install)
  209. required = {
  210. "jwt": "PyJWT",
  211. "fastapi": "fastapi",
  212. "uvicorn": "uvicorn",
  213. "sqlalchemy": "sqlalchemy",
  214. "aiosqlite": "aiosqlite",
  215. "pydantic": "pydantic",
  216. "paho.mqtt": "paho-mqtt",
  217. }
  218. for module, package in required.items():
  219. try:
  220. __import__(module)
  221. except ImportError:
  222. missing.append(package)
  223. if missing:
  224. print("\n" + "=" * 60)
  225. print("ERROR: Missing required Python packages!")
  226. print("=" * 60)
  227. print(f"\nMissing packages: {', '.join(missing)}")
  228. print("\nTo fix, run:")
  229. print(" pip install -r requirements.txt")
  230. print("\nOr if using a virtual environment:")
  231. print(" ./venv/bin/pip install -r requirements.txt")
  232. print("=" * 60 + "\n")
  233. _start_error_server(missing)
  234. check_dependencies()
  235. # =============================================================================
  236. # Import settings first for logging configuration
  237. # Configure logging based on settings
  238. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  239. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  240. log_level = getattr(logging, log_level_str, logging.INFO)
  241. # Trace ID column ([-] when no request scope is active — startup, MQTT
  242. # callbacks, scheduled tasks not chained from a request — so the column
  243. # stays visually aligned and missing values are obvious in grep). See
  244. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  245. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  246. # Create root logger
  247. root_logger = logging.getLogger()
  248. root_logger.setLevel(log_level)
  249. # Trace-ID injection: this filter populates record.trace_id from the
  250. # per-request ContextVar so the format string above can reference it.
  251. # Attached to each HANDLER (not the root logger) because Python's
  252. # logging semantics only invoke a logger's filters on records that
  253. # *originated* at that logger — records propagated up from child
  254. # loggers (every named logger in the app) never trigger root's filter.
  255. # Putting it on the handlers means every record any handler emits gets
  256. # trace_id injected just before the formatter runs, regardless of which
  257. # logger created the record. Without this, the formatter raises
  258. # KeyError on every child-logger record and the record is silently
  259. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  260. # partially" bug we hit. See backend/app/core/trace.py for the
  261. # ContextVar the filter reads.
  262. from backend.app.core.trace import TraceIDFilter
  263. _trace_id_filter = TraceIDFilter()
  264. # Console handler - always enabled
  265. console_handler = logging.StreamHandler()
  266. console_handler.setLevel(log_level)
  267. console_handler.setFormatter(logging.Formatter(log_format))
  268. console_handler.addFilter(_trace_id_filter)
  269. root_logger.addHandler(console_handler)
  270. # File handler - only in production or if explicitly enabled
  271. if app_settings.log_to_file:
  272. log_file = app_settings.log_dir / "bambuddy.log"
  273. file_handler = RotatingFileHandler(
  274. log_file,
  275. maxBytes=app_settings.log_max_bytes,
  276. backupCount=app_settings.log_backup_count,
  277. encoding="utf-8",
  278. )
  279. file_handler.setLevel(log_level)
  280. file_handler.setFormatter(logging.Formatter(log_format))
  281. file_handler.addFilter(_trace_id_filter)
  282. root_logger.addHandler(file_handler)
  283. logging.info("Logging to file: %s", log_file)
  284. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  285. # access logger with propagate=False by default, so without this attach
  286. # there is no on-disk record of which endpoint triggered a server-state
  287. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  288. # for exactly this reason. Filtered to write methods only
  289. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  290. # frontend don't churn the rotation window faster than it's useful.
  291. from backend.app.core.logging_filters import (
  292. CancelledPoolNoiseFilter,
  293. WriteRequestsOnlyFilter,
  294. )
  295. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  296. uvicorn_access_logger.addHandler(file_handler)
  297. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  298. # Uvicorn's access logger has propagate=False (its own default), so the
  299. # root-attached TraceIDFilter never sees these records. Attach a
  300. # second instance directly so HTTP access lines carry the same trace
  301. # ID column as the application logs they correlate with.
  302. uvicorn_access_logger.addFilter(TraceIDFilter())
  303. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  304. # BaseHTTPMiddleware cancelling the inner task scope on client
  305. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  306. # underlying transaction leak; this filter only suppresses the residual
  307. # log records that pre-existing pools still emit during their cleanup.
  308. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  309. # Reduce noise from third-party libraries in production
  310. if not app_settings.debug:
  311. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  312. logging.getLogger("httpcore").setLevel(logging.WARNING)
  313. logging.getLogger("httpx").setLevel(logging.WARNING)
  314. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  315. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  316. # Track active prints: {(printer_id, filename): archive_id}
  317. _active_prints: dict[tuple[int, str], int] = {}
  318. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  319. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  320. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  321. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  322. # instead of running its own grab-now chain when present, so the finish photo
  323. # captures the better-framed pre-bed-drop moment without us having to force
  324. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  325. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  326. #
  327. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  328. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  329. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  330. # bank and the others are not — so the consumer can't tell them apart and
  331. # must not rotate again.
  332. _stage22_finish_frames: dict[int, bytes] = {}
  333. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  334. # `finally` block (whether it captured a frame or not). The consumer in
  335. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  336. # so the FINISH-state fallback path — where moment and completion are dispatched
  337. # back-to-back — doesn't race past the producer with an empty pop, and the
  338. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  339. # grab (Bambu printers allow only one RTSP client at a time).
  340. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  341. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  342. # layer-change and on print-progress advances (#2547) while the model is still
  343. # printing, then consumed by the FINISH-state finish-photo path when the
  344. # dispatcher recorded that it injected End G-code into this print. Bambu
  345. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  346. # plate-swap) has run, so a live grab there would capture the swapped/empty
  347. # plate.
  348. #
  349. # The load-bearing property: both drivers are print telemetry that stops before
  350. # the End G-code executes — no further layer_num increases, and mc_percent
  351. # freezes — so the last banked frame is always the finished print before the
  352. # swap. Anything added as a third driver must hold that same property.
  353. _inprint_frame_bank: dict[int, bytes] = {}
  354. # Monotonic timestamp of the last banked frame per printer — throttles banking
  355. # so tall prints don't add a camera grab on every layer.
  356. _inprint_frame_bank_ts: dict[int, float] = {}
  357. # Minimum seconds between banked frames, except the final object layer which
  358. # always refreshes for the best framing.
  359. _INPRINT_BANK_MIN_INTERVAL = 25.0
  360. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  361. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  362. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  363. # the first connected status update for that connection; transitions back
  364. # to False whenever we observe `state.connected = False` so the next
  365. # reconnect re-arms reconciliation. Keyed by printer_id.
  366. _printer_reconciled_since_connect: dict[int, bool] = {}
  367. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  368. # {(printer_id, filename): archive_id}
  369. _expected_prints: dict[tuple[int, str], int] = {}
  370. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  371. # Used by usage tracker to map 3MF slots to physical AMS trays
  372. _print_ams_mappings: dict[int, list[int]] = {}
  373. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  374. _print_cost_center_ids: dict[int, int] = {}
  375. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  376. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  377. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  378. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  379. # for the queue path. Cleared on print completion or TTL eviction.
  380. _print_plate_ids: dict[int, int] = {}
  381. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  382. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  383. _last_progress_milestone: dict[int, int] = {}
  384. # Track whether first layer complete notification has been sent for current print
  385. _first_layer_notified: dict[int, bool] = {}
  386. # Track whether we already sent a kill-switch stop for the current unauthorized print
  387. _unauthorized_print_kill_sent: set[int] = set()
  388. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  389. # lookup briefly so an unknown active print does not query the database on
  390. # every status frame. A short TTL keeps settings changes responsive.
  391. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  392. _kill_switch_setting_cache: tuple[bool, float] | None = None
  393. # Provider notification started when the kill switch stops a print. The later
  394. # MQTT print-complete callback awaits this task and only sends its regular
  395. # provider notification when the immediate attempt failed.
  396. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  397. # Track HMS errors that have been notified: {printer_id: set of error codes}
  398. # This prevents sending duplicate notifications for the same error
  399. _notified_hms_errors: dict[int, set[str]] = {}
  400. # Track when HMS errors were last seen: {printer_id: timestamp}
  401. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  402. _hms_last_seen: dict[int, float] = {}
  403. _HMS_CLEAR_GRACE_SECONDS = 30.0
  404. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  405. # Used for snapshot-diff detection at print completion
  406. _timelapse_baselines: dict[int, set[str]] = {}
  407. # Track printers waiting for bed to cool after print completion.
  408. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  409. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  410. _bed_cool_waiters: dict[int, dict] = {}
  411. # Track printers where the user explicitly stopped the print from the queue UI.
  412. # When on_print_complete fires with status "failed" for these printers we treat it
  413. # as "cancelled" (stopped by user) so the correct notification email is sent.
  414. _user_stopped_printers: set[int] = set()
  415. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  416. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  417. # holds the previous observation so we only fire on the True → False edge (a
  418. # False → False repeat doesn't notify; an initial False at startup doesn't
  419. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  420. # holds the per-printer pending asyncio task that fires the notification
  421. # after a debounce window — cancelled if the printer reconnects before the
  422. # window elapses, so transient MQTT blips don't flood the user.
  423. _printer_last_connected: dict[int, bool] = {}
  424. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  425. # Debounce: a printer must stay offline this long before we notify. Sized
  426. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  427. # so a single stale-trigger cooldown isn't enough to fire — only a real
  428. # offline that survives one reconnect attempt notifies.
  429. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  430. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  431. # when status="failed" to label the print's failure_reason in archives.
  432. #
  433. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  434. # which is wrong on two counts:
  435. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  436. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  437. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  438. # the public wiki) as part of its user-cancel sequence. Matching on the module
  439. # alone caused user-cancellations to be archived as "Layer shift" failures.
  440. # We now match by full short code only — anything not in this map leaves
  441. # failure_reason=None rather than guessing.
  442. _HMS_FAILURE_REASONS: dict[str, str] = {
  443. # Layer shift / step loss
  444. "0300_4057": "Layer shift",
  445. "0300_4068": "Layer shift",
  446. "0300_800C": "Layer shift",
  447. # Filament runout (printer-side & per-AMS-slot)
  448. "0300_8004": "Filament runout",
  449. "0700_8011": "Filament runout",
  450. "0701_8011": "Filament runout",
  451. "0702_8011": "Filament runout",
  452. "0703_8011": "Filament runout",
  453. "0704_8011": "Filament runout",
  454. "0705_8011": "Filament runout",
  455. "0706_8011": "Filament runout",
  456. "0707_8011": "Filament runout",
  457. "07FF_8011": "Filament runout",
  458. # Clogged nozzle / extruder
  459. "0300_4006": "Clogged nozzle",
  460. "0300_8016": "Clogged nozzle",
  461. "0300_801C": "Clogged nozzle",
  462. "0700_8003": "Clogged nozzle",
  463. "0700_8007": "Clogged nozzle",
  464. "0700_8013": "Clogged nozzle",
  465. "0701_8003": "Clogged nozzle",
  466. "0701_8007": "Clogged nozzle",
  467. "0701_8013": "Clogged nozzle",
  468. "0702_8003": "Clogged nozzle",
  469. }
  470. def _hms_short_code(attr: int, code: int | str) -> str:
  471. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  472. if isinstance(code, str):
  473. code_int = int(code.replace("0x", ""), 16) if code else 0
  474. else:
  475. code_int = int(code or 0)
  476. attr_int = int(attr or 0)
  477. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  478. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  479. """Derive a human-readable failure_reason for an archived print.
  480. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  481. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  482. no HMS code matches (don't guess — null is honest).
  483. """
  484. if status in ("aborted", "cancelled"):
  485. return "User cancelled"
  486. if status != "failed":
  487. return None
  488. for err in hms_errors or []:
  489. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  490. if short_code in _HMS_FAILURE_REASONS:
  491. return _HMS_FAILURE_REASONS[short_code]
  492. return None
  493. # Track created_by_id for expected prints so the user email can be sent even when
  494. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  495. # {(printer_id, filename): created_by_id}
  496. _expected_print_creators: dict[tuple[int, str], int] = {}
  497. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  498. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  499. # updates for the same printer in quick succession (~30 ms apart, observed in
  500. # the wild on H2D + dual AMS).
  501. #
  502. # Without this serialisation, two concurrent on_ams_change callbacks each read
  503. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  504. # the second commit hits
  505. # IntegrityError: duplicate key value violates unique constraint
  506. # "spool_assignment_printer_id_ams_id_tray_id_key"
  507. # SQLite's WAL serial-write semantics had been silently swallowing the race
  508. # until optional Postgres support landed (asyncpg allows true concurrent
  509. # transactions and surfaces the constraint violation).
  510. #
  511. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  512. # assign) are inside the lock. The Spoolman sync block further down stays
  513. # concurrent because it's network-bound and idempotent.
  514. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  515. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  516. """Return the per-printer assignment lock, creating it on first use."""
  517. lock = _ams_assignment_locks.get(printer_id)
  518. if lock is None:
  519. lock = asyncio.Lock()
  520. _ams_assignment_locks[printer_id] = lock
  521. return lock
  522. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  523. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  524. # tag tuple changes for the slot. Cleared when the slot is reported empty
  525. # so remove + reinsert reliably re-prompts the UI.
  526. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  527. async def _broadcast_unknown_tag(
  528. *,
  529. printer_id: int,
  530. ams_id: int,
  531. tray_id: int,
  532. tag_uid: str,
  533. tray_uuid: str,
  534. tray_type: str | None = None,
  535. tray_color: str | None = None,
  536. tray_sub_brands: str | None = None,
  537. tray_count: int | None = None,
  538. ) -> None:
  539. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  540. _logger = logging.getLogger(__name__)
  541. slot_key = (ams_id, tray_id)
  542. tag_key = (tag_uid or "", tray_uuid or "")
  543. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  544. if per_printer.get(slot_key) == tag_key:
  545. _logger.debug(
  546. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  547. printer_id,
  548. ams_id,
  549. tray_id,
  550. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  551. )
  552. return
  553. _logger.info(
  554. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  555. printer_id,
  556. ams_id,
  557. tray_id,
  558. tray_type,
  559. tray_color,
  560. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  561. )
  562. # Broadcast first; only commit the dedup if the WS write succeeds.
  563. # If broadcast raises, the next MQTT push retries instead of being
  564. # permanently silenced by a poisoned dedup entry.
  565. await ws_manager.broadcast(
  566. {
  567. "type": "unknown_tag",
  568. "printer_id": printer_id,
  569. "ams_id": ams_id,
  570. "tray_id": tray_id,
  571. "tag_uid": tag_uid,
  572. "tray_uuid": tray_uuid,
  573. "tray_type": tray_type,
  574. "tray_color": tray_color,
  575. "tray_sub_brands": tray_sub_brands,
  576. "tray_count": tray_count,
  577. }
  578. )
  579. per_printer[slot_key] = tag_key
  580. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  581. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  582. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  583. if per_printer is None:
  584. return
  585. per_printer.pop((ams_id, tray_id), None)
  586. # TTL for expected-print entries: evict registrations older than this to prevent
  587. # unbounded growth when a print is registered but never starts (e.g. printer
  588. # disconnect, app restart, print started from the printer panel).
  589. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  590. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  591. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  592. # Cleanup loop interval
  593. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  594. _expected_prints_cleanup_task: asyncio.Task | None = None
  595. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  596. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  597. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  598. possible_keys: list[tuple[int, str]] = []
  599. filename = (state.gcode_file or state.current_print or "").strip()
  600. subtask_name = (state.subtask_name or "").strip()
  601. if subtask_name:
  602. possible_keys.append((printer_id, subtask_name))
  603. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  604. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  605. if filename:
  606. base_name = filename.rsplit("/", 1)[-1]
  607. if base_name.endswith(".gcode.3mf"):
  608. root_name = base_name[: -len(".gcode.3mf")]
  609. possible_keys.append((printer_id, root_name))
  610. possible_keys.append((printer_id, base_name))
  611. possible_keys.append((printer_id, f"{root_name}.gcode"))
  612. possible_keys.append((printer_id, f"{root_name}.3mf"))
  613. elif base_name.endswith(".3mf"):
  614. root_name = base_name[: -len(".3mf")]
  615. possible_keys.append((printer_id, root_name))
  616. possible_keys.append((printer_id, base_name))
  617. elif base_name.endswith(".gcode"):
  618. root_name = base_name[: -len(".gcode")]
  619. possible_keys.append((printer_id, root_name))
  620. possible_keys.append((printer_id, f"{root_name}.3mf"))
  621. possible_keys.append((printer_id, base_name))
  622. else:
  623. possible_keys.append((printer_id, base_name))
  624. possible_keys.append((printer_id, f"{base_name}.3mf"))
  625. return possible_keys
  626. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  627. """Check the cheap, process-local print ownership signals."""
  628. if printer_manager.get_current_print_user(printer_id):
  629. return True
  630. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  631. async def _is_printer_kill_switch_enabled_cached() -> bool:
  632. """Return the kill-switch setting without querying on every MQTT frame."""
  633. global _kill_switch_setting_cache
  634. now = time.monotonic()
  635. if _kill_switch_setting_cache is not None:
  636. enabled, expires_at = _kill_switch_setting_cache
  637. if now < expires_at:
  638. return enabled
  639. async with async_session() as db:
  640. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  641. enabled = await is_printer_kill_switch_enabled(db)
  642. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  643. return enabled
  644. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  645. """Resolve whether the current print was started by Bambuddy.
  646. ``None`` means identity is not yet safe to decide. The kill switch must
  647. defer in that case: stopping a print is irreversible, and the first status
  648. frames after a restart may arrive before all subtask fields are populated.
  649. """
  650. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  651. return True
  652. possible_keys = _build_status_print_keys(printer_id, state)
  653. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  654. # is on disk. subtask_id is minted per print and pins the answer to the job
  655. # actually running, rather than to an unrelated one that reuses a filename.
  656. raw_subtask_id = getattr(state, "subtask_id", None)
  657. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  658. if subtask_id in ("", "0"):
  659. return None
  660. from backend.app.models.archive import PrintArchive
  661. result = await db.execute(
  662. select(PrintArchive)
  663. .where(
  664. PrintArchive.printer_id == printer_id,
  665. PrintArchive.status == "printing",
  666. PrintArchive.subtask_id == subtask_id,
  667. )
  668. .order_by(PrintArchive.created_at.desc())
  669. .limit(1)
  670. )
  671. archive = result.scalar_one_or_none()
  672. # An archive row on its own proves nothing: `on_print_start` archives every
  673. # print it observes, including ones started from Bambu Studio or Handy, and
  674. # stamps them with the same status and subtask_id. Authorizing on its mere
  675. # existence would disable the kill switch the moment the 3MF finishes
  676. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  677. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  678. # (carried over from the queue item that started it).
  679. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  680. # Rehydrate the fast in-memory path for subsequent status frames. Include
  681. # both the archive filename and every normalized key reported by MQTT.
  682. _active_prints[(printer_id, archive.filename)] = archive.id
  683. for key in possible_keys:
  684. _active_prints[key] = archive.id
  685. return True
  686. # No dispatch marker. Before calling this someone else's print, check whether
  687. # Bambuddy has a job of its own running on this printer: a library-file
  688. # dispatch has no archive at send time, and an archive created seconds later
  689. # by `on_print_start` carries neither marker. The queue row, which the
  690. # scheduler commits to status="printing" before the MQTT send, is the one
  691. # durable record every Bambuddy print has. It cannot be tied to this
  692. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  693. # print is irreversible, and refusing to act costs nothing but a log line.
  694. from backend.app.models.print_queue import PrintQueueItem
  695. dispatched_here = await db.scalar(
  696. select(PrintQueueItem.id)
  697. .where(
  698. PrintQueueItem.printer_id == printer_id,
  699. PrintQueueItem.status == "printing",
  700. )
  701. .limit(1)
  702. )
  703. if dispatched_here is not None:
  704. return None
  705. return False
  706. async def _send_kill_switch_provider_notification(
  707. printer_id: int,
  708. printer_name: str,
  709. data: dict,
  710. ) -> bool:
  711. """Send the immediate print-stopped provider notification.
  712. Returning a success flag lets the normal MQTT completion path retry when
  713. this early notification could not be delivered.
  714. """
  715. logger = logging.getLogger(__name__)
  716. try:
  717. async with async_session() as db:
  718. await notification_service.on_print_complete(
  719. printer_id,
  720. printer_name,
  721. "stopped",
  722. data,
  723. db,
  724. )
  725. return True
  726. except Exception as e:
  727. logger.warning(
  728. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  729. printer_id,
  730. e,
  731. )
  732. return False
  733. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  734. """Wait for an immediate kill-switch notification, if one was scheduled."""
  735. if task is None:
  736. return False
  737. try:
  738. return await task
  739. except Exception as e:
  740. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  741. return False
  742. async def _get_plug_energy(plug, db) -> dict | None:
  743. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  744. For HA plugs, configures the service with current settings from DB.
  745. For MQTT plugs, returns data from the subscription service.
  746. For REST plugs, polls the status URL with JSON path extraction.
  747. """
  748. if plug.plug_type == "homeassistant":
  749. from backend.app.api.routes.settings import get_homeassistant_settings
  750. ha_settings = await get_homeassistant_settings(db)
  751. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  752. return await homeassistant_service.get_energy(plug)
  753. elif plug.plug_type == "mqtt":
  754. # MQTT plugs report "today" energy, not lifetime total
  755. # For per-print tracking, we use "today" as the counter (resets at midnight)
  756. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  757. if mqtt_data:
  758. return {
  759. "power": mqtt_data.power,
  760. "today": mqtt_data.energy,
  761. "total": mqtt_data.energy, # Use today as total for per-print calculations
  762. }
  763. return None
  764. elif plug.plug_type == "rest":
  765. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  766. return await rest_smart_plug_service.get_energy(plug)
  767. else:
  768. return await tasmota_service.get_energy(plug)
  769. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  770. """Capture the smart plug lifetime counter on the archive at print start.
  771. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  772. tracking survives a backend restart mid-print. The print-end handler reads
  773. this value back from the DB and computes the delta against the current
  774. plug counter.
  775. """
  776. _logger = logging.getLogger(__name__)
  777. try:
  778. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  779. plug = plug_result.scalar_one_or_none()
  780. if not plug:
  781. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  782. return False
  783. energy = await _get_plug_energy(plug, db)
  784. if not energy or energy.get("total") is None:
  785. _logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  786. return False
  787. archive.energy_start_kwh = float(energy["total"])
  788. await db.commit()
  789. _logger.info(
  790. "[ENERGY] Recorded starting energy%s for archive %s: %s kWh",
  791. f" ({context})" if context else "",
  792. archive.id,
  793. energy["total"],
  794. )
  795. return True
  796. except Exception as e:
  797. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  798. return False
  799. def register_expected_print(
  800. printer_id: int,
  801. filename: str,
  802. archive_id: int,
  803. ams_mapping: list[int] | None = None,
  804. created_by_id: int | None = None,
  805. cost_center_id: int | None = None,
  806. plate_id: int | None = None,
  807. ):
  808. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  809. # Store with multiple filename variations to catch different naming patterns
  810. _expected_prints[(printer_id, filename)] = archive_id
  811. # Also store without .3mf extension if present
  812. if filename.endswith(".3mf"):
  813. base = filename[:-4]
  814. _expected_prints[(printer_id, base)] = archive_id
  815. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  816. # Store AMS mapping for usage tracking at print completion
  817. if ams_mapping is not None:
  818. _print_ams_mappings[archive_id] = ams_mapping
  819. if cost_center_id is not None:
  820. _print_cost_center_ids[archive_id] = cost_center_id
  821. # Store plate_id for usage tracking when this is a single-plate dispatch from
  822. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  823. # file's filament total to the spool instead of just the printed plate (#1697).
  824. if plate_id is not None:
  825. _print_plate_ids[archive_id] = plate_id
  826. # Store created_by_id so the user start email can be sent even when the archive
  827. # itself has no created_by_id (e.g. library-file-based queue prints)
  828. if created_by_id is not None:
  829. _expected_print_creators[(printer_id, filename)] = created_by_id
  830. if filename.endswith(".3mf"):
  831. base = filename[:-4]
  832. _expected_print_creators[(printer_id, base)] = created_by_id
  833. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  834. # Record registration time for TTL-based eviction
  835. _registered_at = time.monotonic()
  836. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  837. if filename.endswith(".3mf"):
  838. base = filename[:-4]
  839. _expected_print_registered_at[(printer_id, base)] = _registered_at
  840. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  841. logging.getLogger(__name__).info(
  842. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  843. )
  844. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  845. """Undo :func:`register_expected_print` when the print never went out.
  846. Registration has to happen *before* the MQTT print command, because the
  847. printer can report the print before the line after the send executes. So
  848. every path that registers and then fails to send — a cancel winning the
  849. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  850. between — leaves an expectation for a print that will never arrive.
  851. The TTL sweep evicts those after two hours, which is far longer than it
  852. takes a user to react to a failed dispatch by pressing print again: that
  853. reprint would be folded into the *old* archive and take the stale
  854. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  855. Mirrors the sweep's rules, including the one that is easy to get wrong:
  856. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  857. file, so they may only be dropped once no live key still points at that
  858. archive.
  859. """
  860. keys = [(printer_id, filename)]
  861. if filename.endswith(".3mf"):
  862. base = filename[:-4]
  863. keys.append((printer_id, base))
  864. keys.append((printer_id, f"{base}.gcode"))
  865. removed = False
  866. for key in keys:
  867. if _expected_prints.pop(key, None) is not None:
  868. removed = True
  869. _expected_print_creators.pop(key, None)
  870. _expected_print_registered_at.pop(key, None)
  871. if archive_id not in set(_expected_prints.values()):
  872. _print_ams_mappings.pop(archive_id, None)
  873. _print_plate_ids.pop(archive_id, None)
  874. if removed:
  875. logging.getLogger(__name__).info(
  876. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  877. printer_id,
  878. filename,
  879. archive_id,
  880. )
  881. def _compute_run_filament_grams(
  882. status: str,
  883. archive_filament_used_grams: float | None,
  884. progress: float | int | None,
  885. usage_results: list[dict] | None,
  886. ) -> float | None:
  887. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  888. Priority for every status:
  889. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  890. weight delta — same source that drives "Total Consumed" on the
  891. Inventory page, so Stats and Inventory totals stay aligned).
  892. 2. For ``completed``: the slicer estimate (no tracker available, fall
  893. back to the canonical "this print used X" value).
  894. 3. For partial statuses: ``estimate * progress%``.
  895. 4. ``None`` if nothing is known.
  896. """
  897. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  898. if tracked_grams > 0:
  899. return round(tracked_grams, 1)
  900. if status == "completed":
  901. return archive_filament_used_grams
  902. if archive_filament_used_grams:
  903. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  904. if scale > 0:
  905. return round(archive_filament_used_grams * scale, 1)
  906. return None
  907. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  908. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  909. stored_ams_mapping = data.get("ams_mapping")
  910. if not stored_ams_mapping and archive_id:
  911. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  912. return stored_ams_mapping
  913. def _get_start_plate_id(archive_id: int | None) -> int | None:
  914. """Resolve plate_id for print start without consuming stored direct-Print state.
  915. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  916. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  917. read it back at print-start without popping (the entry is popped on print
  918. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  919. """
  920. if archive_id is None:
  921. return None
  922. return _print_plate_ids.get(archive_id)
  923. def _partial_progress_scale(progress: int | float | None) -> float:
  924. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  925. Used by every site that multiplies a "would-have-used" slicer estimate
  926. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  927. so the three sites in ``_background_notifications`` (and the per-plate
  928. override helper) can't drift apart on the coercion shape.
  929. """
  930. return max(0.0, min((progress or 0) / 100.0, 1.0))
  931. def _scope_notification_archive_data_to_plate(
  932. archive_data: dict,
  933. archive_file_path: str | None,
  934. plate_id: int | None,
  935. print_status: str,
  936. progress: int | float | None,
  937. base_dir: Path,
  938. ) -> dict:
  939. """Override summed-across-plates totals in ``archive_data`` with the values
  940. for ``plate_id`` so the completion notification reports what was actually
  941. printed, not the whole project (#1785).
  942. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  943. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  944. the archive card's "whole project" headline, wrong for the completion
  945. notification of a single-plate print. The queue UI already re-reads the
  946. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  947. notification payload (filament grams, time estimate, per-slot breakdown).
  948. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  949. no per-plate values — in every fail case the original ``archive_data`` is
  950. returned unchanged so the notification still sends.
  951. """
  952. if plate_id is None or not archive_file_path:
  953. return archive_data
  954. from backend.app.utils.threemf_tools import (
  955. extract_filament_usage_from_3mf,
  956. extract_print_time_from_3mf,
  957. )
  958. archive_path = base_dir / archive_file_path
  959. if not archive_path.exists():
  960. return archive_data
  961. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  962. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  963. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  964. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  965. if plate_time:
  966. archive_data["print_time_seconds"] = plate_time
  967. # Gate both the grams headline AND the per-slot breakdown on the same
  968. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  969. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  970. # to the project-level grams the archive columns already provide rather
  971. # than ship a project-level headline next to an all-zero per-plate
  972. # breakdown.
  973. if plate_grams > 0:
  974. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  975. archive_data["filament_slots"] = [
  976. {
  977. "slot_id": s.get("slot_id"),
  978. "used_g": round((s.get("used_g") or 0) * scale, 1),
  979. "type": s.get("type", ""),
  980. "color": s.get("color", ""),
  981. }
  982. for s in plate_slots
  983. ]
  984. return archive_data
  985. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  986. """Best-effort filament metadata from the MQTT print-start snapshot.
  987. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  988. file during print, see #1533) so the fallback PrintArchive still has
  989. enough filament info to support the inventory views and AMS-expansion
  990. planning the operator opens it for. Returns a dict with optional
  991. ``filament_type`` and ``filament_color`` keys in the same
  992. comma-separated format the 3MF extractor produces, so the rest of the
  993. codebase treats the fallback archive identically to a normal one.
  994. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  995. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  996. entries). When supplied, only the slots actually consumed by this
  997. print contribute. Without it the function falls back to every loaded
  998. AMS slot — less accurate but still useful.
  999. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1000. that the unit tests pass directly, AND the on_print_start callback
  1001. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1002. bambu_mqtt service hands to main.py at runtime. The original
  1003. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1004. handled the inner shape and silently returned ``{}`` for every real
  1005. print start, leaving fallback archives' filament fields NULL — the
  1006. exact regression the fix was meant to close. Reported with a log
  1007. proving the AMS state was right there at
  1008. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1009. """
  1010. result: dict[str, str] = {}
  1011. # Look at the on_print_start wrapper first, then the inner shape.
  1012. raw_data = (data or {}).get("raw_data")
  1013. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1014. if not isinstance(ams_root, dict):
  1015. ams_root = (data or {}).get("ams") or {}
  1016. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1017. if not isinstance(ams_units, list) or not ams_units:
  1018. return result
  1019. # Map global tray id (unit * 4 + tray) → (type, color).
  1020. loaded: dict[int, tuple[str, str]] = {}
  1021. for unit in ams_units:
  1022. if not isinstance(unit, dict):
  1023. continue
  1024. try:
  1025. unit_id = int(unit.get("id", 0))
  1026. except (TypeError, ValueError):
  1027. continue
  1028. for tray in unit.get("tray") or []:
  1029. if not isinstance(tray, dict):
  1030. continue
  1031. try:
  1032. tray_id = int(tray.get("id", 0))
  1033. except (TypeError, ValueError):
  1034. continue
  1035. ttype = (tray.get("tray_type") or "").strip()
  1036. tcolor = (tray.get("tray_color") or "").strip().upper()
  1037. if not ttype:
  1038. continue # Empty / unloaded slot.
  1039. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1040. if not loaded:
  1041. return result
  1042. if ams_mapping:
  1043. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1044. filaments = [loaded[g] for g in used_ids if g in loaded]
  1045. if not filaments:
  1046. return result # Mapping points entirely at slots we have no data for.
  1047. else:
  1048. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1049. types_joined = ",".join(f[0] for f in filaments)
  1050. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1051. # Column limits per backend/app/models/archive.py: filament_type=50,
  1052. # filament_color=200.
  1053. if types_joined:
  1054. result["filament_type"] = types_joined[:50]
  1055. if colors_joined:
  1056. result["filament_color"] = colors_joined[:200]
  1057. return result
  1058. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1059. """Start a layer-timelapse session for *archive_id* when the printer has
  1060. an external camera configured. Returns True if a session was started.
  1061. Three call sites in on_print_start (expected-archive promotion, fallback
  1062. archive creation, fresh-archive creation) used to inline this same
  1063. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1064. on the first pass). Centralising the conditional + call here makes the
  1065. contract testable in isolation and keeps the three sites locked in step.
  1066. """
  1067. if not (printer.external_camera_enabled and printer.external_camera_url):
  1068. return False
  1069. from backend.app.services.layer_timelapse import start_session
  1070. start_session(
  1071. printer_id,
  1072. archive_id,
  1073. printer.external_camera_url,
  1074. printer.external_camera_type or "mjpeg",
  1075. snapshot_url=printer.external_camera_snapshot_url,
  1076. rotation=getattr(printer, "camera_rotation", 0),
  1077. )
  1078. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1079. return True
  1080. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1081. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1082. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity.
  1083. The short code used for the hms_errors.py lookup table is 'MMMM_EEEE' — module
  1084. from attr bits 16-31, error from the numeric part of code. Falls back to the raw
  1085. short code when no description is on file. Returns None for an empty list so
  1086. callers can leave error_message unset.
  1087. """
  1088. if not hms_errors:
  1089. return None
  1090. from backend.app.services.hms_errors import get_error_description
  1091. parts: list[str] = []
  1092. for err in hms_errors:
  1093. try:
  1094. code_str = str(err.get("code", "")).replace("0x", "")
  1095. error_num = int(code_str, 16) if code_str else 0
  1096. module_num = (int(err.get("attr", 0)) >> 16) & 0xFFFF
  1097. short_code = f"{module_num:04X}_{error_num:04X}"
  1098. except (TypeError, ValueError):
  1099. continue
  1100. description = get_error_description(short_code)
  1101. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  1102. return "; ".join(parts) if parts else None
  1103. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1104. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1105. print completes successfully. Gated to status=='completed': failed, cancelled
  1106. and aborted prints do not count as usage. Caller is responsible for committing
  1107. the session. No-op when the queue item has no linked library file (e.g. reprints
  1108. from an archive). See #1008."""
  1109. if queue_status != "completed" or item.library_file_id is None:
  1110. return
  1111. from backend.app.models.library import LibraryFile
  1112. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1113. if lib_file is None:
  1114. return
  1115. lib_file.print_count = (lib_file.print_count or 0) + 1
  1116. lib_file.last_printed_at = datetime.now(timezone.utc)
  1117. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1118. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1119. When on_print_complete fires with status 'failed' for a printer in this set we
  1120. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1121. rather than a 'print failed' notification.
  1122. """
  1123. _user_stopped_printers.add(printer_id)
  1124. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1125. _last_status_broadcast: dict[int, str] = {}
  1126. # Track printers where we've updated nozzle_count
  1127. _nozzle_count_updated: set[int] = set()
  1128. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1129. """Wait the debounce window then fire `on_printer_offline` if the printer
  1130. is still offline.
  1131. Scheduled by `on_printer_status_change` on the connected → disconnected
  1132. edge (#1752). Cancelled by the same handler if the printer reconnects
  1133. before the window elapses, so a single MQTT blip + recovery doesn't
  1134. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1135. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1136. route through the same status-change callback, so this covers both.
  1137. """
  1138. logger = logging.getLogger(__name__)
  1139. try:
  1140. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1141. still_offline = not printer_manager.is_connected(printer_id)
  1142. logger.info(
  1143. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1144. printer_id,
  1145. still_offline,
  1146. )
  1147. if not still_offline:
  1148. return
  1149. async with async_session() as db:
  1150. from backend.app.models.printer import Printer
  1151. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1152. printer = result.scalar_one_or_none()
  1153. if not printer:
  1154. logger.warning(
  1155. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1156. printer_id,
  1157. )
  1158. return
  1159. logger.info(
  1160. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1161. printer_id,
  1162. printer.name,
  1163. )
  1164. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1165. except asyncio.CancelledError:
  1166. raise
  1167. except Exception as e:
  1168. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1169. finally:
  1170. _printer_offline_notify_tasks.pop(printer_id, None)
  1171. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1172. """Handle printer status changes - broadcast via WebSocket."""
  1173. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1174. # transitions disconnected → connected — which covers both Bambuddy
  1175. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1176. # `reconcile_stale_active_prints` exactly once for this connection so
  1177. # any archive still in `status="printing"` that can't actually be
  1178. # running anymore (printer IDLE / different subtask / empty subtask)
  1179. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1180. # finished during a disconnect window + a smart-plug power cycle
  1181. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1182. # next boot. Reconciliation runs concurrently — it must not block the
  1183. # WebSocket dedup / broadcast logic below, and the connected edge is
  1184. # marked True BEFORE the await so concurrent status updates inside
  1185. # the same connection don't re-trigger reconciliation.
  1186. #
  1187. # Wait for a real push_status before reconciling (#1679): MQTT
  1188. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1189. # the connection, BEFORE `_request_push_all` round-trips. At that
  1190. # instant the `PrinterState` is still on construction defaults — most
  1191. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1192. # If reconcile spawns here, every in-flight archive falls through to
  1193. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1194. # creates a duplicate archive on the real PRINT COMPLETE and
  1195. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1196. # keeps the #1542 mechanism intact: once the first real push_status
  1197. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1198. # fires again with the flag still False — reconcile then runs against
  1199. # actual evidence.
  1200. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1201. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1202. _printer_reconciled_since_connect[printer_id] = True
  1203. spawn_background_task(
  1204. reconcile_stale_active_prints(printer_id),
  1205. name=f"reconcile-stale-prints-{printer_id}",
  1206. )
  1207. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1208. # Re-arm so the next reconnect triggers reconciliation again.
  1209. _printer_reconciled_since_connect[printer_id] = False
  1210. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1211. # connected → disconnected. The "back online" channel is already covered
  1212. # by the print-failure notification (firmware reports gcode_state=FAILED
  1213. # on reconnect of an interrupted print), so we don't add a symmetric
  1214. # online event here.
  1215. prev_connected = _printer_last_connected.get(printer_id)
  1216. _printer_last_connected[printer_id] = state.connected
  1217. if prev_connected is True and not state.connected:
  1218. existing = _printer_offline_notify_tasks.get(printer_id)
  1219. if existing is None or existing.done():
  1220. logging.getLogger(__name__).info(
  1221. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1222. printer_id,
  1223. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1224. )
  1225. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1226. _maybe_notify_printer_offline(printer_id),
  1227. name=f"printer-offline-notify-{printer_id}",
  1228. )
  1229. elif state.connected:
  1230. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1231. if pending is not None and not pending.done():
  1232. logging.getLogger(__name__).info(
  1233. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1234. printer_id,
  1235. )
  1236. pending.cancel()
  1237. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1238. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1239. temps = state.temperatures or {}
  1240. nozzle_temp = round(temps.get("nozzle", 0))
  1241. bed_temp = round(temps.get("bed", 0))
  1242. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1243. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1244. # Auto-detect dual-nozzle printers from MQTT temperature data
  1245. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1246. _nozzle_count_updated.add(printer_id)
  1247. # Update nozzle_count in database
  1248. async with async_session() as db:
  1249. from backend.app.models.printer import Printer
  1250. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1251. printer = result.scalar_one_or_none()
  1252. if printer and printer.nozzle_count != 2:
  1253. printer.nozzle_count = 2
  1254. await db.commit()
  1255. logging.getLogger(__name__).info(
  1256. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1257. )
  1258. # Include target temps for heating phase detection
  1259. bed_target = round(temps.get("bed_target", 0))
  1260. nozzle_target = round(temps.get("nozzle_target", 0))
  1261. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1262. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1263. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  1264. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  1265. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1266. #
  1267. # The filament identity fields are here because Configure Slot writes
  1268. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1269. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1270. # matched, this function returned before broadcasting, and the card kept
  1271. # showing the old filament until the 30s fallback poll or a page reload —
  1272. # even though the configure route asks the printer for a fresh pushall and
  1273. # that push does carry the new values. Reset always worked, because it
  1274. # clears tray_type.
  1275. #
  1276. # These fields only change when someone configures a slot or swaps a spool,
  1277. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1278. ams_tray_key = (
  1279. tuple(
  1280. (
  1281. t.get("id"),
  1282. t.get("tray_type", ""),
  1283. t.get("state"),
  1284. t.get("tray_color", ""),
  1285. t.get("tray_info_idx", ""),
  1286. t.get("tray_sub_brands", ""),
  1287. t.get("cali_idx"),
  1288. )
  1289. for a in (state.raw_data.get("ams") or [])
  1290. for t in a.get("tray", [])
  1291. )
  1292. if state.raw_data
  1293. else ()
  1294. )
  1295. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1296. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1297. # in the AMS change-hash (tray fields only, and widening that would fire
  1298. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1299. # screen changed no key at all and the card's inlet badges sat stale until a
  1300. # reload. Like the filament-backup flag, these only move when someone
  1301. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1302. fts_key = (
  1303. state.fila_switch.installed if state.fila_switch else False,
  1304. tuple(sorted(state.ams_switch_inlet.items())),
  1305. )
  1306. status_key = (
  1307. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1308. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1309. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1310. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1311. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1312. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1313. )
  1314. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1315. if not is_active_print:
  1316. _unauthorized_print_kill_sent.discard(printer_id)
  1317. elif printer_id in _unauthorized_print_kill_sent:
  1318. # stop_print() was already sent for this print; avoid all further
  1319. # ownership and settings work until the printer leaves an active state.
  1320. pass
  1321. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1322. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1323. _unauthorized_print_kill_sent.discard(printer_id)
  1324. else:
  1325. kill_switch_enabled = False
  1326. authorization: bool | None = None
  1327. status_logger = logging.getLogger(__name__)
  1328. try:
  1329. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1330. if kill_switch_enabled:
  1331. async with async_session() as db:
  1332. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1333. except Exception as e:
  1334. # Fail safe: a database/reconciliation error must never turn into an
  1335. # irreversible stop of a print whose ownership is still unknown.
  1336. authorization = None
  1337. status_logger.warning(
  1338. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1339. )
  1340. if not kill_switch_enabled or authorization is True:
  1341. _unauthorized_print_kill_sent.discard(printer_id)
  1342. elif authorization is None:
  1343. _unauthorized_print_kill_sent.discard(printer_id)
  1344. status_logger.debug(
  1345. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1346. printer_id,
  1347. )
  1348. else:
  1349. try:
  1350. stopped = printer_manager.stop_print(printer_id)
  1351. if stopped:
  1352. _unauthorized_print_kill_sent.add(printer_id)
  1353. printer_info = printer_manager.get_printer(printer_id)
  1354. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1355. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1356. notification_data = {
  1357. "status": "stopped",
  1358. "filename": state.gcode_file or state.current_print or "",
  1359. "subtask_name": state.subtask_name or "",
  1360. "progress": state.progress,
  1361. "reason": "unauthorized_print",
  1362. }
  1363. status_logger.warning(
  1364. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1365. printer_id,
  1366. state.state,
  1367. )
  1368. try:
  1369. await ws_manager.broadcast(
  1370. {
  1371. "type": "kill_switch_triggered",
  1372. "printer_id": printer_id,
  1373. "printer_name": printer_name,
  1374. "filename": filename,
  1375. "reason": "unauthorized_print",
  1376. }
  1377. )
  1378. except Exception as e:
  1379. status_logger.warning(
  1380. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1381. )
  1382. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1383. if previous_task is not None and not previous_task.done():
  1384. previous_task.cancel()
  1385. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1386. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1387. name=f"kill-switch-notification-{printer_id}",
  1388. )
  1389. else:
  1390. status_logger.warning(
  1391. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1392. printer_id,
  1393. state.state,
  1394. )
  1395. except Exception as e:
  1396. status_logger.warning(
  1397. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1398. )
  1399. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1400. try:
  1401. printer_info = printer_manager.get_printer(printer_id)
  1402. if printer_info:
  1403. await mqtt_relay.on_printer_status(
  1404. printer_id,
  1405. state,
  1406. printer_info.name,
  1407. printer_info.serial_number,
  1408. printer_manager.is_awaiting_plate_clear(printer_id),
  1409. )
  1410. except Exception:
  1411. pass # Don't fail status callback if MQTT fails
  1412. if _last_status_broadcast.get(printer_id) == status_key:
  1413. return # No change, skip WebSocket broadcast
  1414. _last_status_broadcast[printer_id] = status_key
  1415. # Check for progress milestone notifications (25%, 50%, 75%)
  1416. progress = state.progress or 0
  1417. is_printing = state.state in ("RUNNING", "PRINTING")
  1418. if is_printing and progress > 0:
  1419. # Determine which milestone we've reached
  1420. current_milestone = 0
  1421. if progress >= 75:
  1422. current_milestone = 75
  1423. elif progress >= 50:
  1424. current_milestone = 50
  1425. elif progress >= 25:
  1426. current_milestone = 25
  1427. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1428. # If we've crossed a new milestone, send notification
  1429. if current_milestone > last_milestone:
  1430. _last_progress_milestone[printer_id] = current_milestone
  1431. try:
  1432. from backend.app.models.printer import Printer
  1433. # Read the printer in a short session and release the connection
  1434. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1435. # pinned a pooled connection per milestone, per printer (issue #2572).
  1436. async with async_session() as db:
  1437. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1438. printer = result.scalar_one_or_none()
  1439. printer_name = printer.name if printer else f"Printer {printer_id}"
  1440. filename = state.subtask_name or state.gcode_file or "Unknown"
  1441. # remaining_time is in minutes, convert to seconds for notification
  1442. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1443. # Capture camera snapshot for notification image attachment (no DB held).
  1444. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1445. # Notification send needs a session (provider/template lookups).
  1446. async with async_session() as db:
  1447. await notification_service.on_print_progress(
  1448. printer_id,
  1449. printer_name,
  1450. filename,
  1451. current_milestone,
  1452. db,
  1453. remaining_time_seconds,
  1454. image_data=image_data,
  1455. )
  1456. except Exception as e:
  1457. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1458. elif progress < 5:
  1459. # Reset milestone tracking when print restarts or new print begins
  1460. _last_progress_milestone[printer_id] = 0
  1461. _first_layer_notified[printer_id] = False
  1462. # HMS error codes that should not trigger notifications even though they
  1463. # have known descriptions (e.g. user-initiated actions, not real errors).
  1464. _HMS_NOTIFICATION_SUPPRESS = {
  1465. "0500_400E", # Printing was cancelled (user action, not an error)
  1466. }
  1467. # Check for new HMS errors and send notifications
  1468. current_hms_errors = getattr(state, "hms_errors", []) or []
  1469. if current_hms_errors:
  1470. # Build set of current error codes (using attr for uniqueness)
  1471. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1472. previously_notified = _notified_hms_errors.get(printer_id, set())
  1473. # Find new errors that haven't been notified yet
  1474. new_error_codes = current_error_codes - previously_notified
  1475. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1476. _notified_hms_errors[printer_id] = current_error_codes
  1477. _hms_last_seen[printer_id] = time.time()
  1478. if new_error_codes:
  1479. # Get the actual new errors for the notification
  1480. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1481. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1482. try:
  1483. from backend.app.models.printer import Printer
  1484. # Read the printer in a short session and release the connection
  1485. # BEFORE the ~15s camera snapshot below (issue #2572).
  1486. async with async_session() as db:
  1487. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1488. printer = result.scalar_one_or_none()
  1489. printer_name = printer.name if printer else f"Printer {printer_id}"
  1490. # Format error details for notification
  1491. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1492. module_names = {
  1493. 0x03: "Print/Task",
  1494. 0x05: "Nozzle/Extruder",
  1495. 0x07: "AMS/Filament",
  1496. 0x0C: "Motion Controller",
  1497. 0x12: "Chamber",
  1498. }
  1499. from backend.app.services.hms_errors import get_error_description
  1500. # Capture camera snapshot once for all error notifications (no DB held).
  1501. error_image_data = await _capture_snapshot_for_notification(
  1502. printer_id, printer, logging.getLogger(__name__)
  1503. )
  1504. # Notification sends need a session (provider/template lookups).
  1505. async with async_session() as db:
  1506. sent_count = 0
  1507. for error in new_errors:
  1508. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1509. # Build short code like "0700_8010"
  1510. # Mask to 16 bits to handle printers that send larger values
  1511. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1512. error_code_masked = error_code_int & 0xFFFF
  1513. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1514. # Only notify for errors with known descriptions — printers
  1515. # send many undocumented/phantom codes that aren't real errors.
  1516. description = get_error_description(short_code)
  1517. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1518. continue
  1519. error_type = f"{module_name} Error"
  1520. error_detail = description
  1521. await notification_service.on_printer_error(
  1522. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1523. )
  1524. sent_count += 1
  1525. if sent_count:
  1526. logging.getLogger(__name__).info(
  1527. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1528. )
  1529. # Also publish to MQTT relay (no DB).
  1530. printer_info = printer_manager.get_printer(printer_id)
  1531. if printer_info:
  1532. errors_data = [
  1533. {
  1534. "code": e.code,
  1535. "attr": e.attr,
  1536. "module": e.module,
  1537. "severity": e.severity,
  1538. }
  1539. for e in new_errors
  1540. ]
  1541. await mqtt_relay.on_printer_error(
  1542. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1543. )
  1544. except Exception as e:
  1545. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1546. else:
  1547. # No HMS errors — only clear tracking after a grace period to prevent
  1548. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1549. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1550. # on/off every few seconds as conditions fluctuate around thresholds.
  1551. if printer_id in _notified_hms_errors:
  1552. last_seen = _hms_last_seen.get(printer_id, 0)
  1553. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1554. _notified_hms_errors.pop(printer_id, None)
  1555. _hms_last_seen.pop(printer_id, None)
  1556. await ws_manager.send_printer_status(
  1557. printer_id,
  1558. printer_state_to_dict(
  1559. state,
  1560. printer_id,
  1561. printer_manager.get_model(printer_id),
  1562. printer_manager.get_drying_targets(printer_id),
  1563. ),
  1564. )
  1565. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1566. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1567. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1568. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1569. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1570. K-profiles are per-nozzle and the printer's calibration table is numbered
  1571. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1572. switch's other inlet therefore silently invalidates every configured slot in
  1573. it: the index stays put and now resolves against the other nozzle's table.
  1574. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1575. and 0.020 on the right kept the left profile after the move, and a manual
  1576. RFID re-read only re-asserted the same wrong one.
  1577. Configuring a slot is a deliberate preparation step, so this re-selects
  1578. rather than re-configures: only the calibration binding moves, and only for
  1579. slots whose spool already has a stored profile for the new nozzle. A slot
  1580. Bambuddy knows nothing about is left exactly as the operator left it.
  1581. """
  1582. logger = logging.getLogger(__name__)
  1583. target_extruder = extruder_for_inlet(inlet)
  1584. if target_extruder is None:
  1585. return
  1586. client = printer_manager.get_client(printer_id)
  1587. state = printer_manager.get_status(printer_id)
  1588. if not client or not state or not state.raw_data:
  1589. return
  1590. nozzle_diameter = "0.4"
  1591. if state.nozzles and state.nozzles[0].nozzle_diameter:
  1592. nozzle_diameter = state.nozzles[0].nozzle_diameter
  1593. ams_raw = state.raw_data.get("ams")
  1594. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1595. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1596. if not unit:
  1597. return
  1598. try:
  1599. async with async_session() as db:
  1600. for tray in unit.get("tray", []):
  1601. tray_id = int(tray.get("id", -1))
  1602. if tray_id < 0 or not tray.get("tray_type"):
  1603. continue
  1604. current_idx = tray.get("cali_idx")
  1605. profile = await find_slot_kprofile_for_extruder(
  1606. db, printer_id, ams_id, tray_id, target_extruder, nozzle_diameter
  1607. )
  1608. if profile is None or profile.cali_idx is None:
  1609. continue
  1610. if current_idx == profile.cali_idx:
  1611. continue # Already on the right one.
  1612. logger.info(
  1613. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1614. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1615. printer_id,
  1616. ams_id,
  1617. tray_id,
  1618. inlet,
  1619. target_extruder,
  1620. profile.name,
  1621. current_idx,
  1622. profile.cali_idx,
  1623. profile.k_value,
  1624. )
  1625. client.extrusion_cali_sel(
  1626. ams_id=ams_id,
  1627. tray_id=tray_id,
  1628. cali_idx=profile.cali_idx,
  1629. filament_id=profile.filament_id or tray.get("tray_info_idx", "") or "",
  1630. nozzle_diameter=nozzle_diameter,
  1631. )
  1632. except Exception as e:
  1633. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1634. async def on_ams_change(printer_id: int, ams_data: list):
  1635. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1636. logger = logging.getLogger(__name__)
  1637. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1638. # on_print_complete may pop _active_sessions during our awaits (#880).
  1639. from backend.app.services.usage_tracker import _active_sessions
  1640. _print_active = printer_id in _active_sessions
  1641. # A slot that reports empty while a print is running is a filament runout,
  1642. # not a spool swap: the spool is still physically in the AMS, just
  1643. # consumed. Dropping either inventory backend's slot link there loses the
  1644. # only record of which spool fed the print, so the completion path can't
  1645. # charge the runout segment to anything. Both cleanup passes below consult
  1646. # this; computed once, up front, so neither depends on the other having run.
  1647. _unlink_state = printer_manager.get_status(printer_id)
  1648. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  1649. # MQTT relay - publish AMS change
  1650. try:
  1651. printer_info = printer_manager.get_printer(printer_id)
  1652. if printer_info:
  1653. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1654. except Exception:
  1655. pass # Don't fail AMS callback if MQTT fails
  1656. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1657. # This ensures frontend gets immediate updates when AMS slots are configured
  1658. try:
  1659. state = printer_manager.get_status(printer_id)
  1660. if state:
  1661. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1662. await ws_manager.send_printer_status(
  1663. printer_id,
  1664. printer_state_to_dict(
  1665. state,
  1666. printer_id,
  1667. printer_manager.get_model(printer_id),
  1668. printer_manager.get_drying_targets(printer_id),
  1669. ),
  1670. )
  1671. except Exception as e:
  1672. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1673. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1674. # Auto-unlink spool assignments with stale fingerprints
  1675. try:
  1676. async with async_session() as db:
  1677. from sqlalchemy.orm import selectinload
  1678. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1679. from backend.app.models.spool import Spool as _Spool
  1680. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1681. result = await db.execute(
  1682. select(SA)
  1683. .where(SA.printer_id == printer_id)
  1684. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1685. )
  1686. # ``printing_now`` (top of this function) keeps a runout from
  1687. # unlinking the spool that fed the print — the next idle-time pass
  1688. # unlinks it if the user really did take it out.
  1689. stale = []
  1690. for assignment in result.scalars().all():
  1691. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1692. if assignment.ams_id == 255:
  1693. ps = printer_manager.get_status(printer_id)
  1694. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1695. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1696. current_tray = None
  1697. for vt in vt_tray_raw:
  1698. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1699. current_tray = vt
  1700. break
  1701. if not current_tray:
  1702. # vt_tray data may not have arrived yet — keep assignment
  1703. continue
  1704. else:
  1705. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1706. if not current_tray:
  1707. if printing_now:
  1708. logger.info(
  1709. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1710. assignment.spool_id,
  1711. assignment.ams_id,
  1712. assignment.tray_id,
  1713. )
  1714. continue
  1715. logger.info(
  1716. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1717. assignment.spool_id,
  1718. assignment.ams_id,
  1719. assignment.tray_id,
  1720. )
  1721. stale.append(assignment) # Slot empty
  1722. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1723. # A Bambu Lab spool is in this slot — check if it's the same spool
  1724. # that's currently assigned. If yes, keep the assignment (avoids
  1725. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1726. # the printer's filament preset on every startup).
  1727. tray_uuid = current_tray.get("tray_uuid", "")
  1728. tag_uid = current_tray.get("tag_uid", "")
  1729. spool = assignment.spool
  1730. spool_matches = False
  1731. if spool:
  1732. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1733. spool.tag_uid
  1734. and tag_uid
  1735. and tag_uid != "0000000000000000"
  1736. and spool.tag_uid.upper() == tag_uid.upper()
  1737. ):
  1738. spool_matches = True
  1739. if spool_matches:
  1740. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1741. cur_color = current_tray.get("tray_color", "")
  1742. cur_type = current_tray.get("tray_type", "")
  1743. fp_color = assignment.fingerprint_color or ""
  1744. fp_type = assignment.fingerprint_type or ""
  1745. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1746. assignment.fingerprint_color = cur_color
  1747. assignment.fingerprint_type = cur_type
  1748. logger.debug(
  1749. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1750. assignment.spool_id,
  1751. assignment.ams_id,
  1752. assignment.tray_id,
  1753. )
  1754. continue
  1755. # Different BL spool or unrecognized — unlink so auto-assign can match
  1756. logger.info(
  1757. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1758. assignment.spool_id,
  1759. assignment.ams_id,
  1760. assignment.tray_id,
  1761. tray_uuid,
  1762. )
  1763. stale.append(assignment)
  1764. else:
  1765. cur_color = current_tray.get("tray_color", "")
  1766. cur_type = current_tray.get("tray_type", "")
  1767. cur_state = current_tray.get("state")
  1768. fp_color = assignment.fingerprint_color or ""
  1769. fp_type = assignment.fingerprint_type or ""
  1770. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1771. # the slot was empty when the user pre-assigned via SpoolBuddy
  1772. # (the firmware drops ams_filament_setting on empty slots, so
  1773. # MQTT was deferred). The moment any filament gets inserted
  1774. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1775. # reconfigured spool — fire the deferred configuration.
  1776. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1777. # extruder" code) OR, on firmwares that don't use the state
  1778. # enum meaningfully, a non-empty tray_type when state is
  1779. # NOT one of the firmware's explicit empty signals (9, 10).
  1780. # state-only was wrong for firmwares that never set 11 — A1
  1781. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1782. # always report state=3 — so the replay never fired for them
  1783. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1784. # explicit "empty" signals authoritative over any stale
  1785. # tray_type that might survive the relay's auto-clearing.
  1786. loaded = cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1787. if not fp_type.strip() and loaded and assignment.spool:
  1788. try:
  1789. from backend.app.api.routes.inventory import (
  1790. apply_spool_to_slot_via_mqtt,
  1791. )
  1792. await apply_spool_to_slot_via_mqtt(
  1793. db=db,
  1794. current_user=None,
  1795. spool=assignment.spool,
  1796. printer_id=printer_id,
  1797. ams_id=assignment.ams_id,
  1798. tray_id=assignment.tray_id,
  1799. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1800. current_tray_type=cur_type,
  1801. )
  1802. logger.info(
  1803. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1804. assignment.spool_id,
  1805. printer_id,
  1806. assignment.ams_id,
  1807. assignment.tray_id,
  1808. )
  1809. except Exception:
  1810. logger.exception(
  1811. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1812. assignment.spool_id,
  1813. printer_id,
  1814. assignment.ams_id,
  1815. assignment.tray_id,
  1816. )
  1817. assignment.fingerprint_color = cur_color
  1818. assignment.fingerprint_type = cur_type
  1819. continue
  1820. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1821. # Blank tray data mid-print is a runout, not a swap: the
  1822. # firmware clears colour and type when it unloads a spool
  1823. # it just emptied. Unlinking here would erase the record
  1824. # of which spool fed the print so far.
  1825. if printing_now and not cur_color.strip() and not cur_type.strip():
  1826. logger.info(
  1827. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  1828. "(runout?)",
  1829. assignment.spool_id,
  1830. assignment.ams_id,
  1831. assignment.tray_id,
  1832. )
  1833. continue
  1834. # Fingerprint mismatch — but check if tray now matches the
  1835. # assigned spool (e.g. auto-configure changed the tray).
  1836. spool = assignment.spool
  1837. if spool:
  1838. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1839. spool_type = (spool.material or "").upper()
  1840. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  1841. logger.info(
  1842. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  1843. assignment.spool_id,
  1844. assignment.ams_id,
  1845. assignment.tray_id,
  1846. )
  1847. assignment.fingerprint_color = cur_color
  1848. assignment.fingerprint_type = cur_type
  1849. continue
  1850. logger.info(
  1851. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  1852. assignment.spool_id,
  1853. assignment.ams_id,
  1854. assignment.tray_id,
  1855. cur_color,
  1856. cur_type,
  1857. fp_color,
  1858. fp_type,
  1859. spool.rgba if spool else "?",
  1860. spool.material if spool else "?",
  1861. )
  1862. stale.append(assignment) # Spool changed
  1863. # Snapshot slots before delete — ORM attribute access after the
  1864. # commit would refresh against a deleted row.
  1865. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  1866. for a in stale:
  1867. await db.delete(a)
  1868. if stale:
  1869. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  1870. # Commit any changes (stale deletions and/or fingerprint updates)
  1871. await db.commit()
  1872. # Tell open browsers the assignment is gone (#2575). Only the manual
  1873. # REST assign/unassign endpoints broadcast this event; without it the
  1874. # frontend's spool-assignments cache keeps rendering the unlinked
  1875. # spool on the slot until an unrelated refetch — which reads exactly
  1876. # like "the fix didn't work" (reporter verified: a browser refresh
  1877. # after the swap showed the correct state all along).
  1878. for ams_id, tray_id in unlinked_slots:
  1879. await ws_manager.broadcast(
  1880. {
  1881. "type": "spool_assignment_changed",
  1882. "printer_id": printer_id,
  1883. "ams_id": ams_id,
  1884. "tray_id": tray_id,
  1885. }
  1886. )
  1887. except Exception as e:
  1888. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  1889. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  1890. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  1891. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  1892. # "no existing assignment" for the same (printer, ams, tray) and race to
  1893. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  1894. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  1895. # bug stayed latent there. See _ams_assignment_locks comment for details.
  1896. try:
  1897. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1898. from backend.app.api.routes.settings import get_setting
  1899. from backend.app.models.spool import Spool
  1900. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1901. from backend.app.services.spool_tag_matcher import (
  1902. auto_assign_spool,
  1903. create_spool_from_tray,
  1904. find_matching_untagged_spool,
  1905. get_spool_by_tag,
  1906. is_bambu_tag,
  1907. is_valid_tag,
  1908. link_tag_to_inventory_spool,
  1909. )
  1910. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1911. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  1912. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  1913. if not _spoolman_on or _spoolman_on.lower() != "true":
  1914. for ams_unit in ams_data:
  1915. if not isinstance(ams_unit, dict):
  1916. continue
  1917. ams_id = int(ams_unit.get("id", 0))
  1918. for tray in ams_unit.get("tray", []):
  1919. if not isinstance(tray, dict):
  1920. continue
  1921. tray_id = int(tray.get("id", 0))
  1922. tag_uid = tray.get("tag_uid", "")
  1923. tray_uuid = tray.get("tray_uuid", "")
  1924. tray_info_idx = tray.get("tray_info_idx", "")
  1925. if not tray.get("tray_type"):
  1926. # Slot reported empty — drop any cached unknown-tag
  1927. # broadcast so reinserting the same spool re-prompts.
  1928. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  1929. continue # Empty slot
  1930. # Check if assignment already exists for this slot
  1931. existing = await db.execute(
  1932. select(SA)
  1933. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  1934. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  1935. )
  1936. existing_assignment = existing.scalar_one_or_none()
  1937. if existing_assignment:
  1938. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  1939. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  1940. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  1941. # Skip during active prints: the usage tracker handles deduction
  1942. # precisely via 3MF data on print completion. Without this guard the
  1943. # AMS remain% SET and the usage tracker ADD both fire from the same
  1944. # MQTT message, doubling the deduction (#880).
  1945. if _print_active:
  1946. continue
  1947. remain_raw = tray.get("remain")
  1948. if (
  1949. remain_raw is not None
  1950. and existing_assignment.spool
  1951. and not existing_assignment.spool.weight_locked
  1952. ):
  1953. try:
  1954. remain_val = int(remain_raw)
  1955. except (TypeError, ValueError):
  1956. remain_val = -1
  1957. if 1 <= remain_val <= 100:
  1958. lw = existing_assignment.spool.label_weight or 1000
  1959. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1960. current_used = existing_assignment.spool.weight_used or 0
  1961. if new_used > current_used + 1:
  1962. logger.info(
  1963. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  1964. existing_assignment.spool_id,
  1965. current_used,
  1966. new_used,
  1967. remain_val,
  1968. )
  1969. existing_assignment.spool.weight_used = new_used
  1970. await db.commit()
  1971. # Re-apply stored K-profile when the live tray's
  1972. # cali_idx drifted from the spool's stored profile.
  1973. # This catches "reset slot → re-read" and any other
  1974. # path where the firmware loses the user's K-profile
  1975. # selection while the SpoolAssignment row persists.
  1976. # Per the maintainer's rule: any time a spool tag is
  1977. # identified and matches inventory, the slot must be
  1978. # configured with the spool's stored settings. Without
  1979. # this block the existing-assignment branch only ran
  1980. # weight-sync and let the firmware-default cali_idx win.
  1981. try:
  1982. spool = existing_assignment.spool
  1983. if (
  1984. spool is not None
  1985. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  1986. and spool.k_profiles
  1987. ):
  1988. state = printer_manager.get_status(printer_id)
  1989. nozzle_diameter = "0.4"
  1990. if state and state.nozzles:
  1991. nd = state.nozzles[0].nozzle_diameter
  1992. if nd:
  1993. nozzle_diameter = nd
  1994. slot_extruder = resolve_slot_extruder(
  1995. ams_id,
  1996. tray_id,
  1997. state.ams_extruder_map if state else None,
  1998. state.ams_switch_inlet if state else None,
  1999. )
  2000. # Prefer exact extruder match, fall back to
  2001. # extruder-agnostic kp for the same printer +
  2002. # nozzle. Avoids hard-skipping when the AMS is
  2003. # mapped differently than at calibration time.
  2004. matching_kp = None
  2005. fallback_kp = None
  2006. for kp in spool.k_profiles:
  2007. if (
  2008. kp.printer_id != printer_id
  2009. or kp.nozzle_diameter != nozzle_diameter
  2010. or kp.cali_idx is None
  2011. ):
  2012. continue
  2013. if (
  2014. slot_extruder is not None
  2015. and kp.extruder is not None
  2016. and kp.extruder == slot_extruder
  2017. ):
  2018. matching_kp = kp
  2019. break
  2020. if fallback_kp is None:
  2021. fallback_kp = kp
  2022. chosen_kp = matching_kp or fallback_kp
  2023. if chosen_kp is not None:
  2024. live_cali_idx = tray.get("cali_idx")
  2025. # Only fire MQTT when the printer's live
  2026. # cali_idx differs from the stored value.
  2027. # Avoids spamming the broker on every
  2028. # MQTT push during steady-state operation.
  2029. if live_cali_idx != chosen_kp.cali_idx:
  2030. client = printer_manager.get_client(printer_id)
  2031. if client:
  2032. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2033. client.extrusion_cali_sel(
  2034. ams_id=ams_id,
  2035. tray_id=tray_id,
  2036. cali_idx=chosen_kp.cali_idx,
  2037. filament_id=cali_filament_id,
  2038. nozzle_diameter=nozzle_diameter,
  2039. )
  2040. logger.info(
  2041. "Re-applied K-profile cali_idx=%d for spool %d "
  2042. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2043. chosen_kp.cali_idx,
  2044. spool.id,
  2045. printer_id,
  2046. ams_id,
  2047. tray_id,
  2048. live_cali_idx,
  2049. )
  2050. except Exception:
  2051. logger.exception(
  2052. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2053. printer_id,
  2054. ams_id,
  2055. tray_id,
  2056. )
  2057. continue
  2058. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2059. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2060. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2061. if not spool:
  2062. # Try matching an untagged inventory spool (same material/color)
  2063. spool = await find_matching_untagged_spool(db, tray)
  2064. if spool:
  2065. await link_tag_to_inventory_spool(db, spool, tray)
  2066. elif _auto_add_unknown:
  2067. spool = await create_spool_from_tray(db, tray)
  2068. else:
  2069. # Auto-add disabled: surface the slot so the
  2070. # user can add it manually via the UI.
  2071. await _broadcast_unknown_tag(
  2072. printer_id=printer_id,
  2073. ams_id=ams_id,
  2074. tray_id=tray_id,
  2075. tag_uid=tag_uid,
  2076. tray_uuid=tray_uuid,
  2077. tray_type=tray.get("tray_type"),
  2078. tray_color=tray.get("tray_color"),
  2079. tray_sub_brands=tray.get("tray_sub_brands"),
  2080. tray_count=len(ams_unit.get("tray", [])),
  2081. )
  2082. continue
  2083. # Slot matched (existing tag, untagged inventory
  2084. # match, or freshly auto-created spool) — drop any
  2085. # stale dedup so a future tag swap re-prompts.
  2086. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2087. await auto_assign_spool(
  2088. printer_id,
  2089. ams_id,
  2090. tray_id,
  2091. spool,
  2092. printer_manager,
  2093. db,
  2094. tray_info_idx=tray_info_idx,
  2095. )
  2096. await db.commit()
  2097. await ws_manager.broadcast(
  2098. {
  2099. "type": "spool_auto_assigned",
  2100. "printer_id": printer_id,
  2101. "ams_id": ams_id,
  2102. "tray_id": tray_id,
  2103. "spool_id": spool.id,
  2104. }
  2105. )
  2106. logger.info(
  2107. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2108. spool.id,
  2109. printer_id,
  2110. ams_id,
  2111. tray_id,
  2112. )
  2113. elif is_valid_tag(tag_uid, tray_uuid):
  2114. # Non-BL spool with some tag — let user choose
  2115. await _broadcast_unknown_tag(
  2116. printer_id=printer_id,
  2117. ams_id=ams_id,
  2118. tray_id=tray_id,
  2119. tag_uid=tag_uid,
  2120. tray_uuid=tray_uuid,
  2121. tray_type=tray.get("tray_type"),
  2122. tray_color=tray.get("tray_color"),
  2123. tray_sub_brands=tray.get("tray_sub_brands"),
  2124. tray_count=len(ams_unit.get("tray", [])),
  2125. )
  2126. # No-tag slots (generic non-RFID filament) are left alone:
  2127. # nothing to identify, prompting "+ Add" would just create
  2128. # ghost spools with empty tags on every confirm.
  2129. except Exception as e:
  2130. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2131. try:
  2132. async with async_session() as db:
  2133. from backend.app.api.routes.settings import get_setting
  2134. from backend.app.models.printer import Printer
  2135. # Check if Spoolman is enabled
  2136. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2137. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2138. return
  2139. # Check sync mode
  2140. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2141. if sync_mode and sync_mode != "auto":
  2142. return # Only sync on auto mode
  2143. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2144. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2145. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2146. # always owned by per-print tracking, never by AMS auto-sync. The
  2147. # setting is still read by the settings UI for backwards compat but
  2148. # has no effect on the sync path here.
  2149. # Get Spoolman URL
  2150. spoolman_url = await get_setting(db, "spoolman_url")
  2151. if not spoolman_url:
  2152. return
  2153. # Get or create Spoolman client
  2154. client = await get_spoolman_client()
  2155. if not client:
  2156. try:
  2157. client = await init_spoolman_client(spoolman_url)
  2158. except ValueError as exc:
  2159. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2160. return
  2161. # Check if Spoolman is reachable
  2162. if not await client.health_check():
  2163. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2164. return
  2165. # Get printer name for location
  2166. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2167. printer = result.scalar_one_or_none()
  2168. printer_name = printer.name if printer else f"Printer {printer_id}"
  2169. # OPTIMIZATION: Fetch all spools once before processing trays
  2170. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2171. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2172. try:
  2173. cached_spools = await client.get_spools()
  2174. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2175. except Exception as e:
  2176. logger.error(
  2177. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2178. printer_id,
  2179. e,
  2180. )
  2181. return
  2182. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2183. from sqlalchemy.orm import selectinload
  2184. from backend.app.models.spool_assignment import SpoolAssignment
  2185. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2186. inventory_weights: dict[tuple[int, int], float] = {}
  2187. try:
  2188. assign_result = await db.execute(
  2189. select(SpoolAssignment)
  2190. .options(selectinload(SpoolAssignment.spool))
  2191. .where(SpoolAssignment.printer_id == printer_id)
  2192. )
  2193. for assignment in assign_result.scalars().all():
  2194. spool = assignment.spool
  2195. if spool and spool.label_weight > 0:
  2196. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2197. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2198. except Exception as e:
  2199. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2200. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2201. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2202. try:
  2203. slot_result = await db.execute(
  2204. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2205. )
  2206. for slot in slot_result.scalars().all():
  2207. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2208. except Exception as e:
  2209. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2210. # Sync each AMS tray and collect slot changes for DB persistence
  2211. synced = 0
  2212. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2213. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2214. for ams_unit in ams_data:
  2215. if not isinstance(ams_unit, dict):
  2216. continue
  2217. ams_id = int(ams_unit.get("id", 0))
  2218. trays = ams_unit.get("tray", [])
  2219. for tray_data in trays:
  2220. if not isinstance(tray_data, dict):
  2221. continue
  2222. tray_id_raw = int(tray_data.get("id", 0))
  2223. tray = client.parse_ams_tray(ams_id, tray_data)
  2224. if not tray:
  2225. # Empty tray slot — record for local assignment cleanup
  2226. # and drop any cached unknown-tag broadcast so a
  2227. # reinserted spool re-prompts.
  2228. #
  2229. # Not during a running print: a slot that empties there
  2230. # is a filament runout, and the spool is still in the
  2231. # AMS. `spoolman_slot_assignments` is how a tag-less
  2232. # spool assigned through the Bambuddy UI is resolved at
  2233. # completion (#1459), so deleting the row mid-print
  2234. # loses the runout segment's usage — the same failure
  2235. # the internal inventory's auto-unlink had.
  2236. if not printing_now:
  2237. empty_slots.append((ams_id, tray_id_raw))
  2238. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2239. continue
  2240. spool_tag = (
  2241. tray.tray_uuid
  2242. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2243. else tray.tag_uid
  2244. )
  2245. # Provide the hint only when no RFID is available
  2246. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2247. try:
  2248. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2249. result = await client.sync_ams_tray(
  2250. tray,
  2251. printer_name,
  2252. # Per-print tracking is the only weight writer (#1119).
  2253. # AMS auto-sync still maintains spool metadata / slot
  2254. # assignments but no longer touches remaining_weight.
  2255. disable_weight_sync=True,
  2256. cached_spools=cached_spools,
  2257. inventory_remaining=inv_remaining,
  2258. spoolman_spool_id_hint=hint,
  2259. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2260. )
  2261. if result is None and spool_tag and not auto_add_unknown_rfid:
  2262. # Spoolman skipped auto-create per user setting — surface
  2263. # the slot so the UI can offer "+ Add to inventory".
  2264. await _broadcast_unknown_tag(
  2265. printer_id=printer_id,
  2266. ams_id=ams_id,
  2267. tray_id=tray.tray_id,
  2268. tag_uid=tray.tag_uid or "",
  2269. tray_uuid=tray.tray_uuid or "",
  2270. tray_type=tray.tray_type,
  2271. tray_color=tray.tray_color,
  2272. tray_sub_brands=tray.tray_sub_brands,
  2273. tray_count=len(trays),
  2274. )
  2275. elif result:
  2276. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2277. if result:
  2278. synced += 1
  2279. if result.get("id"):
  2280. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2281. # If a new spool was created, add it to the cache
  2282. # so subsequent trays can find it if they reference the same tag
  2283. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2284. if not spool_exists:
  2285. cached_spools.append(result)
  2286. logger.debug(
  2287. "[Printer %s] Added newly created spool %s to cache",
  2288. printer_id,
  2289. result["id"],
  2290. )
  2291. # Reconcile slot_preset_mappings (the same row internal
  2292. # mode keeps in sync via inventory + spool_tag_matcher).
  2293. # Without this the slot card surfaces the previous spool's
  2294. # preset name — same bug shape, different inventory mode.
  2295. from backend.app.services.slot_preset_writer import (
  2296. upsert_slot_preset_for_spoolman_spool,
  2297. )
  2298. await upsert_slot_preset_for_spoolman_spool(
  2299. db=db,
  2300. spoolman_spool=result,
  2301. tray_info_idx=tray.tray_info_idx or "",
  2302. tray_sub_brands=tray.tray_sub_brands or "",
  2303. tray_type=tray.tray_type or "",
  2304. printer_id=printer_id,
  2305. ams_id=ams_id,
  2306. tray_id=tray.tray_id,
  2307. )
  2308. except Exception as e:
  2309. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2310. if synced > 0:
  2311. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2312. # Persist slot assignment changes to the local table
  2313. if slot_changes or empty_slots:
  2314. try:
  2315. for ams_id, tray_id, spool_id in slot_changes:
  2316. await db.execute(
  2317. text(
  2318. "INSERT INTO spoolman_slot_assignments"
  2319. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2320. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2321. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2322. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2323. ),
  2324. {
  2325. "printer_id": printer_id,
  2326. "ams_id": ams_id,
  2327. "tray_id": tray_id,
  2328. "spool_id": spool_id,
  2329. },
  2330. )
  2331. for ams_id, tray_id in empty_slots:
  2332. await db.execute(
  2333. delete(SpoolmanSlotAssignment).where(
  2334. SpoolmanSlotAssignment.printer_id == printer_id,
  2335. SpoolmanSlotAssignment.ams_id == ams_id,
  2336. SpoolmanSlotAssignment.tray_id == tray_id,
  2337. )
  2338. )
  2339. await db.commit()
  2340. except Exception as e:
  2341. await db.rollback()
  2342. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2343. except Exception as e:
  2344. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2345. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2346. """Capture a camera snapshot for notification image attachment.
  2347. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2348. Uses: external camera > buffered frame > fresh capture.
  2349. """
  2350. if not printer:
  2351. return None
  2352. try:
  2353. from backend.app.api.routes.settings import get_setting
  2354. async with async_session() as db:
  2355. capture_enabled = await get_setting(db, "capture_finish_photo")
  2356. if capture_enabled is not None and capture_enabled.lower() != "true":
  2357. return None
  2358. # Try external camera first
  2359. if printer.external_camera_enabled and printer.external_camera_url:
  2360. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2361. from backend.app.api.routes.camera import live_frame_for_capture
  2362. from backend.app.services.external_camera import capture_frame
  2363. # An external camera allows one reader, so capturing while a viewer
  2364. # is attached fails (#2707). A None here falls through to the paths
  2365. # below exactly as a failed capture did.
  2366. defer, buffered = live_frame_for_capture(printer_id)
  2367. if defer:
  2368. frame_data = buffered
  2369. else:
  2370. frame_data = await capture_frame(
  2371. printer.external_camera_url,
  2372. printer.external_camera_type or "mjpeg",
  2373. snapshot_url=printer.external_camera_snapshot_url,
  2374. )
  2375. if frame_data and len(frame_data) <= 2_500_000:
  2376. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2377. return _apply_camera_rotation(frame_data, printer, logger)
  2378. # Try buffered frame from active stream
  2379. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2380. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2381. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2382. buffered_frame = get_buffered_frame(printer_id)
  2383. if (active_for_printer or active_chamber) and buffered_frame:
  2384. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2385. if len(buffered_frame) <= 2_500_000:
  2386. return _apply_camera_rotation(buffered_frame, printer, logger)
  2387. # Fresh capture from printer camera
  2388. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2389. from backend.app.services.camera import capture_camera_frame_bytes
  2390. frame_data = await capture_camera_frame_bytes(
  2391. printer.ip_address, printer.access_code, printer.model, timeout=15
  2392. )
  2393. if frame_data and len(frame_data) <= 2_500_000:
  2394. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2395. return _apply_camera_rotation(frame_data, printer, logger)
  2396. except Exception as e:
  2397. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2398. return None
  2399. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2400. """#1867: bank a recent in-print camera frame for the finish photo.
  2401. Called on every layer change and (#2547) on every print-progress advance.
  2402. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2403. path has a pre-End-G-code image for prints that end with a plate swap.
  2404. Both drivers are print telemetry that stops the instant printing ends: no
  2405. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2406. plate swap) executes. So the last banked frame is always the finished print,
  2407. never the swapped plate — that property is what the #1867 path relies on and
  2408. it must survive any change to the throttle below.
  2409. Layer changes alone were not enough: they stop when the *final* layer
  2410. begins, which on a three-minute last layer left the bank stale by the whole
  2411. length of that layer (#2547). Progress keeps ticking through it.
  2412. Best-effort: any failure just leaves the previous banked frame.
  2413. """
  2414. logger = logging.getLogger(__name__)
  2415. client = printer_manager.get_client(printer_id)
  2416. state = client.state if client else None
  2417. if not state or state.state != "RUNNING":
  2418. return
  2419. # Only during actual extrusion — firmware ticks layer_num during the
  2420. # pre-print calibration sequence, whose sub-stages are non-zero.
  2421. if state.mc_print_sub_stage not in (None, 0):
  2422. return
  2423. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2424. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2425. # now that progress advances also drive banking, that exemption would fire a
  2426. # camera grab on every percent tick of the last layer. Bambu printers accept
  2427. # one RTSP client at a time, so each grab contends with the live view.
  2428. now = time.monotonic()
  2429. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2430. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2431. return
  2432. total = state.total_layers or 0
  2433. try:
  2434. async with async_session() as db:
  2435. from backend.app.models.printer import Printer
  2436. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2437. printer = result.scalar_one_or_none()
  2438. if not printer:
  2439. return
  2440. # Reuses the notification snapshot path, which honours the
  2441. # `capture_finish_photo` setting (returns None when disabled) so we
  2442. # don't bank frames the user never asked for.
  2443. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2444. if frame:
  2445. _inprint_frame_bank[printer_id] = frame
  2446. _inprint_frame_bank_ts[printer_id] = now
  2447. logger.debug(
  2448. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2449. printer_id,
  2450. layer_num,
  2451. total,
  2452. len(frame),
  2453. )
  2454. except Exception as e:
  2455. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2456. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2457. """Apply camera rotation to snapshot image if configured."""
  2458. from backend.app.services.camera import apply_camera_rotation
  2459. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2460. async def _send_print_start_notification(
  2461. printer_id: int,
  2462. data: dict,
  2463. archive_data: dict | None = None,
  2464. logger=None,
  2465. ):
  2466. """Helper to send print start notification with optional archive data."""
  2467. if logger is None:
  2468. logger = logging.getLogger(__name__)
  2469. try:
  2470. async with async_session() as db:
  2471. from backend.app.models.printer import Printer
  2472. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2473. printer = result.scalar_one_or_none()
  2474. printer_name = printer.name if printer else f"Printer {printer_id}"
  2475. # Capture camera snapshot for notification image attachment
  2476. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2477. if image_data:
  2478. if archive_data is None:
  2479. archive_data = {}
  2480. archive_data["image_data"] = image_data
  2481. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  2482. # Send user-specific email notification for print start
  2483. if archive_data and archive_data.get("created_by_id"):
  2484. await notification_service.send_user_print_email(
  2485. event_type="user_print_start",
  2486. created_by_id=archive_data["created_by_id"],
  2487. printer_name=printer_name,
  2488. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  2489. db=db,
  2490. )
  2491. except Exception as e:
  2492. logger.warning("Notification on_print_start failed: %s", e)
  2493. async def _dispatch_user_print_email(
  2494. status: str,
  2495. created_by_id: int | None,
  2496. printer_name: str,
  2497. filename: str,
  2498. db,
  2499. ) -> None:
  2500. """Send a user-specific print-completion email based on print status.
  2501. Maps the normalised print status to the correct event type and delegates
  2502. to :meth:`NotificationService.send_user_print_email`. A single helper
  2503. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  2504. "stopped"`` dispatch block at every call site.
  2505. Does nothing if *created_by_id* is ``None``.
  2506. """
  2507. if created_by_id is None:
  2508. return
  2509. if status == "completed":
  2510. event_type = "user_print_complete"
  2511. elif status == "failed":
  2512. event_type = "user_print_failed"
  2513. elif status in ("stopped", "aborted", "cancelled"):
  2514. event_type = "user_print_stopped"
  2515. else:
  2516. return
  2517. await notification_service.send_user_print_email(
  2518. event_type=event_type,
  2519. created_by_id=created_by_id,
  2520. printer_name=printer_name,
  2521. filename=filename,
  2522. db=db,
  2523. )
  2524. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  2525. """Extract printable objects from an archive's 3MF file and store in printer state."""
  2526. try:
  2527. from backend.app.services.archive import extract_printable_objects_from_3mf
  2528. client = printer_manager.get_client(printer_id)
  2529. if not client:
  2530. return
  2531. file_path = app_settings.base_dir / archive.file_path
  2532. if file_path.is_file() and str(file_path).endswith(".3mf"):
  2533. with open(file_path, "rb") as f:
  2534. threemf_data = f.read()
  2535. # Extract with positions for UI overlay, scoped to the plate that
  2536. # is printing — resolve_plate_id is the same resolver /cover uses,
  2537. # so the object list can't disagree with the thumbnail it is drawn
  2538. # over (#2522).
  2539. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  2540. threemf_data,
  2541. plate_number=resolve_plate_id(client.state),
  2542. include_positions=True,
  2543. )
  2544. if printable_objects:
  2545. client.state.printable_objects = printable_objects
  2546. client.state.printable_objects_bbox_all = bbox_all
  2547. client.state.skipped_objects = []
  2548. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  2549. except Exception as e:
  2550. logger.debug("Failed to extract printable objects from archive: %s", e)
  2551. async def on_print_start(printer_id: int, data: dict):
  2552. """Handle print start - archive the 3MF file immediately."""
  2553. logger = logging.getLogger(__name__)
  2554. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  2555. # Clear any stale user-stopped flag from previous print cycles
  2556. _user_stopped_printers.discard(printer_id)
  2557. _kill_switch_notification_tasks.pop(printer_id, None)
  2558. # #1721: drop any leftover pre-captured finish frame from a prior print
  2559. # so a never-consumed cache entry can't bleed into the new print's photo.
  2560. _stage22_finish_frames.pop(printer_id, None)
  2561. # #1867: same for the in-print frame bank — a queued print must not reuse
  2562. # the previous job's banked frame.
  2563. _inprint_frame_bank.pop(printer_id, None)
  2564. _inprint_frame_bank_ts.pop(printer_id, None)
  2565. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  2566. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  2567. # print's flag instead of inheriting it.
  2568. print_dispatch_context.adopt(printer_id)
  2569. # Cancel any active bed cooldown waiter for this printer
  2570. if _bed_cool_waiters.pop(printer_id, None):
  2571. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  2572. # Clear cached cover images so the new print's thumbnail is fetched fresh
  2573. from backend.app.api.routes.printers import clear_cover_cache
  2574. clear_cover_cache(printer_id)
  2575. await ws_manager.send_print_start(printer_id, data)
  2576. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  2577. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  2578. # MQTT relay - publish print start
  2579. try:
  2580. printer_info = printer_manager.get_printer(printer_id)
  2581. if printer_info:
  2582. await mqtt_relay.on_print_start(
  2583. printer_id,
  2584. printer_info.name,
  2585. printer_info.serial_number,
  2586. data.get("filename", ""),
  2587. data.get("subtask_name", ""),
  2588. )
  2589. except Exception:
  2590. pass # Don't fail print start callback if MQTT fails
  2591. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  2592. # and mapping, and the seeded tray-change log.
  2593. #
  2594. # Unconditional, for both inventory backends. This only *captures* — the
  2595. # writing is still split, with the internal tracker skipped at completion
  2596. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  2597. # carries its plate-scoped 3MF figures and stored mapping, but not the
  2598. # tray-change log, and that log is the only record of which spool fed
  2599. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  2600. # it on one side only would leave Spoolman users with the mid-print
  2601. # restart bug this fixes for everyone else.
  2602. try:
  2603. async with async_session() as db:
  2604. from backend.app.api.routes.settings import get_setting
  2605. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  2606. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2607. await usage_on_print_start(
  2608. printer_id,
  2609. data,
  2610. printer_manager,
  2611. db=db,
  2612. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  2613. )
  2614. except Exception as e:
  2615. logger.warning("Usage tracker on_print_start failed: %s", e)
  2616. # Track if notification was sent (to avoid sending twice)
  2617. notification_sent = False
  2618. # Smart plug automation: turn on plug when print starts
  2619. try:
  2620. async with async_session() as db:
  2621. await smart_plug_manager.on_print_start(printer_id, db)
  2622. except Exception as e:
  2623. logger.warning("Smart plug on_print_start failed: %s", e)
  2624. async with async_session() as db:
  2625. from backend.app.models.printer import Printer
  2626. from backend.app.services.bambu_ftp import list_files_async
  2627. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2628. printer = result.scalar_one_or_none()
  2629. # Plate detection check - pause if objects detected on build plate
  2630. logger.info(
  2631. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  2632. )
  2633. if printer and printer.plate_detection_enabled:
  2634. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  2635. # Release the pooled DB connection before the plate-detection camera
  2636. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  2637. # printer SELECT has run so far — nothing to persist — so this commit
  2638. # is a data-noop that ends the read transaction and returns the
  2639. # connection to the pool during the I/O (issue #2572). expire_on_commit
  2640. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  2641. # archive lookups below re-acquire a fresh connection on next execute.
  2642. await db.commit()
  2643. try:
  2644. from backend.app.services.plate_detection import check_plate_empty
  2645. # Build ROI tuple from printer settings if available
  2646. roi = None
  2647. if all(
  2648. [
  2649. printer.plate_detection_roi_x is not None,
  2650. printer.plate_detection_roi_y is not None,
  2651. printer.plate_detection_roi_w is not None,
  2652. printer.plate_detection_roi_h is not None,
  2653. ]
  2654. ):
  2655. roi = (
  2656. printer.plate_detection_roi_x,
  2657. printer.plate_detection_roi_y,
  2658. printer.plate_detection_roi_w,
  2659. printer.plate_detection_roi_h,
  2660. )
  2661. # Auto-turn on chamber light if it's off for better detection
  2662. light_was_off = False
  2663. client = printer_manager.get_client(printer_id)
  2664. if client and client.state:
  2665. light_was_off = not client.state.chamber_light
  2666. if light_was_off:
  2667. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  2668. client.set_chamber_light(True)
  2669. # Wait for light to physically turn on and camera to adjust exposure
  2670. await asyncio.sleep(2.5)
  2671. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  2672. plate_result = await check_plate_empty(
  2673. printer_id=printer_id,
  2674. ip_address=printer.ip_address,
  2675. access_code=printer.access_code,
  2676. model=printer.model,
  2677. include_debug_image=False,
  2678. external_camera_url=printer.external_camera_url,
  2679. external_camera_type=printer.external_camera_type,
  2680. use_external=printer.external_camera_enabled,
  2681. roi=roi,
  2682. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  2683. )
  2684. # Restore chamber light to original state
  2685. if light_was_off and client:
  2686. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  2687. client.set_chamber_light(False)
  2688. if not plate_result.needs_calibration and not plate_result.is_empty:
  2689. # Objects detected - pause the print!
  2690. logger.warning(
  2691. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  2692. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  2693. )
  2694. client = printer_manager.get_client(printer_id)
  2695. if client:
  2696. client.pause_print()
  2697. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  2698. # Send notification about plate not empty
  2699. await ws_manager.broadcast(
  2700. {
  2701. "type": "plate_not_empty",
  2702. "printer_id": printer_id,
  2703. "printer_name": printer.name,
  2704. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  2705. }
  2706. )
  2707. # Also send push notification
  2708. try:
  2709. await notification_service.on_plate_not_empty(
  2710. printer_id=printer_id,
  2711. printer_name=printer.name,
  2712. db=db,
  2713. difference_percent=plate_result.difference_percent,
  2714. )
  2715. except Exception as notif_err:
  2716. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  2717. else:
  2718. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  2719. except Exception as plate_err:
  2720. # Don't block print on plate detection errors
  2721. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  2722. if not printer:
  2723. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  2724. if not notification_sent:
  2725. await _send_print_start_notification(printer_id, data, logger=logger)
  2726. return
  2727. if not printer.auto_archive:
  2728. # auto-archive disabled — check if there's an expected print (dispatched
  2729. # by BamBuddy via queue/reprint) that already has an archive to promote.
  2730. # If so, fall through to the expected-print handling below so the archive
  2731. # is tracked in _active_prints and usage tracking works at completion.
  2732. _fn = data.get("filename", "")
  2733. _sn = data.get("subtask_name", "")
  2734. _check_keys: list[tuple[int, str]] = []
  2735. if _sn:
  2736. _check_keys += [
  2737. (printer_id, _sn),
  2738. (printer_id, f"{_sn}.3mf"),
  2739. (printer_id, f"{_sn}.gcode.3mf"),
  2740. ]
  2741. if _fn:
  2742. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  2743. _check_keys.append((printer_id, _base_fn))
  2744. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  2745. _check_keys += [
  2746. (printer_id, _no_archive_base),
  2747. (printer_id, f"{_no_archive_base}.3mf"),
  2748. ]
  2749. _has_expected = any(k in _expected_prints for k in _check_keys)
  2750. if not _has_expected:
  2751. # No expected print — truly external print (started from slicer/touchscreen)
  2752. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  2753. if not notification_sent:
  2754. _no_archive_creator: int | None = None
  2755. for _key in _check_keys:
  2756. _expected_prints.pop(_key, None)
  2757. _expected_print_registered_at.pop(_key, None)
  2758. popped_creator = _expected_print_creators.pop(_key, None)
  2759. if _no_archive_creator is None:
  2760. _no_archive_creator = popped_creator
  2761. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  2762. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  2763. return
  2764. else:
  2765. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  2766. # Get the filename and subtask_name
  2767. filename = data.get("filename", "")
  2768. subtask_name = data.get("subtask_name", "")
  2769. # MQTT subtask_id uniquely identifies a print job on the printer. When
  2770. # present, it lets us match an archive across a backend restart (#972):
  2771. # same id → same print → resume the existing row instead of cancelling
  2772. # it and recreating from scratch (which loses started_at). Treat "0"
  2773. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  2774. raw_mqtt = data.get("raw_data") or {}
  2775. subtask_id = raw_mqtt.get("subtask_id")
  2776. if subtask_id is not None:
  2777. subtask_id = str(subtask_id).strip()
  2778. if subtask_id in ("", "0"):
  2779. subtask_id = None
  2780. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  2781. # Skip the printer's own jobs — a calibration run is not a user's print.
  2782. # See is_internal_printer_job for what counts and why both fields are
  2783. # tested; the pressure-advance line reports as a subtask name with no
  2784. # /usr/ path, which the old prefix-only test here missed entirely.
  2785. #
  2786. # No notification either. The event describes the printer calibrating
  2787. # itself, so "Print started" is as wrong as the archive was, and the
  2788. # matching completion is suppressed in on_print_complete for the same
  2789. # reason.
  2790. if is_internal_printer_job(filename, subtask_name):
  2791. logger.info(
  2792. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  2793. filename,
  2794. subtask_name,
  2795. )
  2796. return
  2797. if not filename and not subtask_name:
  2798. # Send notification without archive data (no filename)
  2799. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  2800. if not notification_sent:
  2801. await _send_print_start_notification(printer_id, data, logger=logger)
  2802. return
  2803. # Check if this is an expected print from reprint/scheduled
  2804. # Build list of possible keys to check
  2805. expected_keys = []
  2806. if subtask_name:
  2807. expected_keys.append((printer_id, subtask_name))
  2808. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  2809. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  2810. if filename:
  2811. fname = filename.split("/")[-1] if "/" in filename else filename
  2812. expected_keys.append((printer_id, fname))
  2813. # Strip extensions to match
  2814. base = fname.replace(".gcode", "").replace(".3mf", "")
  2815. expected_keys.append((printer_id, base))
  2816. expected_keys.append((printer_id, f"{base}.3mf"))
  2817. expected_archive_id = None
  2818. for key in expected_keys:
  2819. expected_archive_id = _expected_prints.pop(key, None)
  2820. _expected_print_registered_at.pop(key, None)
  2821. if expected_archive_id:
  2822. # Clean up other possible keys for this print
  2823. for other_key in expected_keys:
  2824. _expected_prints.pop(other_key, None)
  2825. _expected_print_registered_at.pop(other_key, None)
  2826. break
  2827. if expected_archive_id:
  2828. # This is a reprint/scheduled print - use existing archive, don't create new one
  2829. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  2830. from backend.app.models.archive import PrintArchive
  2831. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  2832. archive = result.scalar_one_or_none()
  2833. if archive:
  2834. # Update archive status to printing
  2835. archive.status = "printing"
  2836. archive.started_at = datetime.now(timezone.utc)
  2837. # Reprint of an archive reuses the source row. Without resetting
  2838. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  2839. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  2840. # extracts the *original* print's last frame, which then ships in
  2841. # the completion notification (#1707). Clear the path so the
  2842. # scanner runs fresh; also unlink the old video file so reprints
  2843. # don't accumulate orphans in the archive directory. Photos list
  2844. # is left alone — accumulating one finish photo per run is fine.
  2845. # The print-start baseline (#2704) is stale for the same reason:
  2846. # it describes the printer before the previous run. The capture
  2847. # below overwrites it, but clear it here too so an early failure
  2848. # can't leave the scan diffing against the wrong snapshot.
  2849. archive.timelapse_baseline = None
  2850. stale_timelapse_relpath = archive.timelapse_path
  2851. if stale_timelapse_relpath:
  2852. archive.timelapse_path = None
  2853. try:
  2854. stale_path = app_settings.base_dir / stale_timelapse_relpath
  2855. if stale_path.is_file():
  2856. stale_path.unlink()
  2857. logger.info(
  2858. "Deleted stale timelapse %s on reprint of archive %s",
  2859. stale_timelapse_relpath,
  2860. expected_archive_id,
  2861. )
  2862. except OSError as e:
  2863. logger.warning(
  2864. "Failed to delete stale timelapse %s on reprint: %s",
  2865. stale_timelapse_relpath,
  2866. e,
  2867. )
  2868. # Persist a restart-stable id so a later restart resumes this
  2869. # archive by subtask_id instead of name-matching + duplicating
  2870. # it (#1485). The printer often hasn't echoed subtask_id back
  2871. # this soon after dispatch, so fall back to the id Bambuddy
  2872. # minted when it sent the print command. Scoped to this
  2873. # expected-print branch on purpose: an expected match means
  2874. # Bambuddy dispatched this exact print in this process, so the
  2875. # client's last-dispatch id genuinely belongs to it — using it
  2876. # for an externally-started print could mis-tag the archive.
  2877. effective_subtask_id = subtask_id
  2878. if not effective_subtask_id:
  2879. _client = printer_manager.get_client(printer_id)
  2880. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  2881. if _dispatched:
  2882. effective_subtask_id = str(_dispatched).strip() or None
  2883. # Update on first-set OR on reprint (the queue dispatcher mints
  2884. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  2885. # the rewrite for reprints leaves the archive holding the FIRST
  2886. # run's id; if MQTT then reconnects mid-print, the reconciler
  2887. # (#1542) compares the stale stored id against the printer's
  2888. # live id, sees a mismatch, and synthesises a bogus PRINT
  2889. # COMPLETE — exactly the false-positive "Print Stopped" reported
  2890. # in #1807. Inequality check preserves the noop-on-stable-push
  2891. # behaviour the earlier `not archive.subtask_id` guard provided.
  2892. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  2893. archive.subtask_id = effective_subtask_id
  2894. # #1403 follow-up: VP-queue archives are created with
  2895. # printer_id=None at queue-add time (we don't know which
  2896. # printer will run the job yet). When the print actually
  2897. # starts on a specific printer the expected-archive lookup
  2898. # used to skip this assignment, leaving printer_id=None
  2899. # forever — which then disables the "Scan for timelapse"
  2900. # button in ArchivesPage (gated on !archive.printer_id).
  2901. if archive.printer_id != printer_id:
  2902. archive.printer_id = printer_id
  2903. await db.commit()
  2904. # Track as active print
  2905. _active_prints[(printer_id, archive.filename)] = archive.id
  2906. if subtask_name:
  2907. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  2908. # Start timelapse session if external camera is enabled (#1353).
  2909. # Queue / VP-dispatched prints land here in the expected-archive
  2910. # branch and used to skip start_session entirely — frames were
  2911. # never captured and the post-print stitch silently returned None.
  2912. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  2913. # Inject ams_mapping into usage tracker session — the session was created
  2914. # before expected-print promotion, so it may have ams_mapping=None when
  2915. # the MQTT request topic subscription failed (common on P1S/A1).
  2916. _stored_map = _print_ams_mappings.get(expected_archive_id)
  2917. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  2918. if _stored_map or _stored_plate_id is not None:
  2919. try:
  2920. from backend.app.services.usage_tracker import _active_sessions
  2921. _ut_session = _active_sessions.get(printer_id)
  2922. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  2923. _ut_session.ams_mapping = _stored_map
  2924. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  2925. # plate_id injection covers direct-Print of plate N of a multi-plate
  2926. # 3MF — queue prints already capture it via the on_print_start queue
  2927. # lookup, but direct-Print never goes through the queue (#1697).
  2928. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  2929. _ut_session.plate_id = _stored_plate_id
  2930. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  2931. except Exception:
  2932. pass
  2933. # Set up energy tracking (#941: persist start on archive row)
  2934. await _record_energy_start(archive, printer_id, db, context="expected-print")
  2935. await ws_manager.send_archive_updated(
  2936. {
  2937. "id": archive.id,
  2938. "status": "printing",
  2939. }
  2940. )
  2941. # Send notification with archive data (reprint/scheduled)
  2942. if not notification_sent:
  2943. # Use archive's created_by_id; fall back to the creator registered via
  2944. # register_expected_print (handles library-file-based queue items where
  2945. # the freshly-created archive has no created_by_id yet).
  2946. # Pop ALL matching keys so no stale entries remain in the dict.
  2947. fallback_creator = None
  2948. for key in expected_keys:
  2949. popped = _expected_print_creators.pop(key, None)
  2950. if fallback_creator is None:
  2951. fallback_creator = popped
  2952. archive_data = {
  2953. "print_time_seconds": archive.print_time_seconds,
  2954. "created_by_id": archive.created_by_id or fallback_creator,
  2955. }
  2956. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2957. # Extract printable objects from the archived 3MF file
  2958. _load_objects_from_archive(archive, printer_id, logger)
  2959. # Store Spoolman tracking data for per-filament usage reporting
  2960. try:
  2961. await _store_spoolman_print_data(
  2962. printer_id,
  2963. archive.id,
  2964. archive.file_path,
  2965. db,
  2966. printer_manager,
  2967. ams_mapping=_get_start_ams_mapping(data, archive.id),
  2968. plate_id=_get_start_plate_id(archive.id),
  2969. )
  2970. except Exception as e:
  2971. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  2972. # Capture timelapse file baseline for snapshot-diff on completion
  2973. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  2974. # hit this branch — without the baseline the completion-time scan
  2975. # falls into its "take baseline now" fallback, which snapshots
  2976. # AFTER the new MP4 already exists and never matches a diff
  2977. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  2978. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  2979. return # Skip creating a new archive
  2980. # Check if there's already a "printing" archive for this printer/file
  2981. # This prevents duplicates when backend restarts during an active print
  2982. from backend.app.models.archive import PrintArchive
  2983. existing_archive: PrintArchive | None = None
  2984. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  2985. # across a backend restart for the same print, so this is the most
  2986. # reliable way to reattach. We also accept a previously stale-cancelled
  2987. # archive here so users upgrading mid-print get revived when the row
  2988. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  2989. if subtask_id:
  2990. by_id = await db.execute(
  2991. select(PrintArchive)
  2992. .where(PrintArchive.printer_id == printer_id)
  2993. .where(PrintArchive.subtask_id == subtask_id)
  2994. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  2995. .order_by(PrintArchive.created_at.desc())
  2996. .limit(1)
  2997. )
  2998. candidate = by_id.scalar_one_or_none()
  2999. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3000. existing_archive = candidate
  3001. # Fallback match: name-based lookup. Kept as-is for prints whose
  3002. # subtask_id is missing ("0" / local / non-cloud prints).
  3003. if existing_archive is None:
  3004. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3005. existing = await db.execute(
  3006. select(PrintArchive)
  3007. .where(PrintArchive.printer_id == printer_id)
  3008. .where(PrintArchive.status == "printing")
  3009. .where(
  3010. or_(
  3011. PrintArchive.print_name == check_name,
  3012. PrintArchive.filename.in_(
  3013. [
  3014. f"{check_name}.3mf",
  3015. f"{check_name}.gcode.3mf",
  3016. ]
  3017. ),
  3018. )
  3019. )
  3020. .order_by(PrintArchive.created_at.desc())
  3021. .limit(1)
  3022. )
  3023. existing_archive = existing.scalar_one_or_none()
  3024. if existing_archive:
  3025. # subtask_id match → always resume, regardless of age. Same print,
  3026. # just a backend restart. Revive if it was previously stale-cancelled.
  3027. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  3028. if subtask_match:
  3029. if existing_archive.status == "cancelled":
  3030. logger.warning(
  3031. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  3032. existing_archive.id,
  3033. subtask_id,
  3034. )
  3035. existing_archive.status = "printing"
  3036. existing_archive.failure_reason = None
  3037. await db.commit()
  3038. else:
  3039. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  3040. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3041. if existing_archive.energy_start_kwh is None:
  3042. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  3043. if not notification_sent:
  3044. archive_data = {
  3045. "print_time_seconds": existing_archive.print_time_seconds,
  3046. "created_by_id": existing_archive.created_by_id,
  3047. }
  3048. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3049. _load_objects_from_archive(existing_archive, printer_id, logger)
  3050. return
  3051. # Name-match only (no subtask_id to anchor on): decide resume vs.
  3052. # stale from the printer's *current* progress, not wall-clock age.
  3053. # A genuinely long print used to trip a blind 4h cutoff and have its
  3054. # live archive cancelled + duplicated on every backend restart
  3055. # (#1485). If the printer reports real progress, this name-matched
  3056. # 'printing' archive IS that ongoing print — resume it whatever its
  3057. # age. Only treat it as a stale leftover when the printer clearly
  3058. # shows a different, freshly-started print: near-0% progress on an
  3059. # archive far too old to still be at 0%. Unknown progress (printer
  3060. # not connected) never cancels — resuming is the safe default.
  3061. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  3062. live_status = printer_manager.get_status(printer_id)
  3063. live_progress = getattr(live_status, "progress", None) if live_status else None
  3064. looks_stale = (
  3065. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  3066. )
  3067. if looks_stale:
  3068. logger.warning(
  3069. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  3070. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  3071. )
  3072. existing_archive.status = "cancelled"
  3073. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  3074. await db.commit()
  3075. # Fall through to create new archive (don't return)
  3076. else:
  3077. logger.info(
  3078. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  3079. )
  3080. # Track this as the active print
  3081. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3082. # Attach subtask_id retroactively so future restarts can resume.
  3083. # Compare for inequality (not "is empty") to also pick up reprint
  3084. # dispatches that mint a fresh id — see #1807 for the bogus
  3085. # "Print Stopped" the strict-empty guard caused on reconnect.
  3086. if subtask_id and existing_archive.subtask_id != subtask_id:
  3087. existing_archive.subtask_id = subtask_id
  3088. await db.commit()
  3089. # Also set up energy tracking if not already tracked (#941: persisted column)
  3090. if existing_archive.energy_start_kwh is None:
  3091. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  3092. # Send notification with archive data (existing archive)
  3093. if not notification_sent:
  3094. archive_data = {
  3095. "print_time_seconds": existing_archive.print_time_seconds,
  3096. "created_by_id": existing_archive.created_by_id,
  3097. }
  3098. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3099. # Extract printable objects from the archived 3MF file
  3100. _load_objects_from_archive(existing_archive, printer_id, logger)
  3101. return
  3102. # Build list of possible 3MF filenames to try
  3103. possible_names = []
  3104. # Bambu printers typically store files as "Name.gcode.3mf"
  3105. # The subtask_name is usually the best source for the filename
  3106. if subtask_name:
  3107. # Try common Bambu naming patterns
  3108. possible_names.append(f"{subtask_name}.gcode.3mf")
  3109. possible_names.append(f"{subtask_name}.3mf")
  3110. # Try original filename with .3mf extension
  3111. if filename:
  3112. # Extract just the filename part, not the full path
  3113. fname = filename.split("/")[-1] if "/" in filename else filename
  3114. if fname.endswith(".3mf"):
  3115. possible_names.append(fname)
  3116. elif fname.endswith(".gcode"):
  3117. base = fname.rsplit(".", 1)[0]
  3118. possible_names.append(f"{base}.gcode.3mf")
  3119. possible_names.append(f"{base}.3mf")
  3120. else:
  3121. possible_names.append(f"{fname}.gcode.3mf")
  3122. possible_names.append(f"{fname}.3mf")
  3123. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3124. space_variants = []
  3125. for name in possible_names:
  3126. if " " in name:
  3127. space_variants.append(name.replace(" ", "_"))
  3128. possible_names.extend(space_variants)
  3129. # Remove duplicates while preserving order
  3130. seen = set()
  3131. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  3132. logger.info("Trying filenames: %s", possible_names)
  3133. # Release the pooled DB connection before the 3MF FTP download. Reaching
  3134. # here means none of the expected-/existing-archive write branches ran
  3135. # (they all return earlier) — only SELECTs have executed on this path, so
  3136. # this commit persists nothing; it ends the read transaction so the
  3137. # connection returns to the pool during the download. That download tries
  3138. # up to five remote paths per candidate filename with retry/backoff and
  3139. # can run for minutes under FTP contention; holding the session across it
  3140. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  3141. # work runs during the download — the new-archive writes below re-acquire
  3142. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  3143. await db.commit()
  3144. # Try to find and download the 3MF file
  3145. temp_path = None
  3146. downloaded_filename = None
  3147. # Cache check: cover endpoint may have already pulled this 3MF during
  3148. # the print (frontend opens the card and shows the thumbnail) — reuse
  3149. # that file instead of re-downloading 36MB over the same FTP link that
  3150. # just served it (#972). The cache keys on a normalized filename so
  3151. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  3152. for try_filename in possible_names:
  3153. if not try_filename.endswith(".3mf"):
  3154. continue
  3155. cached = get_cached_3mf(printer_id, try_filename)
  3156. if cached:
  3157. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  3158. temp_path = cached
  3159. downloaded_filename = try_filename
  3160. break
  3161. # Does this printer keep the sliced file somewhere FTPS can reach? On
  3162. # H2-series and P2S the answer is routinely no — the file stays on
  3163. # internal eMMC and port 990 only ever serves external storage — and
  3164. # then the whole sweep below (six filenames x five directories x four
  3165. # retries, then the directory walk) is ~110 connections that cannot
  3166. # succeed. Skip it and say why (#2780).
  3167. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  3168. if not storage.reachable and not downloaded_filename:
  3169. logger.info(
  3170. "Skipping the 3MF lookup for printer %s: %s — the print file is not on storage "
  3171. "Bambuddy can read over FTPS, so no path would find it",
  3172. printer_id,
  3173. storage.reason,
  3174. )
  3175. # Get FTP retry settings
  3176. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3177. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  3178. if not try_filename.endswith(".3mf"):
  3179. continue
  3180. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  3181. # printers, so try it first — deferring it to last cost #972's reporter
  3182. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  3183. # landing on the path that actually had the file.
  3184. remote_paths = [
  3185. f"/{try_filename}",
  3186. f"/cache/{try_filename}",
  3187. f"/model/{try_filename}",
  3188. f"/data/{try_filename}",
  3189. f"/data/Metadata/{try_filename}",
  3190. ]
  3191. temp_path = app_settings.archive_dir / "temp" / try_filename
  3192. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3193. for remote_path in remote_paths:
  3194. if ftps_handshake_blocked(printer.ip_address):
  3195. # The printer's FTPS service is not completing a TLS
  3196. # handshake, so it has no path we could reach — walking the
  3197. # remaining candidates only re-runs the same failure
  3198. # (#2780). Fall through to the no-3MF archive now.
  3199. logger.warning(
  3200. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  3201. printer_id,
  3202. )
  3203. break
  3204. logger.debug("Trying FTP download: %s", remote_path)
  3205. try:
  3206. if ftp_retry_enabled:
  3207. downloaded = await with_ftp_retry(
  3208. download_file_async,
  3209. printer.ip_address,
  3210. printer.access_code,
  3211. remote_path,
  3212. temp_path,
  3213. timeout=ftp_timeout,
  3214. socket_timeout=ftp_timeout,
  3215. printer_model=printer.model,
  3216. max_retries=ftp_retry_count,
  3217. retry_delay=ftp_retry_delay,
  3218. operation_name=f"Download 3MF from {remote_path}",
  3219. non_retry_exceptions=(FileNotOnPrinterError,),
  3220. )
  3221. else:
  3222. downloaded = await download_file_async(
  3223. printer.ip_address,
  3224. printer.access_code,
  3225. remote_path,
  3226. temp_path,
  3227. timeout=ftp_timeout,
  3228. socket_timeout=ftp_timeout,
  3229. printer_model=printer.model,
  3230. )
  3231. if downloaded:
  3232. downloaded_filename = try_filename
  3233. logger.info("Downloaded: %s", remote_path)
  3234. # Populate shared cache so the cover endpoint (if it
  3235. # runs next) doesn't refetch the same 36MB over FTP.
  3236. cache_3mf_download(printer_id, try_filename, temp_path)
  3237. break
  3238. except FileNotOnPrinterError:
  3239. # 550 — file isn't at this path. Advance to next candidate
  3240. # without burning the retry budget.
  3241. logger.debug("3MF not at %s (550), trying next path", remote_path)
  3242. except Exception as e:
  3243. logger.debug("FTP download failed for %s: %s", remote_path, e)
  3244. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  3245. break
  3246. # If still not found, try listing directories to find matching file
  3247. # Different printer models use different directory structures. Skipped
  3248. # when the printer's FTPS handshake is failing — the directory walk is
  3249. # five more connections that cannot get further than the download did.
  3250. if (
  3251. not downloaded_filename
  3252. and storage.reachable
  3253. and (filename or subtask_name)
  3254. and not ftps_handshake_blocked(printer.ip_address)
  3255. ):
  3256. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  3257. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  3258. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  3259. for search_dir in search_dirs:
  3260. if downloaded_filename:
  3261. break
  3262. try:
  3263. dir_files = await list_files_async(
  3264. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  3265. )
  3266. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  3267. if threemf_files:
  3268. logger.info(
  3269. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  3270. )
  3271. for f in dir_files:
  3272. if f.get("is_directory"):
  3273. continue
  3274. fname = f.get("name", "")
  3275. # Normalize both for comparison (spaces and underscores are equivalent)
  3276. fname_normalized = fname.lower().replace(" ", "_")
  3277. search_normalized = search_term.replace(" ", "_")
  3278. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  3279. logger.info("Found matching file in %s: %s", search_dir, fname)
  3280. temp_path = app_settings.archive_dir / "temp" / fname
  3281. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3282. remote_full_path = posixpath.join(search_dir, fname)
  3283. if ftp_retry_enabled:
  3284. downloaded = await with_ftp_retry(
  3285. download_file_async,
  3286. printer.ip_address,
  3287. printer.access_code,
  3288. remote_full_path,
  3289. temp_path,
  3290. timeout=ftp_timeout,
  3291. socket_timeout=ftp_timeout,
  3292. printer_model=printer.model,
  3293. max_retries=ftp_retry_count,
  3294. retry_delay=ftp_retry_delay,
  3295. operation_name=f"Download 3MF from {remote_full_path}",
  3296. )
  3297. else:
  3298. downloaded = await download_file_async(
  3299. printer.ip_address,
  3300. printer.access_code,
  3301. remote_full_path,
  3302. temp_path,
  3303. timeout=ftp_timeout,
  3304. socket_timeout=ftp_timeout,
  3305. printer_model=printer.model,
  3306. )
  3307. if downloaded:
  3308. downloaded_filename = fname
  3309. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  3310. cache_3mf_download(printer_id, fname, temp_path)
  3311. break
  3312. except Exception as e:
  3313. logger.debug("Failed to list %s: %s", search_dir, e)
  3314. # Validate the downloaded 3MF actually matches the plate that's running
  3315. # (#1204): subtask_name lags across consecutive plates of the same model,
  3316. # so the first FTP candidate (built from subtask_name) can land on the
  3317. # previous plate's still-resident upload. Cross-check the slice_info
  3318. # plate index against the plate parsed from gcode_file (always fresh —
  3319. # it's the field whose change triggered this callback).
  3320. if downloaded_filename and temp_path:
  3321. expected_plate = parse_plate_id(filename)
  3322. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  3323. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  3324. logger.warning(
  3325. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  3326. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  3327. downloaded_filename,
  3328. actual_plate,
  3329. expected_plate,
  3330. subtask_name,
  3331. )
  3332. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  3333. retry_succeeded = False
  3334. if corrected_subtask and corrected_subtask != subtask_name:
  3335. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  3336. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  3337. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  3338. for remote_path in (
  3339. f"/{try_filename}",
  3340. f"/cache/{try_filename}",
  3341. f"/model/{try_filename}",
  3342. f"/data/{try_filename}",
  3343. f"/data/Metadata/{try_filename}",
  3344. ):
  3345. try:
  3346. if ftp_retry_enabled:
  3347. downloaded = await with_ftp_retry(
  3348. download_file_async,
  3349. printer.ip_address,
  3350. printer.access_code,
  3351. remote_path,
  3352. retry_temp_path,
  3353. timeout=ftp_timeout,
  3354. socket_timeout=ftp_timeout,
  3355. printer_model=printer.model,
  3356. max_retries=ftp_retry_count,
  3357. retry_delay=ftp_retry_delay,
  3358. operation_name=f"Re-download 3MF from {remote_path}",
  3359. non_retry_exceptions=(FileNotOnPrinterError,),
  3360. )
  3361. else:
  3362. downloaded = await download_file_async(
  3363. printer.ip_address,
  3364. printer.access_code,
  3365. remote_path,
  3366. retry_temp_path,
  3367. timeout=ftp_timeout,
  3368. socket_timeout=ftp_timeout,
  3369. printer_model=printer.model,
  3370. )
  3371. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  3372. logger.info(
  3373. "[CALLBACK] Re-download succeeded with corrected name %s "
  3374. "(plate %s) — replacing wrong file",
  3375. try_filename,
  3376. expected_plate,
  3377. )
  3378. try:
  3379. temp_path.unlink(missing_ok=True)
  3380. except OSError:
  3381. pass
  3382. temp_path = retry_temp_path
  3383. downloaded_filename = try_filename
  3384. subtask_name = corrected_subtask
  3385. cache_3mf_download(printer_id, try_filename, temp_path)
  3386. retry_succeeded = True
  3387. break
  3388. elif downloaded:
  3389. # Wrong plate again — discard and keep trying
  3390. try:
  3391. retry_temp_path.unlink(missing_ok=True)
  3392. except OSError:
  3393. pass
  3394. except FileNotOnPrinterError:
  3395. continue
  3396. except Exception as e:
  3397. logger.debug("Re-download failed for %s: %s", remote_path, e)
  3398. if retry_succeeded:
  3399. break
  3400. # If the retry didn't find a matching file, drop the wrong 3MF
  3401. # so the no-3MF fallback below creates an archive whose name
  3402. # at least reflects the right plate.
  3403. if not retry_succeeded:
  3404. logger.warning(
  3405. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  3406. expected_plate,
  3407. )
  3408. try:
  3409. temp_path.unlink(missing_ok=True)
  3410. except OSError:
  3411. pass
  3412. temp_path = None
  3413. downloaded_filename = None
  3414. # Override the stale subtask_name so the fallback archive's
  3415. # print_name reflects the correct plate. Prefer the swapped
  3416. # name when we have one; otherwise let filename win.
  3417. if corrected_subtask:
  3418. subtask_name = corrected_subtask
  3419. else:
  3420. subtask_name = ""
  3421. if not downloaded_filename or not temp_path:
  3422. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  3423. # Create a fallback archive without 3MF data so the print is still tracked
  3424. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  3425. try:
  3426. from backend.app.models.archive import PrintArchive
  3427. # Derive print name from subtask_name or filename
  3428. print_name = subtask_name or filename
  3429. if print_name:
  3430. # Clean up the name (remove extensions, path parts)
  3431. print_name = print_name.split("/")[-1]
  3432. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  3433. else:
  3434. print_name = "Unknown Print"
  3435. # Recover estimated print time from MQTT (best-effort for notifications)
  3436. fallback_print_time = None
  3437. mqtt_remaining = data.get("remaining_time")
  3438. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  3439. fallback_print_time = int(mqtt_remaining)
  3440. if fallback_print_time is None:
  3441. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  3442. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  3443. fallback_print_time = int(mc_remaining * 60)
  3444. # Best-effort filament metadata from MQTT — see
  3445. # _extract_filament_data_from_mqtt. Without this the fallback
  3446. # archive's filament fields stayed NULL even though the AMS
  3447. # state at print start was sitting right there in `data`.
  3448. # The slicer's ams_mapping (when present) narrows the result
  3449. # to slots actually used by the print (#1533).
  3450. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  3451. # Create minimal archive entry
  3452. fallback_archive = PrintArchive(
  3453. printer_id=printer_id,
  3454. filename=filename or f"{print_name}.3mf",
  3455. file_path="", # Empty - no 3MF file available
  3456. file_size=0,
  3457. print_name=print_name,
  3458. print_time_seconds=fallback_print_time,
  3459. status="printing",
  3460. started_at=datetime.now(timezone.utc),
  3461. subtask_id=subtask_id,
  3462. filament_type=mqtt_filament_meta.get("filament_type"),
  3463. filament_color=mqtt_filament_meta.get("filament_color"),
  3464. extra_data={
  3465. "no_3mf_available": True,
  3466. # Why the card is empty, when we know. The banner reads
  3467. # this to stop telling H2/P2 owners to switch on a
  3468. # setting that is already on and would not help (#2780).
  3469. "no_3mf_reason": storage.reason,
  3470. "original_subtask": subtask_name,
  3471. "_print_data": data,
  3472. },
  3473. )
  3474. db.add(fallback_archive)
  3475. await db.commit()
  3476. await db.refresh(fallback_archive)
  3477. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  3478. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  3479. # Track as active print
  3480. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  3481. if filename:
  3482. _active_prints[(printer_id, filename)] = fallback_archive.id
  3483. if subtask_name:
  3484. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  3485. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  3486. # Record starting energy if smart plug available (#941: persisted column)
  3487. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  3488. # Send WebSocket notification
  3489. await ws_manager.send_archive_created(
  3490. {
  3491. "id": fallback_archive.id,
  3492. "printer_id": fallback_archive.printer_id,
  3493. "filename": fallback_archive.filename,
  3494. "print_name": fallback_archive.print_name,
  3495. "status": fallback_archive.status,
  3496. }
  3497. )
  3498. # MQTT relay - publish archive created
  3499. try:
  3500. await mqtt_relay.on_archive_created(
  3501. archive_id=fallback_archive.id,
  3502. print_name=fallback_archive.print_name,
  3503. printer_name=printer.name,
  3504. status=fallback_archive.status,
  3505. )
  3506. except Exception:
  3507. pass # Don't fail if MQTT fails
  3508. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  3509. try:
  3510. await _store_spoolman_print_data(
  3511. printer_id,
  3512. fallback_archive.id,
  3513. fallback_archive.file_path,
  3514. db,
  3515. printer_manager,
  3516. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  3517. plate_id=_get_start_plate_id(fallback_archive.id),
  3518. )
  3519. except Exception as e:
  3520. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  3521. # Send notification without archive data (file not found)
  3522. if not notification_sent:
  3523. await _send_print_start_notification(printer_id, data, logger=logger)
  3524. return
  3525. except Exception as e:
  3526. logger.error("Failed to create fallback archive: %s", e)
  3527. # Send notification without archive data (file not found)
  3528. if not notification_sent:
  3529. await _send_print_start_notification(printer_id, data, logger=logger)
  3530. return
  3531. try:
  3532. # Archive the file with status "printing"
  3533. service = ArchiveService(db)
  3534. archive = await service.archive_print(
  3535. printer_id=printer_id,
  3536. source_file=temp_path,
  3537. print_data={**data, "status": "printing"},
  3538. subtask_id=subtask_id,
  3539. )
  3540. if archive:
  3541. # Track this active print (use both original filename and downloaded filename)
  3542. _active_prints[(printer_id, downloaded_filename)] = archive.id
  3543. if filename and filename != downloaded_filename:
  3544. _active_prints[(printer_id, filename)] = archive.id
  3545. if subtask_name:
  3546. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3547. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  3548. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3549. # Record starting energy from smart plug if available (#941: persisted column)
  3550. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  3551. await ws_manager.send_archive_created(
  3552. {
  3553. "id": archive.id,
  3554. "printer_id": archive.printer_id,
  3555. "filename": archive.filename,
  3556. "print_name": archive.print_name,
  3557. "status": archive.status,
  3558. }
  3559. )
  3560. # MQTT relay - publish archive created
  3561. try:
  3562. await mqtt_relay.on_archive_created(
  3563. archive_id=archive.id,
  3564. print_name=archive.print_name,
  3565. printer_name=printer.name,
  3566. status=archive.status,
  3567. )
  3568. except Exception:
  3569. pass # Don't fail if MQTT fails
  3570. # Send notification with archive data (new archive created)
  3571. if not notification_sent:
  3572. archive_data = {
  3573. "print_time_seconds": archive.print_time_seconds,
  3574. "created_by_id": archive.created_by_id,
  3575. }
  3576. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3577. # Extract printable objects for skip object functionality
  3578. try:
  3579. from backend.app.services.archive import extract_printable_objects_from_3mf
  3580. client = printer_manager.get_client(printer_id)
  3581. if client:
  3582. with open(temp_path, "rb") as f:
  3583. threemf_data = f.read()
  3584. # Extract with positions for UI overlay, scoped to the
  3585. # plate that is printing — an all-plates 3MF carries
  3586. # every plate's objects (#2522).
  3587. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  3588. threemf_data,
  3589. plate_number=resolve_plate_id(client.state),
  3590. include_positions=True,
  3591. )
  3592. if printable_objects:
  3593. # Store objects in printer state
  3594. client.state.printable_objects = printable_objects
  3595. client.state.printable_objects_bbox_all = bbox_all
  3596. client.state.skipped_objects = [] # Reset skipped objects for new print
  3597. logger.info(
  3598. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  3599. )
  3600. except Exception as e:
  3601. logger.debug("Failed to extract printable objects: %s", e)
  3602. # Store Spoolman tracking data for per-filament usage reporting
  3603. try:
  3604. await _store_spoolman_print_data(
  3605. printer_id,
  3606. archive.id,
  3607. archive.file_path,
  3608. db,
  3609. printer_manager,
  3610. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3611. plate_id=_get_start_plate_id(archive.id),
  3612. )
  3613. except Exception as e:
  3614. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3615. # Capture timelapse file baseline for snapshot-diff on completion
  3616. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3617. finally:
  3618. # Keep temp_path around until print completes so the cover endpoint
  3619. # can reuse it (#972). Cache eviction in on_print_complete deletes
  3620. # the file. If the cache entry was evicted early (file vanished),
  3621. # clean up any stragglers here to avoid leaking disk on retries.
  3622. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  3623. if temp_path and temp_path.exists() and cached_now != temp_path:
  3624. temp_path.unlink()
  3625. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  3626. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  3627. # tests can shrink them without waiting out real delays.
  3628. #
  3629. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  3630. # looking. Across 247 support bundles the attempt that found the video was #1
  3631. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  3632. # decaying one, which is the signature of a budget that expires while files are
  3633. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  3634. # prints make big videos and the printer writes them after the print ends, so
  3635. # the poll now runs for minutes and costs one FTP LIST per round.
  3636. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  3637. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  3638. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  3639. def _timelapse_scan_max_attempts() -> int:
  3640. """Round cap for the poll, derived from the wall-clock budget.
  3641. The deadline alone is not a sufficient bound: it assumes each round really
  3642. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  3643. and an FTP list that fails immediately would otherwise spin against the
  3644. printer at full speed for the whole window. Whichever bound is reached
  3645. first ends the poll.
  3646. """
  3647. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  3648. # A zero interval makes the wall-clock budget meaningless; fall back to
  3649. # the round count the production interval would have given.
  3650. return 32
  3651. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  3652. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  3653. """Video filenames already attached to some other archive of this printer.
  3654. Used to disambiguate when more than one file is new since the baseline —
  3655. which happens when a previous print's video landed after this print's
  3656. baseline was taken. Ordering the candidates would be the obvious fix and is
  3657. the wrong one: it can only be done on mtime or on the filename timestamp,
  3658. both of which come from the printer's own clock, and a LAN-only printer
  3659. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  3660. ``attach_timelapse`` saves the video into the archive directory under the
  3661. printer's original filename, and the later MP4 conversion keeps the stem,
  3662. so the stem of ``timelapse_path`` recovers what was claimed.
  3663. """
  3664. from backend.app.models.archive import PrintArchive
  3665. rows = await db.execute(
  3666. select(PrintArchive.timelapse_path).where(
  3667. PrintArchive.printer_id == printer_id,
  3668. PrintArchive.id != exclude_archive_id,
  3669. PrintArchive.timelapse_path.is_not(None),
  3670. )
  3671. )
  3672. return {Path(p).stem for p in rows.scalars().all() if p}
  3673. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  3674. """List video files from printer's timelapse directory.
  3675. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  3676. Returns (video_files, found_path) where video_files is a list of file dicts
  3677. and found_path is the directory where they were found, or ([], None).
  3678. """
  3679. from backend.app.services.bambu_ftp import list_files_async
  3680. logger = logging.getLogger(__name__)
  3681. # No card in the slot means no /timelapse to walk — four connections that
  3682. # can only fail, on a path whose failures are swallowed and so would go on
  3683. # costing time silently forever (#2780).
  3684. #
  3685. # ``getattr`` rather than ``printer.id``: every dereference below happens
  3686. # inside the loop's own try/except, so a caller that passed something
  3687. # unexpected used to get an empty listing rather than an exception. Keep
  3688. # that, instead of making this gate the first thing that can raise here.
  3689. printer_id = getattr(printer, "id", None)
  3690. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  3691. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  3692. return [], None
  3693. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  3694. try:
  3695. found_files = await list_files_async(
  3696. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  3697. )
  3698. if found_files:
  3699. video_files = [
  3700. f
  3701. for f in found_files
  3702. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  3703. ]
  3704. if video_files:
  3705. return video_files, timelapse_path
  3706. except Exception as e:
  3707. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  3708. continue
  3709. return [], None
  3710. async def _capture_timelapse_baseline_at_start(
  3711. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  3712. ) -> None:
  3713. """Snapshot the printer's timelapse directory at print start so the
  3714. completion-time scan can pick the new file by set-difference.
  3715. Must be called from every on_print_start path that proceeds to a real
  3716. print — both the new-archive branch and the expected-archive branch (which
  3717. queue / VP-dispatched prints take). Without a baseline,
  3718. _scan_for_timelapse_with_retries falls into its "take baseline now"
  3719. fallback that runs AFTER the new MP4 has already landed on the SD card,
  3720. so the new file ends up in the "baseline" set and no diff ever matches.
  3721. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  3722. unreliable — the snapshot-diff approach sidesteps that entirely.
  3723. When ``archive_id`` is known the baseline is also written to the archive
  3724. row, so it survives a restart and the manual "Scan for Timelapse" button
  3725. can run the same diff instead of falling back to clock-based matching
  3726. (#2704). Only baselines taken at print start are persisted — one taken at
  3727. completion already contains the new video and would poison a later scan.
  3728. """
  3729. names: set[str] | None = None
  3730. try:
  3731. baseline_files, _ = await _list_timelapse_videos(printer)
  3732. names = {f.get("name", "") for f in baseline_files}
  3733. _timelapse_baselines[printer_id] = names
  3734. logger.info(
  3735. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  3736. len(names),
  3737. printer_id,
  3738. )
  3739. except Exception as e:
  3740. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  3741. if archive_id is None:
  3742. return
  3743. try:
  3744. async with async_session() as db:
  3745. from backend.app.models.archive import PrintArchive
  3746. archive = await db.get(PrintArchive, archive_id)
  3747. if archive is not None:
  3748. # Written even when the listing failed, and then as NULL. A
  3749. # reprint reuses the archive row, so leaving the previous run's
  3750. # baseline in place would have the scan diff this print against
  3751. # the state of the printer before the *last* one — and a stale
  3752. # baseline reads as authoritative, where NULL correctly falls
  3753. # back to a fresh snapshot.
  3754. archive.timelapse_baseline = sorted(names) if names is not None else None
  3755. await db.commit()
  3756. except Exception as e:
  3757. # In-memory baseline still covers the normal completion path.
  3758. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  3759. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  3760. """Poll the printer for this print's timelapse and attach it.
  3761. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  3762. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  3763. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  3764. (#2704). Comparing the current listing against the set of filenames that
  3765. existed when the print started needs no clock at all, because the printer
  3766. writes the video only once the print has ended.
  3767. Baseline precedence: the caller's in-memory set, then the one persisted on
  3768. the archive at print start, then a snapshot taken now. The last of those is
  3769. a poor substitute — by completion the new video may already be on the card,
  3770. in which case it lands in the "baseline" and no diff can ever match — but it
  3771. is all that is available for a print that began before Bambuddy started.
  3772. On success the video is deleted from the printer, which keeps ``/timelapse``
  3773. down to the unclaimed files and makes the next diff unambiguous.
  3774. """
  3775. logger = logging.getLogger(__name__)
  3776. # --- Phase 1: establish the baseline -------------------------------------
  3777. try:
  3778. async with async_session() as db:
  3779. from backend.app.models.printer import Printer
  3780. service = ArchiveService(db)
  3781. archive = await service.get_archive(archive_id)
  3782. if not archive:
  3783. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  3784. return
  3785. if archive.timelapse_path:
  3786. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  3787. return
  3788. if not archive.printer_id:
  3789. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  3790. return
  3791. if baseline_names is not None:
  3792. logger.info(
  3793. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  3794. len(baseline_names),
  3795. archive_id,
  3796. )
  3797. elif archive.timelapse_baseline is not None:
  3798. # Persisted at print start — survives a restart mid-print.
  3799. baseline_names = set(archive.timelapse_baseline)
  3800. logger.info(
  3801. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  3802. len(baseline_names),
  3803. archive_id,
  3804. )
  3805. else:
  3806. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3807. printer = result.scalar_one_or_none()
  3808. if not printer:
  3809. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  3810. return
  3811. baseline_files, _ = await _list_timelapse_videos(printer)
  3812. baseline_names = {f.get("name", "") for f in baseline_files}
  3813. logger.info(
  3814. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  3815. len(baseline_names),
  3816. archive_id,
  3817. )
  3818. except Exception as e:
  3819. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  3820. return
  3821. # --- Phase 2: poll for a file that was not there when the print began -----
  3822. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  3823. max_attempts = _timelapse_scan_max_attempts()
  3824. seen_names: set[str] = set()
  3825. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  3826. attempt = 0
  3827. while True:
  3828. await asyncio.sleep(delay)
  3829. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  3830. attempt += 1
  3831. try:
  3832. from backend.app.models.printer import Printer
  3833. # Read phase: fetch archive + printer in a short session and release
  3834. # the pooled connection BEFORE the FTP list/download below. Holding it
  3835. # across the FTP round-trips left one connection idle-in-transaction per
  3836. # in-flight scan (issue #2572).
  3837. async with async_session() as db:
  3838. service = ArchiveService(db)
  3839. archive = await service.get_archive(archive_id)
  3840. if not archive:
  3841. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  3842. return
  3843. if archive.timelapse_path:
  3844. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  3845. return
  3846. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3847. printer = result.scalar_one_or_none()
  3848. if not printer:
  3849. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  3850. return
  3851. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  3852. # I/O phase (no DB connection held): FTP list + download.
  3853. video_files, found_path = await _list_timelapse_videos(printer)
  3854. # The poll can run for dozens of rounds, so only narrate a round
  3855. # that saw something change. Repeating the whole listing every 30 s
  3856. # would bury the one interesting line in the support bundle.
  3857. names_now = {f.get("name", "") for f in video_files}
  3858. changed = attempt == 1 or names_now != seen_names
  3859. seen_names = names_now
  3860. speak = logger.info if changed else logger.debug
  3861. if video_files:
  3862. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  3863. if changed:
  3864. for f in video_files[:5]:
  3865. logger.info("[TIMELAPSE] - %s", f.get("name"))
  3866. attached = await _attach_first_unclaimed_timelapse(
  3867. archive_id, printer, video_files, baseline_names, claimed, attempt, logger, quiet=not changed
  3868. )
  3869. if attached:
  3870. return
  3871. else:
  3872. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  3873. except Exception as e:
  3874. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  3875. if attempt >= max_attempts or time.monotonic() >= deadline:
  3876. break
  3877. # No name-match fallback: it compared the print name against the filename,
  3878. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  3879. # bundles it fired 159 times and matched zero times, so all it added was a
  3880. # misleading log line before giving up.
  3881. logger.warning(
  3882. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  3883. archive_id,
  3884. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  3885. )
  3886. async def _attach_first_unclaimed_timelapse(
  3887. archive_id: int,
  3888. printer,
  3889. video_files: list[dict],
  3890. baseline_names: set[str],
  3891. claimed: set[str],
  3892. attempt: int,
  3893. logger: logging.Logger,
  3894. *,
  3895. quiet: bool = False,
  3896. ) -> bool:
  3897. """Download and attach the one video that belongs to this print.
  3898. A candidate is any file absent from the print-start baseline. More than one
  3899. can qualify when a previous print's video landed late, after this print's
  3900. baseline was taken — those are filtered out by name, because they are
  3901. already attached to another archive. Sorting the candidates instead would
  3902. mean sorting on mtime or on the filename timestamp, both of which come from
  3903. the printer's unsynced clock.
  3904. Returns True once a video is attached. The printer's copy is deleted only
  3905. after the attach succeeds on bytes whose length matched the listing.
  3906. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  3907. already seen this exact listing — the poll runs for many rounds and only the
  3908. rounds where something changed are worth an INFO line.
  3909. """
  3910. from backend.app.services.bambu_ftp import (
  3911. delete_archived_timelapse,
  3912. download_file_bytes_async,
  3913. remote_file_settled,
  3914. )
  3915. speak = logger.debug if quiet else logger.info
  3916. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  3917. if not new_files:
  3918. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  3919. return False
  3920. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  3921. if not candidates:
  3922. speak(
  3923. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  3924. attempt,
  3925. len(new_files),
  3926. )
  3927. return False
  3928. if len(candidates) > 1:
  3929. logger.warning(
  3930. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  3931. "the rest stay on the printer for manual selection",
  3932. attempt,
  3933. len(candidates),
  3934. ", ".join(str(f.get("name")) for f in candidates),
  3935. )
  3936. target = candidates[0]
  3937. file_name = target.get("name")
  3938. remote_path = target.get("path") or f"/timelapse/{file_name}"
  3939. logger.info(
  3940. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  3941. attempt,
  3942. file_name,
  3943. archive_id,
  3944. )
  3945. # The listing always carries a size (`list_files` skips entries it can't
  3946. # parse), but read it explicitly: the delete below is destructive and must
  3947. # depend on a size we actually had, not on one we hoped was there.
  3948. expected_size = target.get("size")
  3949. timelapse_data = await download_file_bytes_async(
  3950. printer.ip_address,
  3951. printer.access_code,
  3952. remote_path,
  3953. printer_model=printer.model,
  3954. expected_size=expected_size,
  3955. )
  3956. if not timelapse_data:
  3957. # Short or failed transfer. The printer keeps its copy, so the next
  3958. # round can try again — which is exactly why the delete below is
  3959. # gated on a verified download.
  3960. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  3961. return False
  3962. # The length check above proves we got what the listing said, not that the
  3963. # printer had finished writing. A video still being written can be listed
  3964. # short, served short, and pass — so confirm it has stopped growing before
  3965. # committing to it and deleting the original (#2704).
  3966. if not await remote_file_settled(
  3967. printer.ip_address,
  3968. printer.access_code,
  3969. remote_path,
  3970. len(timelapse_data),
  3971. printer_model=printer.model,
  3972. ):
  3973. return False
  3974. # Write phase: attach in a fresh short-lived session.
  3975. async with async_session() as db:
  3976. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  3977. if not success:
  3978. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  3979. return False
  3980. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  3981. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  3982. await delete_archived_timelapse(
  3983. printer.ip_address,
  3984. printer.access_code,
  3985. remote_path,
  3986. verified=expected_size is not None,
  3987. printer_model=printer.model,
  3988. printer_name=printer.name,
  3989. )
  3990. return True
  3991. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  3992. # module-level so tests can monkeypatch them down to ~0 without timing out.
  3993. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  3994. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  3995. # How long the *background* upgrade keeps waiting after the notification has
  3996. # already gone out (#2704 follow-up). The short bound above exists so a slow
  3997. # printer can't hold up the print-complete notification; this one exists so the
  3998. # archive still ends up with the better frame afterwards.
  3999. #
  4000. # Measured across 261 attaches in the support bundles, the video lands a median
  4001. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  4002. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  4003. # was 546s. Every other model was inside 26s. The long budget is therefore
  4004. # almost entirely for P1-series users; on everything else the short wait already
  4005. # wins and this task never runs.
  4006. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  4007. async def _capture_finish_photo_from_timelapse(
  4008. archive_id: int,
  4009. archive_dir: Path,
  4010. timeout: float | None = None,
  4011. rotation: int = 0,
  4012. ) -> tuple[str | None, bool]:
  4013. """Wait for the per-print timelapse to land on the archive and extract its
  4014. last frame as the finish photo (#1397).
  4015. Bambu firmware stops timelapse recording after the toolhead parks but
  4016. before the bed-drop end-gcode runs, so the last frame frames the finished
  4017. print correctly. A live camera grab at gcode_state=FINISH captures the
  4018. bed already lowered.
  4019. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  4020. ``archive.timelapse_path`` when the file lands. This function polls for
  4021. that field.
  4022. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  4023. the wait ran out with no video on the archive yet — i.e. the video may
  4024. still be coming and a later attempt could succeed. It is False when the
  4025. video landed (whether or not extraction worked), because in that case
  4026. waiting longer changes nothing. The caller uses that to decide between
  4027. falling back permanently and scheduling a background upgrade.
  4028. ``rotation`` is the printer's camera_rotation, applied to the extracted
  4029. still (#2708) so this source agrees with every other finish-photo source.
  4030. The archived video itself is the printer's own file and is left alone —
  4031. rotating it would mean re-encoding it.
  4032. """
  4033. import uuid
  4034. from backend.app.models.archive import PrintArchive
  4035. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  4036. logger = logging.getLogger(__name__)
  4037. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  4038. deadline = asyncio.get_event_loop().time() + budget
  4039. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  4040. while True:
  4041. async with async_session() as db:
  4042. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4043. archive = result.scalar_one_or_none()
  4044. timelapse_relpath = archive.timelapse_path if archive else None
  4045. if timelapse_relpath:
  4046. video_path = app_settings.base_dir / timelapse_relpath
  4047. if video_path.exists() and video_path.stat().st_size > 0:
  4048. photos_dir = archive_dir / "photos"
  4049. photos_dir.mkdir(parents=True, exist_ok=True)
  4050. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4051. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4052. output_path = photos_dir / filename
  4053. if await extract_video_last_frame(video_path, output_path):
  4054. await apply_camera_rotation_to_file(output_path, rotation, logger)
  4055. logger.info(
  4056. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  4057. video_path.name,
  4058. archive_id,
  4059. )
  4060. return filename, False
  4061. logger.warning(
  4062. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  4063. video_path.name,
  4064. archive_id,
  4065. )
  4066. return None, False
  4067. if asyncio.get_event_loop().time() >= deadline:
  4068. logger.info(
  4069. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  4070. archive_id,
  4071. budget,
  4072. )
  4073. return None, True
  4074. await asyncio.sleep(poll_interval)
  4075. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  4076. """Add the timelapse's last frame to an archive after the fact (#2704).
  4077. The print-complete notification waits only ~60s for the video, because
  4078. holding a notification for minutes is worse than sending it with a live
  4079. camera grab. On a P1-series printer the video often lands well after that,
  4080. so the archive used to be stuck with the live grab — which is taken at
  4081. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  4082. the worse photo of the two.
  4083. This keeps waiting in the background and, when the video arrives, extracts
  4084. the frame and puts it *first* in the archive's photo list, so opening the
  4085. gallery shows it. The live grab is deliberately kept: the notification that
  4086. already went out links to that exact file, and deleting it would leave a
  4087. broken image in Discord or Telegram.
  4088. """
  4089. logger = logging.getLogger(__name__)
  4090. filename, _ = await _capture_finish_photo_from_timelapse(
  4091. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  4092. )
  4093. if not filename:
  4094. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  4095. return
  4096. try:
  4097. async with async_session() as db:
  4098. from backend.app.models.archive import PrintArchive
  4099. archive = await db.get(PrintArchive, archive_id)
  4100. if archive is None:
  4101. return
  4102. photos = list(archive.photos or [])
  4103. if filename in photos:
  4104. return
  4105. # Front of the list: PhotoGalleryModal opens at index 0.
  4106. archive.photos = [filename, *photos]
  4107. await db.commit()
  4108. except Exception as e:
  4109. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  4110. return
  4111. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  4112. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  4113. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  4114. """Put the filament-attribution context back after a restart mid-print.
  4115. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  4116. both die with the process. The print keeps running, so at completion the
  4117. tracker would fall back to whatever the printer reports *now* — and AMS
  4118. filament backup makes "now" the substitute tray, charging the whole print
  4119. to the spool that only finished it.
  4120. The persisted row is only trusted when its print name still matches what
  4121. the printer says it is running: a row left behind by a completion we never
  4122. saw must not attach itself to the next print.
  4123. """
  4124. try:
  4125. from backend.app.api.routes.settings import get_setting
  4126. from backend.app.services.usage_tracker import (
  4127. clear_persisted_session,
  4128. get_persisted_print_name,
  4129. restore_session,
  4130. )
  4131. persisted_name = await get_persisted_print_name(db, printer_id)
  4132. current_name = (state.subtask_name or "").strip()
  4133. if persisted_name and current_name and persisted_name.strip() != current_name:
  4134. logger.info(
  4135. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  4136. printer_id,
  4137. persisted_name,
  4138. current_name,
  4139. )
  4140. await clear_persisted_session(db, printer_id)
  4141. # Fall through to seeding: the print on the printer is real, it just
  4142. # isn't the one the row described.
  4143. persisted_log = None
  4144. else:
  4145. # Spoolman users get the tray-change log back but no in-memory
  4146. # session — see ``on_print_start`` on why that dict is load-bearing
  4147. # for the remain%-sync guard.
  4148. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4149. persisted_log = await restore_session(
  4150. db,
  4151. printer_id,
  4152. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  4153. )
  4154. if persisted_log:
  4155. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  4156. # Anything this process already observed goes after the persisted
  4157. # history — the log is ordered by layer, and a fresh process can
  4158. # only have seen changes from later in the print.
  4159. for entry in state.tray_change_log or []:
  4160. if tuple(entry) not in restored:
  4161. restored.append(tuple(entry))
  4162. state.tray_change_log = restored
  4163. tray_now = state.tray_now
  4164. if 0 <= tray_now <= 254:
  4165. if not state.tray_change_log:
  4166. # No persisted history — a print that started before this build,
  4167. # or before the row existed. Seed with the tray feeding right
  4168. # now so the remainder of the print is at least attributable to
  4169. # the right spool.
  4170. state.tray_change_log = [(tray_now, state.layer_num)]
  4171. logger.info(
  4172. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  4173. printer_id,
  4174. tray_now,
  4175. state.layer_num,
  4176. )
  4177. # The tray handler updates ``last_loaded_tray`` on every push
  4178. # regardless of whether it logged a change, so re-align it to avoid
  4179. # a duplicate entry on the next push. Only ever with a real tray:
  4180. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  4181. # 255" fallback, and writing 255 into it would defeat that.
  4182. state.last_loaded_tray = tray_now
  4183. except Exception:
  4184. # Never let attribution recovery cost the caller its timelapse
  4185. # baseline — that capture has to happen before the printer uploads
  4186. # the in-flight MP4 and there is no second chance at it.
  4187. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  4188. async def on_print_running_observed(printer_id: int, data: dict):
  4189. """Restart-recovery for a print that started before Bambuddy came up.
  4190. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  4191. after Bambuddy startup (#1304 guard, prevents duplicate archive
  4192. creation). This hook restores the persisted archive into ``_active_prints``
  4193. and captures the timelapse baseline that normally hangs off print start.
  4194. Fires once per session, in lieu of on_print_start when restart-recovery
  4195. kicks in. The printer doesn't upload the timelapse until after PRINT
  4196. COMPLETE, so a baseline captured any time during the print is still
  4197. pre-upload.
  4198. """
  4199. logger = logging.getLogger(__name__)
  4200. async with async_session() as db:
  4201. from backend.app.models.printer import Printer
  4202. state = printer_manager.get_status(printer_id)
  4203. if state is not None:
  4204. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  4205. if authorization is True:
  4206. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  4207. await _restore_usage_tracking_session(printer_id, state, db, logger)
  4208. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4209. printer = result.scalar_one_or_none()
  4210. if not printer:
  4211. logger.warning(
  4212. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  4213. printer_id,
  4214. )
  4215. return
  4216. # Avoid double-capture: ownership reconciliation above must still run when
  4217. # a baseline already exists, but the camera work itself is one-shot.
  4218. if printer_id in _timelapse_baselines:
  4219. logger.debug(
  4220. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  4221. printer_id,
  4222. )
  4223. return
  4224. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  4225. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  4226. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  4227. against the printer's current MQTT state.
  4228. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  4229. COMPLETE events, typically a print finishing during an MQTT disconnect
  4230. window followed by a smart-plug power cycle):
  4231. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  4232. provably not running anymore — only branch that should fire under
  4233. normal disconnect-then-reconnect timing.
  4234. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  4235. firmware mints a fresh ``subtask_id`` for each print, including the
  4236. ghost replay it runs after a power cycle from a leftover SD file —
  4237. so a mismatch unambiguously means the in-DB archive is no longer
  4238. the print on the printer.
  4239. 3. Printer is running but ``subtask_name`` is empty. The printer
  4240. doesn't know what it's running; the archive's reference to it is
  4241. already broken.
  4242. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  4243. with matching subtask_id+subtask_name is left alone. The cost of a false
  4244. positive is a duplicate archive on the next real PRINT COMPLETE — the
  4245. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  4246. clears on synthesis, so the real completion creates a fresh row instead
  4247. of overwriting the synthesised one (#1679). The cost of a false negative
  4248. is the ghost-print loop in #1542.
  4249. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  4250. MQTT has connected but the first ``push_status`` response hasn't been
  4251. applied yet — ``PrinterState`` is sitting on its construction defaults.
  4252. The reconcile caller in ``on_printer_status_change`` is already gated
  4253. on a real ``state.state``, so in normal operation this branch is
  4254. unreachable; it's kept as belt-and-braces for future callers and for
  4255. the narrow window where a partial state update could arrive
  4256. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  4257. ``not stale`` on degenerate input is strictly conservative: a real
  4258. stale archive will still be caught by the next push_status arriving
  4259. with terminal state.
  4260. """
  4261. current_state = (state.state or "").upper()
  4262. if current_state in ("", "UNKNOWN"):
  4263. # No real push_status yet — PrinterState defaults are not evidence.
  4264. return False, ""
  4265. if current_state in ("IDLE", "FINISH", "FAILED"):
  4266. return True, f"printer state {current_state}"
  4267. # Below here the printer is in a running / pre-running state (RUNNING /
  4268. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  4269. current_subtask_id = (state.subtask_id or "").strip()
  4270. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  4271. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  4272. current_subtask_name = (state.subtask_name or "").strip()
  4273. if not current_subtask_name:
  4274. return True, "printer subtask_name empty"
  4275. return False, ""
  4276. async def reconcile_stale_active_prints(printer_id: int) -> int:
  4277. """Synthesise ``on_print_complete`` for archives whose print can't be
  4278. running on the printer anymore.
  4279. Called once per MQTT (re)connection (from on_printer_status_change when
  4280. the connected edge flips False → True) and at Bambuddy startup (from
  4281. the FastAPI lifespan). Without this, a print that completes during a
  4282. disconnect window — followed by a smart-plug-driven power cycle — leaves
  4283. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  4284. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  4285. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  4286. power cycle until the operator notices (#1542 follow-up). Reconciliation
  4287. closes the loop by faking the missed PRINT COMPLETE — the existing
  4288. cleanup chain handles SD-file deletion, status updates, usage tracking,
  4289. and notifications.
  4290. Synthesised ``status="aborted"`` is the conservative label: we have no
  4291. proof the print finished successfully (and no progress evidence to
  4292. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  4293. fires later, overwrites the status with the correct value.
  4294. Returns the number of archives reconciled.
  4295. """
  4296. state = printer_manager.get_status(printer_id)
  4297. if not state:
  4298. return 0
  4299. # Don't reconcile while disconnected — we'd be making a decision against
  4300. # stale cached state. The connected → reconcile edge handles this.
  4301. if not state.connected:
  4302. return 0
  4303. from backend.app.models.archive import PrintArchive
  4304. reconciled = 0
  4305. async with async_session() as db:
  4306. result = await db.execute(
  4307. select(PrintArchive).where(
  4308. PrintArchive.printer_id == printer_id,
  4309. PrintArchive.status == "printing",
  4310. )
  4311. )
  4312. active = list(result.scalars().all())
  4313. if not active:
  4314. return 0
  4315. logger = logging.getLogger(__name__)
  4316. for archive in active:
  4317. is_stale, reason = _is_active_archive_stale(archive, state)
  4318. if not is_stale:
  4319. continue
  4320. logger.info(
  4321. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  4322. printer_id,
  4323. archive.id,
  4324. archive.filename,
  4325. reason,
  4326. )
  4327. # Synthesised payload: minimal fields the on_print_complete chain
  4328. # needs. `_reconciled` marker lets downstream code distinguish this
  4329. # from a real MQTT-driven completion if it ever needs to (e.g. for
  4330. # metrics / debug logging). raw_data is the live printer state so
  4331. # the usage tracker can compare end-of-print remain% against the
  4332. # captured start values.
  4333. try:
  4334. await on_print_complete(
  4335. printer_id,
  4336. {
  4337. "status": "aborted",
  4338. "filename": archive.filename,
  4339. "subtask_name": archive.print_name or "",
  4340. "subtask_id": archive.subtask_id or "",
  4341. "raw_data": state.raw_data or {},
  4342. "_reconciled": True,
  4343. },
  4344. )
  4345. reconciled += 1
  4346. except Exception as e:
  4347. # Catch-all: a reconciliation failure must not block the
  4348. # printer's normal status flow. The archive stays in
  4349. # ``status="printing"`` and the next reconnect retries.
  4350. logger.warning(
  4351. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  4352. archive.id,
  4353. e,
  4354. )
  4355. return reconciled
  4356. # #2547: clearance left between the nozzle and the top of the print when the
  4357. # plate is commanded back into camera framing. The nozzle is parked away from
  4358. # the part by then, so this is belt-and-braces against a max_z_height that
  4359. # under-reports (e.g. a slicer that excludes a final Z hop).
  4360. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  4361. # How far below the restored position to drop the plate again afterwards, so
  4362. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  4363. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  4364. # on machines with less headroom.
  4365. _PLATE_PARK_DROP_MM = 100.0
  4366. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  4367. # this axis, so it is a proven-safe speed for the full travel.
  4368. _PLATE_RESTORE_FEEDRATE = 600
  4369. # Time allowed for the plate to reach the restored position before the camera
  4370. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  4371. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  4372. # How long `_background_finish_photo` waits for this producer. Must cover the
  4373. # settle window plus a worst-case RTSP grab (15s), and stay below the
  4374. # notification path's own photo wait so a slow producer degrades to a
  4375. # photo-less notification rather than a missed one.
  4376. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  4377. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  4378. """Height of the print that just finished on ``printer_id``, or None (#2547).
  4379. This number becomes the target of a real Z move, so every step here refuses
  4380. rather than guesses. A height belonging to some *other* print is the one
  4381. failure that could drive the nozzle into the model: 20 mm carried onto a
  4382. 200 mm print would command the plate up through the part.
  4383. Two independent things therefore have to agree before a height is returned:
  4384. 1. **Identity.** The archive is matched by the finished print's own
  4385. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  4386. resolve to "Cube v2". Matching on "most recent archive for this printer"
  4387. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  4388. binding concurrently with us, and a print Bambuddy failed to archive
  4389. would silently resolve to its predecessor.
  4390. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  4391. match the layer count the printer itself reported over MQTT for the print
  4392. that just ended. These come from genuinely different sources, so a
  4393. mismatch means the row is not this print, whatever its name says.
  4394. ``completed`` is accepted alongside ``printing`` only because
  4395. ``on_print_complete`` may already have flipped the status by the time we
  4396. run; the identity check above is what actually selects the row.
  4397. """
  4398. subtask_name = (data.get("subtask_name") or "").strip()
  4399. if not subtask_name:
  4400. # Nothing to identify the print by — refuse rather than fall back to
  4401. # "whatever ran last on this printer".
  4402. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  4403. return None
  4404. try:
  4405. from backend.app.models.archive import PrintArchive
  4406. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  4407. async with async_session() as db:
  4408. result = await db.execute(
  4409. select(PrintArchive)
  4410. .where(
  4411. PrintArchive.printer_id == printer_id,
  4412. PrintArchive.status.in_(("printing", "completed")),
  4413. PrintArchive.deleted_at.is_(None),
  4414. or_(
  4415. PrintArchive.print_name == subtask_name,
  4416. PrintArchive.filename == subtask_name,
  4417. PrintArchive.filename == f"{subtask_name}.3mf",
  4418. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  4419. ),
  4420. )
  4421. .order_by(PrintArchive.id.desc())
  4422. .limit(1)
  4423. )
  4424. archive = result.scalar_one_or_none()
  4425. if archive is None or not archive.file_path:
  4426. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  4427. return None
  4428. client = printer_manager.get_client(printer_id)
  4429. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  4430. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  4431. logger.warning(
  4432. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  4433. "— refusing to move the plate on a height that may not be this print's",
  4434. printer_id,
  4435. archive.id,
  4436. archive.total_layers,
  4437. reported_layers,
  4438. )
  4439. return None
  4440. path = Path(archive.file_path)
  4441. if not path.is_absolute():
  4442. path = Path(app_settings.data_dir) / path
  4443. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  4444. except Exception as e:
  4445. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  4446. return None
  4447. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  4448. """Raise the plate back into camera framing before the finish photo (#2547).
  4449. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  4450. the time ``gcode_state`` reaches FINISH the finished print sits far below
  4451. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  4452. This commands an absolute ``G1 Z`` back to just above the last printed
  4453. layer.
  4454. Absolute, not relative, is the whole safety argument. ``max_z_height +
  4455. clearance`` is a height the toolhead was physically at seconds earlier, so
  4456. it is inside the travel limits by construction and leaves the nozzle above
  4457. the part. It is also unambiguous across model families: Z is the
  4458. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  4459. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  4460. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  4461. (#2579).
  4462. Returns True if the move was sent and waited out, False if it was skipped.
  4463. """
  4464. client = printer_manager.get_client(printer_id)
  4465. if client is None:
  4466. return False
  4467. # Re-read state immediately before commanding motion. If the queue has
  4468. # already started the next print, the printer is no longer ours to move.
  4469. state = getattr(client, "state", None)
  4470. if state is None or state.state != "FINISH":
  4471. logger.info(
  4472. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  4473. printer_id,
  4474. getattr(state, "state", "unknown"),
  4475. )
  4476. return False
  4477. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  4478. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  4479. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  4480. return False
  4481. logger.info(
  4482. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  4483. printer_id,
  4484. target_z,
  4485. max_z_height,
  4486. _PLATE_RESTORE_CLEARANCE_MM,
  4487. _PLATE_RESTORE_SETTLE_SECONDS,
  4488. )
  4489. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  4490. return True
  4491. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  4492. """Drop the plate again after the finish photo (#2547).
  4493. Without this the user walks up to a finished print sitting just under the
  4494. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  4495. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  4496. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  4497. print homes anyway.
  4498. """
  4499. client = printer_manager.get_client(printer_id)
  4500. state = getattr(client, "state", None) if client else None
  4501. if client is None or state is None or state.state != "FINISH":
  4502. return
  4503. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  4504. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  4505. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  4506. """True if a queue item is about to take this printer (#2547).
  4507. The scheduler dispatches the next job the moment a print completes, and a
  4508. plate move interleaved with a print start is not a race worth having. The
  4509. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  4510. this window; this closes the head of it.
  4511. """
  4512. try:
  4513. from backend.app.models.print_queue import PrintQueueItem
  4514. async with async_session() as db:
  4515. result = await db.execute(
  4516. select(PrintQueueItem.id)
  4517. .where(
  4518. PrintQueueItem.printer_id == printer_id,
  4519. PrintQueueItem.status.in_(("pending", "printing")),
  4520. )
  4521. .limit(1)
  4522. )
  4523. return result.scalar_one_or_none() is not None
  4524. except Exception as e:
  4525. # Fail closed: if we can't tell, don't move the plate.
  4526. logging.getLogger(__name__).debug(
  4527. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  4528. )
  4529. return True
  4530. async def on_finish_photo_moment(printer_id: int, data: dict):
  4531. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  4532. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  4533. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  4534. fallback for prints that skip stage 22 (cancel, external-spool-only,
  4535. HMS halt, firmware variants). Grabs one frame via the same
  4536. external-camera / RTSP path the post-completion fallback uses, stores
  4537. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  4538. ``_background_finish_photo`` consume the cached bytes when it runs.
  4539. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  4540. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  4541. set to Smooth (#1721). No force-on now means the user's explicit
  4542. timelapse=off in the slicer send dialog is respected.
  4543. """
  4544. logger = logging.getLogger(__name__)
  4545. trigger = data.get("trigger", "unknown")
  4546. timelapse_was_active = bool(data.get("timelapse_was_active"))
  4547. logger.info(
  4548. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  4549. printer_id,
  4550. trigger,
  4551. timelapse_was_active,
  4552. )
  4553. # If a timelapse is actively recording, skip the pre-capture — the
  4554. # post-completion path will extract the last frame from the recorded
  4555. # video, which still provides the best framing (toolhead parked,
  4556. # before bed drop) without the per-layer parking side effects.
  4557. if timelapse_was_active:
  4558. logger.info(
  4559. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  4560. printer_id,
  4561. )
  4562. return
  4563. # #1790: register the producer-done event BEFORE the first await so the
  4564. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  4565. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  4566. # The `finally` below guarantees `set()` runs on every exit, including
  4567. # early returns and exceptions, so the consumer's bounded wait can't hang.
  4568. producer_done = asyncio.Event()
  4569. _stage22_finish_in_flight[printer_id] = producer_done
  4570. # #2547: set once the plate has actually been raised, and read by the
  4571. # `finally` below. Declared out here so a failure anywhere after the move —
  4572. # a camera timeout, a DB error — still lowers the plate again.
  4573. restore_max_z: float | None = None
  4574. try:
  4575. async with async_session() as db:
  4576. from backend.app.api.routes.settings import get_setting
  4577. from backend.app.models.printer import Printer
  4578. capture_setting = await get_setting(db, "capture_finish_photo")
  4579. if capture_setting is not None and capture_setting.lower() != "true":
  4580. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  4581. return
  4582. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  4583. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  4584. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4585. printer = result.scalar_one_or_none()
  4586. if printer is None:
  4587. logger.warning(
  4588. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  4589. printer_id,
  4590. )
  4591. return
  4592. frame_bytes: bytes | None = None
  4593. # #2708: the banked frame arrives already rotated — it comes from
  4594. # `_capture_snapshot_for_notification`, which rotates before returning.
  4595. # Every other source below is a raw grab. Tracking which lets us store
  4596. # exactly one rotation in `_stage22_finish_frames` either way.
  4597. frame_already_rotated = False
  4598. # On the FINISH-state path the End G-code has already run, and two very
  4599. # different situations arrive here needing opposite answers.
  4600. #
  4601. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  4602. # snippet may have ejected the plate — the scene in front of the camera
  4603. # is no longer the finished print, and no amount of moving the plate
  4604. # brings it back. Use the banked in-print frame instead.
  4605. #
  4606. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  4607. # than the camera frames well, and the toolhead is parked out of the
  4608. # way. That is the *best* moment available on firmware that never emits
  4609. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  4610. # back. Preferring the bank here unconditionally, as this code used to,
  4611. # is what shipped a mid-print photo with the toolhead over the part.
  4612. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  4613. banked = _inprint_frame_bank.get(printer_id)
  4614. if banked:
  4615. frame_bytes = banked
  4616. frame_already_rotated = True
  4617. logger.info(
  4618. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  4619. "frame (%d bytes) instead of a post-swap live grab",
  4620. len(banked),
  4621. )
  4622. else:
  4623. logger.warning(
  4624. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  4625. "in-print bank is empty — falling back to a live grab, which may show a "
  4626. "swapped or empty plate",
  4627. printer_id,
  4628. )
  4629. # `restore_max_z` is set only once the plate is actually up, because the
  4630. # `finally` reads it to decide whether it owes a move back down.
  4631. #
  4632. # Never on a print whose End G-code Bambuddy injected, even when the bank
  4633. # came up empty above: that machine may have just ejected its plate, and
  4634. # driving Z into whatever a swap mechanism is doing is not a risk worth
  4635. # taking for a photo of a bed we already know may be bare.
  4636. if (
  4637. frame_bytes is None
  4638. and trigger == "finish_state"
  4639. and restore_plate_enabled
  4640. and not print_dispatch_context.end_gcode_injected(printer_id)
  4641. ):
  4642. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  4643. if wants_restore is None:
  4644. logger.info(
  4645. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  4646. printer_id,
  4647. )
  4648. elif await _plate_restore_is_blocked_by_queue(printer_id):
  4649. logger.info(
  4650. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  4651. printer_id,
  4652. )
  4653. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  4654. restore_max_z = wants_restore
  4655. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  4656. from backend.app.api.routes.camera import live_frame_for_capture
  4657. from backend.app.services.external_camera import capture_frame
  4658. # #2707: this used to collide with the live view and fail, which is
  4659. # how finish-photo notifications went out with no image attached.
  4660. # Leaving frame_bytes None keeps the rest of the fallback chain.
  4661. defer, buffered = live_frame_for_capture(printer_id)
  4662. if defer:
  4663. frame_bytes = buffered
  4664. else:
  4665. frame_bytes = await capture_frame(
  4666. printer.external_camera_url,
  4667. printer.external_camera_type or "mjpeg",
  4668. snapshot_url=printer.external_camera_snapshot_url,
  4669. )
  4670. if frame_bytes:
  4671. logger.info(
  4672. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  4673. len(frame_bytes),
  4674. )
  4675. elif frame_bytes is None:
  4676. from backend.app.api.routes.camera import get_buffered_frame
  4677. buffered = get_buffered_frame(printer_id)
  4678. if buffered:
  4679. frame_bytes = buffered
  4680. logger.info(
  4681. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  4682. len(frame_bytes),
  4683. )
  4684. else:
  4685. from backend.app.services.camera import capture_camera_frame_bytes
  4686. frame_bytes = await capture_camera_frame_bytes(
  4687. ip_address=printer.ip_address,
  4688. access_code=printer.access_code,
  4689. model=printer.model,
  4690. timeout=15,
  4691. )
  4692. if frame_bytes:
  4693. logger.info(
  4694. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  4695. len(frame_bytes),
  4696. )
  4697. if frame_bytes:
  4698. if not frame_already_rotated:
  4699. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  4700. _stage22_finish_frames[printer_id] = frame_bytes
  4701. else:
  4702. logger.warning(
  4703. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  4704. printer_id,
  4705. )
  4706. except Exception as e:
  4707. logger.warning(
  4708. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  4709. printer_id,
  4710. e,
  4711. )
  4712. finally:
  4713. # #2547: we raised the plate, so we own lowering it — including when the
  4714. # capture above failed or threw partway through.
  4715. if restore_max_z is not None:
  4716. try:
  4717. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  4718. except Exception as e:
  4719. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  4720. # #1790: always unblock the consumer's bounded wait — whether we stored
  4721. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  4722. # dict entry by the consumer doesn't affect signalling.
  4723. producer_done.set()
  4724. def _subtask_name_from_filename(filename: str) -> str:
  4725. """Recover the subtask name a print command would have carried for *filename*.
  4726. The dispatcher derives the printer-facing subtask name from the archive's
  4727. file name, so stripping the extensions back off gives the value MQTT echoes
  4728. on completion. Only the two extensions Bambuddy actually stores are removed,
  4729. and in the order they nest (``.gcode.3mf``), so a model whose own name
  4730. contains a dot -- ``My.Model.3mf`` -- keeps it.
  4731. """
  4732. name = PurePosixPath(filename).name
  4733. for suffix in (".3mf", ".gcode"):
  4734. if name.lower().endswith(suffix):
  4735. name = name[: -len(suffix)]
  4736. return name
  4737. # How the printer marks a subtask name it had to cut short. Observed on real
  4738. # hardware at ~100 characters, but the cut-off is not a fixed character count
  4739. # (a name with multibyte characters came back at 98), so match the marker
  4740. # rather than a length.
  4741. _SUBTASK_TRUNCATION_MARKER = "..."
  4742. def _normalise_subtask_name(name: str) -> str:
  4743. """Canonical form for comparing a dispatched name against MQTT's echo.
  4744. The printer does not echo the name back verbatim: it substitutes
  4745. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  4746. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  4747. The 3MF lookup in this module has always known that -- it builds
  4748. space-to-underscore variants of every candidate filename, and its
  4749. directory search normalises both sides before comparing. This exists so
  4750. the completion check reads the same rule from the same place instead of
  4751. growing its own, which is exactly how it came to disagree (#2829).
  4752. """
  4753. return name.strip().replace(" ", "_").casefold()
  4754. def _subtask_names_match(expected: str, observed: str) -> bool:
  4755. """Whether two subtask names describe the same print.
  4756. Beyond the space/underscore substitution, the printer truncates long names
  4757. and marks the cut with ``...``. A truncated echo has to count as a match or
  4758. every print with a long name strands its queue item the same way.
  4759. """
  4760. expected_n = _normalise_subtask_name(expected)
  4761. observed_n = _normalise_subtask_name(observed)
  4762. if expected_n == observed_n:
  4763. return True
  4764. # Either side can be the truncated one: the printer truncates what it
  4765. # echoes, and an archive whose own filename was recorded from a previous
  4766. # truncated echo carries the marker too.
  4767. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  4768. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  4769. return True
  4770. return False
  4771. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  4772. """Whether this completion event is plausibly about *item*'s print.
  4773. The caller finds its queue row by printer and ``status='printing'`` alone,
  4774. which is all a completion event gives it -- there is no run identifier in
  4775. the MQTT payload to match on. That makes the lookup indiscriminate: any
  4776. completion delivered for this printer closes whichever row happens to be
  4777. printing, however unrelated. Comparing the subtask name against the archive
  4778. the row was dispatched with costs one primary-key load and rules that out.
  4779. Deliberately permissive: it answers False only on a positive disagreement
  4780. between two names we actually have. A row with no archive, an archive with
  4781. no file name, or an event with no subtask name is unverifiable rather than
  4782. wrong, and refusing those would strand the item in ``printing`` and wedge
  4783. the printer's queue -- a worse failure than the one being prevented.
  4784. """
  4785. observed = (data.get("subtask_name") or "").strip()
  4786. if not observed or item.archive_id is None:
  4787. return True
  4788. from backend.app.models.archive import PrintArchive
  4789. archive = await db.get(PrintArchive, item.archive_id)
  4790. if archive is None or not archive.filename:
  4791. return True
  4792. expected = _subtask_name_from_filename(archive.filename)
  4793. if not expected or _subtask_names_match(expected, observed):
  4794. return True
  4795. logging.getLogger(__name__).warning(
  4796. "Ignoring print completion for queue item %s: it was dispatched as %r "
  4797. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  4798. "printing rather than closing a run this event is not about.",
  4799. item.id,
  4800. expected,
  4801. archive.id,
  4802. archive.filename,
  4803. observed,
  4804. )
  4805. return False
  4806. async def on_print_complete(printer_id: int, data: dict):
  4807. """Handle print completion - update the archive status."""
  4808. import time
  4809. logger = logging.getLogger(__name__)
  4810. start_time = time.time()
  4811. def log_timing(section: str):
  4812. elapsed = time.time() - start_time
  4813. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  4814. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  4815. # A kill-switch stop sends its provider notification immediately. Keep the
  4816. # task so the later notification path can await it and avoid a duplicate;
  4817. # if that immediate attempt failed, the regular completion path retries.
  4818. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  4819. # Drop the 3MF download cache for this printer (#972). The print is over,
  4820. # nothing else legitimately needs the bytes; keeping them would only risk
  4821. # handing a stale file to the next print if it reuses the same name.
  4822. clear_3mf_cache(printer_id)
  4823. try:
  4824. ws_data = {
  4825. "status": data.get("status"),
  4826. "filename": data.get("filename"),
  4827. "subtask_name": data.get("subtask_name"),
  4828. "timelapse_was_active": data.get("timelapse_was_active"),
  4829. }
  4830. await ws_manager.send_print_complete(printer_id, ws_data)
  4831. log_timing("WebSocket send_print_complete")
  4832. except Exception as e:
  4833. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  4834. # Capture user info before clearing (needed for print log entry)
  4835. _print_user_info = printer_manager.get_current_print_user(printer_id)
  4836. # Clear current print user tracking (Issue #206)
  4837. printer_manager.clear_current_print_user(printer_id)
  4838. # If the user explicitly stopped this print from the queue UI the printer will
  4839. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  4840. # correct "print stopped" notification/email is sent instead of a failure alert.
  4841. _raw_status = data.get("status", "completed")
  4842. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  4843. logger.info(
  4844. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  4845. _raw_status,
  4846. printer_id,
  4847. )
  4848. data = {**data, "status": "cancelled"}
  4849. _user_stopped_printers.discard(printer_id)
  4850. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  4851. # may have left material on the bed: a user can cancel ten hours into a
  4852. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  4853. # touchscreen-stop reports `aborted` rather than `cancelled` because
  4854. # `_user_stopped_printers` is only populated when the user stops via the
  4855. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  4856. # which auto-dispatched the next queued print onto a fouled bed two seconds
  4857. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  4858. # Auto Off power cycles and Bambuddy restarts.
  4859. _final_status = data.get("status", "completed")
  4860. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  4861. printer_manager.set_awaiting_plate_clear(printer_id, True)
  4862. # MQTT relay - publish print complete
  4863. try:
  4864. printer_info = printer_manager.get_printer(printer_id)
  4865. if printer_info:
  4866. await mqtt_relay.on_print_complete(
  4867. printer_id,
  4868. printer_info.name,
  4869. printer_info.serial_number,
  4870. data.get("filename", ""),
  4871. data.get("subtask_name", ""),
  4872. data.get("status", "completed"),
  4873. )
  4874. except Exception:
  4875. pass # Don't fail print complete callback if MQTT fails
  4876. filename = data.get("filename", "")
  4877. subtask_name = data.get("subtask_name", "")
  4878. if not filename and not subtask_name:
  4879. logger.warning("Print complete without filename or subtask_name")
  4880. return
  4881. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  4882. # Build list of possible keys to try (matching how they were registered in on_print_start)
  4883. possible_keys = []
  4884. # Try subtask_name variations first (most reliable for matching)
  4885. if subtask_name:
  4886. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  4887. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4888. possible_keys.append((printer_id, subtask_name))
  4889. # Try filename variations
  4890. if filename:
  4891. # Extract just the filename if it's a path
  4892. fname = filename.split("/")[-1] if "/" in filename else filename
  4893. if fname.endswith(".3mf"):
  4894. possible_keys.append((printer_id, fname))
  4895. elif fname.endswith(".gcode"):
  4896. base_name = fname.rsplit(".", 1)[0]
  4897. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  4898. possible_keys.append((printer_id, f"{base_name}.3mf"))
  4899. possible_keys.append((printer_id, fname))
  4900. else:
  4901. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  4902. possible_keys.append((printer_id, f"{fname}.3mf"))
  4903. possible_keys.append((printer_id, fname))
  4904. # Also try full path versions
  4905. if filename.endswith(".3mf"):
  4906. possible_keys.append((printer_id, filename))
  4907. elif filename.endswith(".gcode"):
  4908. base_name = filename.rsplit(".", 1)[0]
  4909. possible_keys.append((printer_id, f"{base_name}.3mf"))
  4910. possible_keys.append((printer_id, filename))
  4911. else:
  4912. possible_keys.append((printer_id, f"{filename}.3mf"))
  4913. possible_keys.append((printer_id, filename))
  4914. # Find the archive for this print
  4915. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  4916. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  4917. archive_id = None
  4918. for key in possible_keys:
  4919. archive_id = _active_prints.pop(key, None)
  4920. if archive_id:
  4921. logger.info("Found archive %s with key %s", archive_id, key)
  4922. # Also clean up any other keys pointing to this archive
  4923. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  4924. for k in keys_to_remove:
  4925. _active_prints.pop(k, None)
  4926. break
  4927. if not archive_id:
  4928. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  4929. async with async_session() as db:
  4930. from backend.app.models.archive import PrintArchive
  4931. # Try matching by subtask_name (stored as print_name) first
  4932. if subtask_name:
  4933. result = await db.execute(
  4934. select(PrintArchive)
  4935. .where(PrintArchive.printer_id == printer_id)
  4936. .where(PrintArchive.status == "printing")
  4937. .where(
  4938. or_(
  4939. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  4940. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  4941. )
  4942. )
  4943. .order_by(PrintArchive.created_at.desc())
  4944. .limit(1)
  4945. )
  4946. archive = result.scalar_one_or_none()
  4947. if archive:
  4948. archive_id = archive.id
  4949. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  4950. # Also try by filename
  4951. if not archive_id and filename:
  4952. result = await db.execute(
  4953. select(PrintArchive)
  4954. .where(PrintArchive.printer_id == printer_id)
  4955. .where(PrintArchive.filename == filename)
  4956. .where(PrintArchive.status == "printing")
  4957. .order_by(PrintArchive.created_at.desc())
  4958. .limit(1)
  4959. )
  4960. archive = result.scalar_one_or_none()
  4961. if archive:
  4962. archive_id = archive.id
  4963. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  4964. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  4965. # auto-start files found in root on power cycle, causing ghost prints.
  4966. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  4967. try:
  4968. if subtask_name:
  4969. archive_filename: str | None = None
  4970. async with async_session() as db:
  4971. from backend.app.models.archive import PrintArchive
  4972. from backend.app.models.printer import Printer
  4973. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4974. printer = result.scalar_one_or_none()
  4975. if archive_id:
  4976. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  4977. archive_filename = archive_row.scalar_one_or_none()
  4978. if printer:
  4979. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  4980. from backend.app.utils.filename import derive_remote_filename
  4981. # Primary candidate: the exact path the dispatcher uploaded to
  4982. # (derived from archive.filename via the same rule as upload).
  4983. # Without it, a library row that ended up with a doubled
  4984. # .gcode.3mf (#1542) leaves the real file behind because the
  4985. # subtask_name + ext fallbacks below don't match what's on the
  4986. # SD card. Fallbacks remain for archive-less prints (subtask
  4987. # never resolved to an archive) and for older naming variants.
  4988. candidate_paths: list[str] = []
  4989. if archive_filename:
  4990. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  4991. for ext in (".3mf", ".gcode"):
  4992. fallback = f"/{subtask_name}{ext}"
  4993. if fallback not in candidate_paths:
  4994. candidate_paths.append(fallback)
  4995. # Three outcomes track across all candidates so the final log
  4996. # line reflects what actually happened. The A1 in #1721 always
  4997. # ends here with ``any_not_found=True`` and the others False
  4998. # — its firmware auto-cleans the SD card before our cleanup
  4999. # runs, every candidate FTP-DELE returns 550, and the old
  5000. # code burned 3 retries × 2 s × 3 candidates per print
  5001. # logging a misleading "may linger" WARNING on a successful
  5002. # print.
  5003. any_deleted = False
  5004. any_real_failure = False
  5005. any_not_found = False
  5006. for remote_path in candidate_paths:
  5007. # Retry only the FAILED case — 550 NOT_FOUND will never
  5008. # recover by waiting, so a "file isn't here" answer
  5009. # advances immediately to the next candidate without
  5010. # consuming the retry budget.
  5011. for attempt in range(1, 4):
  5012. try:
  5013. delete_result = await delete_file_async(
  5014. printer.ip_address,
  5015. printer.access_code,
  5016. remote_path,
  5017. printer_model=printer.model,
  5018. )
  5019. except Exception as e:
  5020. delete_result = DeleteResult.FAILED
  5021. logger.warning(
  5022. "SD card cleanup attempt %d/3 raised for %s: %s",
  5023. attempt,
  5024. remote_path,
  5025. e,
  5026. )
  5027. if delete_result == DeleteResult.DELETED:
  5028. any_deleted = True
  5029. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  5030. break
  5031. if delete_result == DeleteResult.NOT_FOUND:
  5032. any_not_found = True
  5033. break # 550 will not recover; try next candidate
  5034. # FAILED: real error — retry with backoff, then give up
  5035. if attempt < 3:
  5036. await asyncio.sleep(2)
  5037. else:
  5038. any_real_failure = True
  5039. logger.warning(
  5040. "SD card cleanup failed after 3 attempts for %s "
  5041. "(network/auth/transient error — file may linger on SD card)",
  5042. remote_path,
  5043. )
  5044. if not any_deleted and not any_real_failure and any_not_found:
  5045. # Every candidate said "not here." Either the printer
  5046. # firmware swept the SD card itself (common on A1) or the
  5047. # dispatcher's upload path doesn't match our candidate
  5048. # rule. Either way: nothing to clean up, no warning.
  5049. logger.debug(
  5050. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  5051. "(printer likely self-cleaned)",
  5052. printer.name,
  5053. )
  5054. except Exception as e:
  5055. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  5056. log_timing("SD card cleanup")
  5057. # Update queue item status early — must run before the archive_id early-return
  5058. # so queue items don't get stuck in "printing" when archive lookup fails.
  5059. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  5060. queue_item_id = None
  5061. billing_run_id: str | None = None
  5062. billing_user_id: int | None = None
  5063. billing_cost_center_id: int | None = None
  5064. billing_plate_id: int | None = None
  5065. queue_status = None
  5066. queue_auto_off = False
  5067. try:
  5068. from backend.app.core.database import run_with_retry
  5069. from backend.app.models.print_queue import PrintQueueItem
  5070. async def _update_queue_status(db):
  5071. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  5072. nonlocal queue_item_id, queue_status, queue_auto_off
  5073. result = await db.execute(
  5074. select(PrintQueueItem)
  5075. .where(PrintQueueItem.printer_id == printer_id)
  5076. .where(PrintQueueItem.status == "printing")
  5077. )
  5078. printing_items = list(result.scalars().all())
  5079. if len(printing_items) > 1:
  5080. logger.warning(
  5081. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  5082. printer_id,
  5083. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  5084. )
  5085. item = printing_items[0] if printing_items else None
  5086. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  5087. return
  5088. if item:
  5089. queue_status = data.get("status", "completed")
  5090. # MQTT sends "aborted" for cancelled prints; normalise to
  5091. # "cancelled" so it matches the queue schema Literal.
  5092. if queue_status == "aborted":
  5093. queue_status = "cancelled"
  5094. item.status = queue_status
  5095. item.completed_at = datetime.now(timezone.utc)
  5096. if queue_status == "failed" and not item.error_message:
  5097. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  5098. # Bump usage counters on the source library file so admins can
  5099. # sort by "last printed" and (eventually) auto-purge stale
  5100. # files — #1008.
  5101. await _bump_library_file_usage_if_completed(db, item, queue_status)
  5102. await db.commit()
  5103. queue_item_id = item.id
  5104. billing_run_id = item.billing_run_id
  5105. billing_user_id = item.created_by_id
  5106. billing_cost_center_id = item.cost_center_id
  5107. billing_plate_id = item.plate_id
  5108. queue_auto_off = item.auto_off_after
  5109. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  5110. await run_with_retry(_update_queue_status, label="queue status update")
  5111. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  5112. # their own sessions and have their own error handling — no retry needed.
  5113. if queue_item_id is not None:
  5114. # Batch orders (#342): this run may have been the last one an order
  5115. # owed. Re-evaluate here rather than lazily on read, so a finished
  5116. # order reports itself complete without someone opening the page.
  5117. try:
  5118. from backend.app.services.print_batch import refresh_batch_status_for_item
  5119. async with async_session() as db:
  5120. await refresh_batch_status_for_item(db, queue_item_id)
  5121. await db.commit()
  5122. except Exception as e:
  5123. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  5124. # MQTT relay - publish queue job completed
  5125. try:
  5126. printer_info = printer_manager.get_printer(printer_id)
  5127. await mqtt_relay.on_queue_job_completed(
  5128. job_id=queue_item_id,
  5129. filename=filename or subtask_name,
  5130. printer_id=printer_id,
  5131. printer_name=printer_info.name if printer_info else "Unknown",
  5132. status=queue_status,
  5133. )
  5134. except Exception:
  5135. pass # Don't fail if MQTT fails
  5136. # Check if queue is now empty and send notification
  5137. try:
  5138. from sqlalchemy import func as sa_func
  5139. async with async_session() as db:
  5140. count_result = await db.execute(
  5141. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  5142. )
  5143. pending_count = count_result.scalar() or 0
  5144. if pending_count == 0:
  5145. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  5146. completed_result = await db.execute(
  5147. select(sa_func.count(PrintQueueItem.id)).where(
  5148. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  5149. PrintQueueItem.completed_at >= today_start,
  5150. )
  5151. )
  5152. completed_count = completed_result.scalar() or 1
  5153. await notification_service.on_queue_completed(
  5154. completed_count=completed_count,
  5155. db=db,
  5156. )
  5157. except Exception:
  5158. pass # Don't fail if notification fails
  5159. # Handle auto_off_after - power off printer if the queue item opted
  5160. # in. Delegates to the smart-plug manager so the off honours each
  5161. # plug's configured strategy (time delay or temperature threshold),
  5162. # is cancelled if the printer starts printing again, and never cuts
  5163. # power on a loaded print (#1890). Previously an inline block here
  5164. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  5165. # timeout regardless of print state — cutting a touchscreen reprint.
  5166. if queue_auto_off:
  5167. try:
  5168. async with async_session() as db:
  5169. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  5170. except Exception as e:
  5171. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  5172. except Exception as e:
  5173. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  5174. log_timing("Queue item update")
  5175. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  5176. # Must run before archive_id early-return so it fires for all prints (including
  5177. # prints started from BambuStudio/touchscreen that have no archive).
  5178. if data.get("status") == "completed":
  5179. try:
  5180. from backend.app.api.routes.settings import get_setting
  5181. async with async_session() as db:
  5182. threshold_str = await get_setting(db, "bed_cooled_threshold")
  5183. threshold = float(threshold_str) if threshold_str else 35.0
  5184. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  5185. async with async_session() as db:
  5186. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  5187. if providers:
  5188. _bed_cool_waiters[printer_id] = {
  5189. "threshold": threshold,
  5190. "filename": filename or subtask_name or "",
  5191. "registered_at": time.time(),
  5192. }
  5193. logger.info(
  5194. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  5195. printer_id,
  5196. threshold,
  5197. )
  5198. else:
  5199. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  5200. except Exception as e:
  5201. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  5202. # Capture the slicer estimate before usage tracking runs. The tracker may
  5203. # update archive.cost with this run's measured cost; billing partial runs
  5204. # against that already-partial value would discount the charge twice.
  5205. billing_planned_grams: float | None = None
  5206. billing_base_cost: float | None = None
  5207. if archive_id:
  5208. try:
  5209. async with async_session() as db:
  5210. from backend.app.models.archive import PrintArchive
  5211. billing_archive = await db.get(PrintArchive, archive_id)
  5212. if billing_archive:
  5213. billing_path = (
  5214. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  5215. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5216. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  5217. billing_archive,
  5218. billing_path,
  5219. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  5220. )
  5221. except Exception as e:
  5222. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  5223. # --- Track filament consumption (must run before archive_id early-return so usage
  5224. # is recorded even when auto-archive is disabled) ---
  5225. usage_results: list[dict] = []
  5226. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  5227. stored_ams_mapping = data.get("ams_mapping")
  5228. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  5229. if not stored_ams_mapping and archive_id:
  5230. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  5231. # Always drain the plate_id register on completion — the session already
  5232. # consumed it at print-start injection; leaving it would leak into the next
  5233. # print on the same archive_id (rare but possible with reprints) (#1697).
  5234. # Capture the popped value so the completion notification can scope the
  5235. # archive-level (summed-across-plates per #1593) filament + time totals
  5236. # down to the single plate that was actually printed (#1785).
  5237. notify_plate_id: int | None = None
  5238. if archive_id:
  5239. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  5240. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  5241. try:
  5242. async with async_session() as db:
  5243. from backend.app.api.routes.settings import get_setting
  5244. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5245. if not _spoolman_on or _spoolman_on.lower() != "true":
  5246. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  5247. async with async_session() as db:
  5248. usage_results = await usage_on_print_complete(
  5249. printer_id,
  5250. data,
  5251. printer_manager,
  5252. db,
  5253. archive_id=archive_id,
  5254. ams_mapping=stored_ams_mapping,
  5255. )
  5256. if usage_results:
  5257. await ws_manager.broadcast(
  5258. {
  5259. "type": "spool_usage_logged",
  5260. "printer_id": printer_id,
  5261. "usage": usage_results,
  5262. }
  5263. )
  5264. log_timing("Usage tracker")
  5265. except Exception as e:
  5266. logger.warning("Usage tracker on_print_complete failed: %s", e)
  5267. # Drop the print-start context unconditionally — the Spoolman branch above
  5268. # skips the internal tracker entirely, so nothing else would clear what
  5269. # print start captured, and a row surviving its print would be restored
  5270. # onto the next one after a restart.
  5271. try:
  5272. from backend.app.services.usage_tracker import discard_session
  5273. async with async_session() as db:
  5274. await discard_session(db, printer_id)
  5275. except Exception as e:
  5276. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  5277. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  5278. if archive_id:
  5279. if data.get("status") == "completed":
  5280. try:
  5281. await _report_spoolman_usage(printer_id, archive_id)
  5282. log_timing("Spoolman usage report")
  5283. except Exception as e:
  5284. logger.warning("Spoolman usage reporting failed: %s", e)
  5285. else:
  5286. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  5287. try:
  5288. async with async_session() as db:
  5289. await _cleanup_spoolman_tracking(
  5290. printer_id,
  5291. archive_id,
  5292. db,
  5293. last_layer_num=data.get("last_layer_num"),
  5294. last_progress=data.get("last_progress"),
  5295. )
  5296. except Exception as e:
  5297. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  5298. log_timing("Filament usage tracking")
  5299. if not archive_id:
  5300. # The printer's own calibration run has no archive by design, so this
  5301. # arrives here every time one finishes. Returning before the no-archive
  5302. # notification is not just noise control: that path attributes an
  5303. # unmatched completion to any queue item this printer finished in the
  5304. # last five minutes, which for a calibration that runs alongside a real
  5305. # print means emailing its owner that their print is done, twice and
  5306. # early. Everything above this point has already run — the plate-clear
  5307. # gate, the queue reconciliation, the SD-card cleanup — so only the
  5308. # notification is skipped.
  5309. if is_internal_printer_job(filename, subtask_name):
  5310. logger.info(
  5311. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  5312. filename,
  5313. subtask_name,
  5314. )
  5315. return
  5316. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  5317. # Still send print-complete/failed/stopped notifications even without an archive.
  5318. # Try to enrich with queue/library-file data so user-specific emails work too.
  5319. async def _notify_no_archive():
  5320. try:
  5321. async with async_session() as db:
  5322. from backend.app.models.library import LibraryFile
  5323. from backend.app.models.print_queue import PrintQueueItem
  5324. from backend.app.models.printer import Printer
  5325. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5326. printer_obj = result.scalar_one_or_none()
  5327. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  5328. # Try to find the most-recent queue item for this printer so we can
  5329. # recover created_by_id and estimated print time.
  5330. # NOTE: By the time this task runs the queue item status has already
  5331. # been updated to a terminal state (completed/failed/cancelled), so
  5332. # we look for recently-completed items (within the last 5 minutes).
  5333. no_archive_data: dict | None = None
  5334. try:
  5335. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  5336. q_result = await db.execute(
  5337. select(PrintQueueItem)
  5338. .where(PrintQueueItem.printer_id == printer_id)
  5339. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  5340. .where(PrintQueueItem.completed_at >= cutoff)
  5341. .order_by(PrintQueueItem.completed_at.desc())
  5342. .limit(1)
  5343. )
  5344. queue_item = q_result.scalar_one_or_none()
  5345. if queue_item:
  5346. no_archive_data = {"created_by_id": queue_item.created_by_id}
  5347. # Pull estimated time from library file when available
  5348. if queue_item.library_file_id:
  5349. lib_result = await db.execute(
  5350. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  5351. )
  5352. lib_file = lib_result.scalar_one_or_none()
  5353. if lib_file and lib_file.print_time_seconds:
  5354. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  5355. except Exception as lookup_err:
  5356. logger.debug(
  5357. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  5358. )
  5359. # Enrich with usage tracker results (captured in enclosing scope)
  5360. if usage_results:
  5361. if no_archive_data is None:
  5362. no_archive_data = {}
  5363. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  5364. if total_from_usage > 0:
  5365. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  5366. no_archive_data["usage_results"] = usage_results
  5367. # Try MQTT remaining_time for print duration when no queue/library data
  5368. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  5369. mqtt_remaining = data.get("remaining_time")
  5370. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5371. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  5372. ps = data.get("status", "completed")
  5373. logger.info(
  5374. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  5375. )
  5376. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  5377. await notification_service.on_print_complete(
  5378. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  5379. )
  5380. else:
  5381. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  5382. # Send user-specific email if we have a created_by_id
  5383. if no_archive_data and no_archive_data.get("created_by_id"):
  5384. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  5385. await _dispatch_user_print_email(
  5386. ps,
  5387. no_archive_data["created_by_id"],
  5388. p_name,
  5389. raw_filename,
  5390. db,
  5391. )
  5392. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  5393. except Exception as e:
  5394. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  5395. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  5396. return
  5397. log_timing("Archive lookup")
  5398. # Update archive status
  5399. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  5400. try:
  5401. async with async_session() as db:
  5402. service = ArchiveService(db)
  5403. status = data.get("status", "completed")
  5404. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  5405. if hms_errors:
  5406. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  5407. failure_reason = derive_failure_reason(status, hms_errors)
  5408. if data.get("_reconciled"):
  5409. # A reconciled completion closes out a stale archive at
  5410. # reconnect — it is not a user action, so don't mislabel it
  5411. # "User cancelled". The "Stale" prefix matches the existing
  5412. # stale-cleanup convention and records that the real end time
  5413. # is unknown, which is also why its logged duration is 0 (#2592).
  5414. failure_reason = "Stale - reconciled after reconnect, end time unknown"
  5415. if failure_reason:
  5416. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  5417. elif status == "failed" and hms_errors:
  5418. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  5419. await service.update_archive_status(
  5420. archive_id,
  5421. status=status,
  5422. completed_at=(
  5423. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  5424. ),
  5425. failure_reason=failure_reason,
  5426. )
  5427. logger.info(
  5428. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  5429. )
  5430. await ws_manager.send_archive_updated(
  5431. {
  5432. "id": archive_id,
  5433. "status": status,
  5434. }
  5435. )
  5436. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  5437. # MQTT relay - publish archive updated
  5438. try:
  5439. await mqtt_relay.on_archive_updated(
  5440. archive_id=archive_id,
  5441. print_name=filename or subtask_name,
  5442. status=status,
  5443. )
  5444. except Exception:
  5445. pass # Don't fail if MQTT fails
  5446. except Exception as e:
  5447. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  5448. # Continue with other operations even if archive update fails
  5449. log_timing("Archive status update")
  5450. # Apply finance wallet charge or release reservations once. For all partial
  5451. # terminal states (failed, aborted at the printer display, or cancelled via
  5452. # Bambuddy) use this run's measured spool delta, falling back to the last
  5453. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  5454. # estimate and therefore cannot represent an interrupted run.
  5455. try:
  5456. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  5457. async with async_session() as db:
  5458. from backend.app.models.archive import PrintArchive
  5459. from backend.app.services.finance_billing import apply_print_charge_for_archive
  5460. archive = await db.get(PrintArchive, archive_id)
  5461. if archive and billing_run_id is None:
  5462. billing_run_id = getattr(archive, "billing_run_id", None)
  5463. if archive and archive.created_by_id is None and _print_user_info:
  5464. archive.created_by_id = _print_user_info.get("user_id")
  5465. await db.flush()
  5466. run_status = data.get("status", "completed")
  5467. last_progress = data.get("last_progress")
  5468. if last_progress is None:
  5469. last_progress = data.get("progress")
  5470. actual_run_grams = _compute_run_filament_grams(
  5471. run_status,
  5472. billing_planned_grams,
  5473. last_progress,
  5474. usage_results,
  5475. )
  5476. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  5477. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  5478. charged = await apply_print_charge_for_archive(
  5479. db,
  5480. archive_id,
  5481. charged_user_id=billing_user_id,
  5482. cost_center_id=(
  5483. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  5484. ),
  5485. print_queue_id=queue_item_id,
  5486. print_run_id=billing_run_id,
  5487. base_cost_override=billing_base_cost,
  5488. filament_usage=filament_usage,
  5489. )
  5490. await db.commit()
  5491. if charged:
  5492. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  5493. except Exception as e:
  5494. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  5495. printer_info = printer_manager.get_printer(printer_id)
  5496. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  5497. billing_filename = filename or subtask_name or "Unknown"
  5498. billing_error = str(e)
  5499. try:
  5500. await ws_manager.broadcast(
  5501. {
  5502. "type": "billing_charge_failed",
  5503. "printer_id": printer_id,
  5504. "printer_name": billing_printer_name,
  5505. "filename": billing_filename,
  5506. "archive_id": archive_id,
  5507. }
  5508. )
  5509. except Exception as notification_error:
  5510. logger.error(
  5511. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  5512. archive_id,
  5513. notification_error,
  5514. )
  5515. async def _notify_billing_charge_failed() -> None:
  5516. try:
  5517. async with async_session() as notification_db:
  5518. await notification_service.on_billing_charge_failed(
  5519. printer_id,
  5520. billing_printer_name,
  5521. billing_filename,
  5522. archive_id,
  5523. billing_error,
  5524. notification_db,
  5525. )
  5526. except Exception as provider_error:
  5527. logger.error(
  5528. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  5529. archive_id,
  5530. provider_error,
  5531. exc_info=True,
  5532. )
  5533. spawn_background_task(
  5534. _notify_billing_charge_failed(),
  5535. name=f"billing-charge-failed-{archive_id}",
  5536. )
  5537. log_timing("Finance charge update")
  5538. # Write independent print log entry (separate table, never touches archives)
  5539. try:
  5540. async with async_session() as db:
  5541. from backend.app.models.archive import PrintArchive
  5542. from backend.app.services.print_log import write_log_entry
  5543. archive = await db.get(PrintArchive, archive_id)
  5544. if archive:
  5545. # Back-fill created_by_id on reprint (#730): reprint reuses the
  5546. # source archive row rather than creating a new one, so an
  5547. # archive that was auto-created from a printer-initiated
  5548. # print (created_by_id=NULL) would otherwise stay unattributed
  5549. # forever. When we have a print-session user AND the archive
  5550. # has no attribution yet, credit the current user. Never
  5551. # overwrite an existing attribution — the original uploader
  5552. # keeps ownership.
  5553. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  5554. if archive.created_by_id is None and _print_user_id is not None:
  5555. archive.created_by_id = _print_user_id
  5556. p_info = printer_manager.get_printer(printer_id)
  5557. # Per-run actuals — written to PrintLogEntry so stats reflect
  5558. # what THIS print actually used, not the source archive's
  5559. # first-run values (#1378). Helper handles the partial-print
  5560. # math (failed / cancelled / stopped get scaled to progress
  5561. # or to tracked spool deltas).
  5562. _run_status = data.get("status", "completed")
  5563. # #2614: scope the per-run estimate to the printed plate. For a
  5564. # multi-plate 3MF dispatched one plate at a time, the archive's
  5565. # filament/cost are the whole-file totals; the PrintLogEntry must
  5566. # reflect only this plate. No effect on single-plate archives (the
  5567. # plate estimate equals the whole-file value) or on the tracker
  5568. # path (measured spool deltas win in _compute_run_filament_grams).
  5569. _est_full_path = (
  5570. app_settings.base_dir / archive.file_path if archive.file_path else None
  5571. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5572. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  5573. _run_grams = _compute_run_filament_grams(
  5574. _run_status,
  5575. _est_grams,
  5576. data.get("last_progress", data.get("progress")),
  5577. usage_results,
  5578. )
  5579. # Per-run cost — prefer usage_results sum. For partial prints
  5580. # we deliberately skip the topup-to-estimate logic in
  5581. # usage_tracker (which assumes the print completed); the raw
  5582. # tracked-spool sum is closer to what THIS run actually cost.
  5583. _run_cost: float | None = None
  5584. if usage_results:
  5585. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  5586. if _run_cost is None and _run_status == "completed":
  5587. _run_cost = _est_cost
  5588. await write_log_entry(
  5589. db,
  5590. archive_id=archive.id,
  5591. # Captured by _update_queue_status above; None for
  5592. # printer-initiated prints with no queue row. Batch
  5593. # cost/energy roll-up joins on it (#342).
  5594. queue_item_id=queue_item_id,
  5595. status=_run_status,
  5596. print_name=archive.print_name,
  5597. printer_name=p_info.name if p_info else None,
  5598. printer_id=printer_id,
  5599. started_at=archive.started_at,
  5600. completed_at=archive.completed_at,
  5601. filament_type=archive.filament_type,
  5602. filament_color=archive.filament_color,
  5603. filament_used_grams=_run_grams,
  5604. cost=_run_cost,
  5605. failure_reason=archive.failure_reason,
  5606. thumbnail_path=archive.thumbnail_path,
  5607. created_by_id=archive.created_by_id,
  5608. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  5609. # Reconciled completions have an unknown real end time —
  5610. # log 0 duration instead of the whole disconnect gap (#2592).
  5611. reconciled=bool(data.get("_reconciled")),
  5612. )
  5613. await db.commit()
  5614. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  5615. except Exception as e:
  5616. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  5617. log_timing("Print log entry")
  5618. # Run slow operations as background tasks to avoid blocking the event loop
  5619. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  5620. async def _background_energy_calculation():
  5621. """Calculate and save energy usage in background.
  5622. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  5623. backend restart no longer loses per-print energy data).
  5624. """
  5625. try:
  5626. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  5627. async with async_session() as db:
  5628. from backend.app.models.archive import PrintArchive
  5629. archive = await db.get(PrintArchive, archive_id)
  5630. if archive is None:
  5631. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  5632. return
  5633. starting_kwh = archive.energy_start_kwh
  5634. if starting_kwh is None:
  5635. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  5636. return
  5637. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5638. plug = plug_result.scalar_one_or_none()
  5639. if plug is None:
  5640. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  5641. return
  5642. energy = await _get_plug_energy(plug, db)
  5643. logger.info("[ENERGY-BG] Energy response: %s", energy)
  5644. if not energy or energy.get("total") is None:
  5645. logger.warning("[ENERGY-BG] No 'total' in energy response")
  5646. return
  5647. energy_used = round(energy["total"] - starting_kwh, 4)
  5648. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  5649. if energy_used < 0:
  5650. logger.warning(
  5651. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  5652. archive_id,
  5653. starting_kwh,
  5654. energy["total"],
  5655. )
  5656. return
  5657. from backend.app.api.routes.settings import get_setting
  5658. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  5659. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  5660. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  5661. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  5662. # reprint doesn't visually clobber the source archive's energy data
  5663. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  5664. from sqlalchemy import func
  5665. from backend.app.models.print_log import PrintLogEntry
  5666. existing_runs = await db.scalar(
  5667. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  5668. )
  5669. if (existing_runs or 0) <= 1:
  5670. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  5671. # we just wrote for THIS print. Either way it's the first run.
  5672. archive.energy_kwh = energy_used
  5673. archive.energy_cost = energy_cost_value
  5674. # Backfill the latest PrintLogEntry for this archive with energy
  5675. # (write_log_entry above ran before this background task completed,
  5676. # so energy fields are still NULL on that row).
  5677. latest_run = await db.execute(
  5678. select(PrintLogEntry)
  5679. .where(PrintLogEntry.archive_id == archive_id)
  5680. .order_by(PrintLogEntry.id.desc())
  5681. .limit(1)
  5682. )
  5683. run_row = latest_run.scalar_one_or_none()
  5684. if run_row is not None:
  5685. run_row.energy_kwh = energy_used
  5686. run_row.energy_cost = energy_cost_value
  5687. await db.commit()
  5688. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  5689. except Exception as e:
  5690. logger.warning("[ENERGY-BG] Failed: %s", e)
  5691. async def _background_finish_photo() -> str | None:
  5692. """Capture finish photo in background. Returns photo filename if captured."""
  5693. # #2547: set once this function has raised the plate itself (the
  5694. # timelapse path, where the moment producer returned without doing it).
  5695. # Declared out here so the `finally` can lower it again no matter where
  5696. # the capture below fails.
  5697. plate_restored_z: float | None = None
  5698. try:
  5699. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  5700. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  5701. # Read phase: settings + printer + archive in a short session, released
  5702. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  5703. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  5704. # tens of seconds; holding this session across it pinned one pooled
  5705. # connection idle-in-transaction per finishing print (issue #2572).
  5706. async with async_session() as db:
  5707. from backend.app.api.routes.settings import get_setting
  5708. from backend.app.models.archive import PrintArchive
  5709. from backend.app.models.printer import Printer
  5710. capture_enabled = await get_setting(db, "capture_finish_photo")
  5711. if capture_enabled is not None and capture_enabled.lower() != "true":
  5712. return None
  5713. if not archive_id:
  5714. return None
  5715. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5716. archive = (
  5717. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5718. ).scalar_one_or_none()
  5719. if not printer or not archive:
  5720. return None
  5721. import uuid
  5722. from datetime import datetime
  5723. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  5724. if not archive.file_path:
  5725. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  5726. archive_dir = resolve_archive_dir(archive)
  5727. photo_filename = None
  5728. # Prefer the timelapse last-frame source when a timelapse was
  5729. # recording — it captures the moment after the toolhead parks
  5730. # but before the bed drops, which the live-camera grab below
  5731. # would miss (#1397). Skipped for external cameras (those have
  5732. # their own framing and don't see a Bambu timelapse). Only
  5733. # runs when the USER explicitly enabled timelapse for this
  5734. # print — #1721 removed Bambuddy's force-on at dispatch
  5735. # because it caused per-layer nozzle parking on Smooth-mode
  5736. # slicer profiles.
  5737. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  5738. printer.external_camera_enabled and printer.external_camera_url
  5739. )
  5740. timelapse_still_pending = False
  5741. if prefer_timelapse_source:
  5742. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  5743. archive_id=archive_id,
  5744. archive_dir=archive_dir,
  5745. rotation=getattr(printer, "camera_rotation", 0),
  5746. )
  5747. # #1721: replacement framing path — on_finish_photo_moment
  5748. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  5749. # parked, bed not yet dropped) and cached the JPEG bytes in
  5750. # _stage22_finish_frames. Consume them now so the saved photo
  5751. # has the better framing instead of the post-bed-drop angle
  5752. # the live-camera fallback below would give.
  5753. if not photo_filename:
  5754. # #1790: on the FINISH-state fallback path the producer
  5755. # task is dispatched back-to-back with this consumer, so
  5756. # a bare pop would race past with an empty result and
  5757. # the RTSP fallback below would collide with the
  5758. # producer's still-in-flight grab (single-client RTSP
  5759. # on Bambu printers). Wait for the producer to finish
  5760. # or give up before touching the cache.
  5761. #
  5762. # #2547: 20s was enough when the producer only ever grabbed a
  5763. # frame. It now also raises the plate first, which costs the
  5764. # settle window before the grab even starts — so the budget has
  5765. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  5766. # under the notification's own photo wait below.
  5767. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  5768. if in_flight is not None:
  5769. try:
  5770. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  5771. except asyncio.TimeoutError:
  5772. logger.warning(
  5773. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  5774. printer_id,
  5775. )
  5776. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  5777. if cached_frame:
  5778. # Already rotated by the producer (#2708) — rotating again
  5779. # here would undo the fix on the banked-frame path, whose
  5780. # bytes reach the cache having been rotated once already.
  5781. photos_dir = archive_dir / "photos"
  5782. photos_dir.mkdir(parents=True, exist_ok=True)
  5783. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5784. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5785. photo_path = photos_dir / photo_filename
  5786. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  5787. logger.info(
  5788. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  5789. photo_filename,
  5790. len(cached_frame),
  5791. )
  5792. # #2547: the timelapse path reaches the live grab below whenever the
  5793. # video hasn't landed in time — the documented usual outcome on
  5794. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  5795. # returned early for those prints without raising the plate, so
  5796. # without this the photo that actually ships in the notification is
  5797. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  5798. # asked us to fix. The archive still gets the better video frame
  5799. # later; this is about the image the user is sent.
  5800. #
  5801. # Gated on `timelapse_was_active` precisely because that is the
  5802. # condition under which the producer skipped. On every other path it
  5803. # has already raised and lowered the plate, and repeating that here
  5804. # would be a second pointless round trip.
  5805. if (
  5806. not photo_filename
  5807. and data.get("timelapse_was_active")
  5808. and not print_dispatch_context.end_gcode_injected(printer_id)
  5809. ):
  5810. try:
  5811. async with async_session() as db:
  5812. from backend.app.api.routes.settings import get_setting
  5813. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  5814. if restore_setting is None or restore_setting.lower() == "true":
  5815. max_z = await _max_z_for_current_print(printer_id, data, logger)
  5816. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  5817. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  5818. plate_restored_z = max_z
  5819. except Exception as e:
  5820. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  5821. # Fallback chain: external camera → buffered live frame →
  5822. # fresh RTSP capture. Only runs if the timelapse path above
  5823. # didn't already produce a photo.
  5824. if not photo_filename:
  5825. if printer.external_camera_enabled and printer.external_camera_url:
  5826. logger.info("[PHOTO-BG] Using external camera")
  5827. from backend.app.api.routes.camera import live_frame_for_capture
  5828. from backend.app.services.external_camera import capture_frame
  5829. # #2707: the second half of the finish-photo failure — the
  5830. # pre-capture and this fallback both collided with the live
  5831. # view. None here continues down the fallback chain.
  5832. defer, buffered = live_frame_for_capture(printer_id)
  5833. if defer:
  5834. frame_data = buffered
  5835. else:
  5836. frame_data = await capture_frame(
  5837. printer.external_camera_url,
  5838. printer.external_camera_type or "mjpeg",
  5839. snapshot_url=printer.external_camera_snapshot_url,
  5840. )
  5841. if frame_data:
  5842. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  5843. photos_dir = archive_dir / "photos"
  5844. photos_dir.mkdir(parents=True, exist_ok=True)
  5845. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5846. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5847. photo_path = photos_dir / photo_filename
  5848. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  5849. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  5850. else:
  5851. # Check if camera stream is active - use buffered frame to avoid freeze
  5852. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  5853. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  5854. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  5855. buffered_frame = get_buffered_frame(printer_id)
  5856. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  5857. # Use frame from active stream
  5858. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  5859. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  5860. photos_dir = archive_dir / "photos"
  5861. photos_dir.mkdir(parents=True, exist_ok=True)
  5862. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5863. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5864. photo_path = photos_dir / photo_filename
  5865. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  5866. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  5867. else:
  5868. # No active stream - capture new frame
  5869. from backend.app.services.camera import capture_finish_photo
  5870. photo_filename = await capture_finish_photo(
  5871. printer_id=printer_id,
  5872. ip_address=printer.ip_address,
  5873. access_code=printer.access_code,
  5874. model=printer.model,
  5875. archive_dir=archive_dir,
  5876. rotation=getattr(printer, "camera_rotation", 0),
  5877. )
  5878. # Write phase: attach the photo in a fresh short-lived session.
  5879. if photo_filename:
  5880. async with async_session() as db:
  5881. from backend.app.models.archive import PrintArchive
  5882. arch = await db.get(PrintArchive, archive_id)
  5883. if arch is not None:
  5884. photos = arch.photos or []
  5885. photos.append(photo_filename)
  5886. arch.photos = photos
  5887. await db.commit()
  5888. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  5889. # The short wait above is bounded so a slow printer can't hold up
  5890. # the print-complete notification, which is what the caller is
  5891. # blocking on. When it ran out with the video still on its way,
  5892. # keep waiting off to the side and add the better frame to the
  5893. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  5894. # users, whose videos routinely take minutes to transfer, never get
  5895. # the pre-bed-drop framing this path exists to provide.
  5896. #
  5897. # Spawned here rather than at the point the wait gave up: both this
  5898. # function and the upgrade do a read-modify-write on `photos`, and
  5899. # the live-camera fallback above can take tens of seconds. Starting
  5900. # the upgrade before that write means the two can interleave and one
  5901. # silently drops the other's entry, leaving a JPEG on disk that the
  5902. # gallery never lists.
  5903. if timelapse_still_pending:
  5904. spawn_background_task(
  5905. _upgrade_finish_photo_from_timelapse(
  5906. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  5907. ),
  5908. name=f"finish-photo-upgrade-{archive_id}",
  5909. )
  5910. return photo_filename
  5911. except Exception as e:
  5912. logger.warning("[PHOTO-BG] Failed: %s", e)
  5913. return None
  5914. finally:
  5915. # #2547: we raised the plate, so we owe the move back down — even if
  5916. # the capture in between threw. Otherwise the user finds the print
  5917. # pinned under the nozzle.
  5918. if plate_restored_z is not None:
  5919. try:
  5920. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  5921. except Exception as e:
  5922. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  5923. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  5924. # Photo capture task - result will be used by notifications
  5925. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  5926. log_timing("Background tasks scheduled (energy, photo)")
  5927. # Also run smart plug, notifications, and maintenance as background tasks
  5928. print_status = data.get("status", "completed")
  5929. async def _background_smart_plug():
  5930. """Handle smart plug automation in background."""
  5931. try:
  5932. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  5933. async with async_session() as db:
  5934. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  5935. logger.info("[AUTO-OFF-BG] Completed")
  5936. except Exception as e:
  5937. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  5938. async def _background_notifications(finish_photo_filename: str | None = None):
  5939. """Send print complete notifications in background."""
  5940. try:
  5941. logger.info(
  5942. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  5943. )
  5944. async with async_session() as db:
  5945. from backend.app.models.archive import PrintArchive
  5946. from backend.app.models.printer import Printer
  5947. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5948. printer = result.scalar_one_or_none()
  5949. printer_name = printer.name if printer else f"Printer {printer_id}"
  5950. archive_data = None
  5951. if archive_id:
  5952. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5953. archive = archive_result.scalar_one_or_none()
  5954. if archive:
  5955. # Actual elapsed time from started_at/completed_at when both are
  5956. # populated (every terminal status sets completed_at after #1198).
  5957. # Falls back to None so the notification path can decide whether to
  5958. # render the slicer estimate as a last resort.
  5959. actual_time_seconds = None
  5960. if archive.started_at and archive.completed_at:
  5961. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  5962. if elapsed > 0:
  5963. actual_time_seconds = int(elapsed)
  5964. archive_data = {
  5965. "print_time_seconds": archive.print_time_seconds,
  5966. "actual_time_seconds": actual_time_seconds,
  5967. "actual_filament_grams": archive.filament_used_grams,
  5968. "failure_reason": archive.failure_reason,
  5969. "created_by_id": archive.created_by_id,
  5970. }
  5971. # Scale filament usage for partial prints
  5972. if print_status != "completed" and archive.filament_used_grams:
  5973. progress = data.get("progress") or 0
  5974. scale = _partial_progress_scale(progress)
  5975. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  5976. archive_data["progress"] = progress
  5977. # Pass per-slot data from archive.extra_data
  5978. if archive.extra_data and archive.extra_data.get("filament_slots"):
  5979. slots = archive.extra_data["filament_slots"]
  5980. if print_status != "completed":
  5981. scale = _partial_progress_scale(data.get("progress"))
  5982. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  5983. archive_data["filament_slots"] = slots
  5984. # Scope project-summed totals down to the plate that was
  5985. # actually printed — see _scope_notification_archive_data_to_plate
  5986. # for the why (#1785).
  5987. archive_data = _scope_notification_archive_data_to_plate(
  5988. archive_data,
  5989. archive.file_path,
  5990. notify_plate_id,
  5991. print_status,
  5992. data.get("progress"),
  5993. app_settings.base_dir,
  5994. )
  5995. # Enrich filament_grams from usage_results when archive has no 3MF data
  5996. if not archive_data.get("actual_filament_grams") and usage_results:
  5997. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  5998. if total_from_usage > 0:
  5999. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6000. # Pass usage tracker results for AMS slot info in notifications
  6001. if usage_results:
  6002. archive_data["usage_results"] = usage_results
  6003. # Add finish photo URL and image bytes if available
  6004. if finish_photo_filename:
  6005. from backend.app.api.routes.settings import get_setting
  6006. external_url = await get_setting(db, "external_url")
  6007. if external_url:
  6008. external_url = external_url.rstrip("/")
  6009. archive_data["finish_photo_url"] = (
  6010. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6011. )
  6012. else:
  6013. # Fallback to relative URL (won't work for external services)
  6014. archive_data["finish_photo_url"] = (
  6015. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6016. )
  6017. # Read finish photo bytes for image attachment (e.g. Pushover)
  6018. try:
  6019. from backend.app.utils.archive_paths import find_archive_photo
  6020. photo_path = find_archive_photo(archive, finish_photo_filename)
  6021. if photo_path is not None:
  6022. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  6023. if len(photo_bytes) <= 2_500_000:
  6024. archive_data["image_data"] = photo_bytes
  6025. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  6026. else:
  6027. logger.warning(
  6028. f"[NOTIFY-BG] Finish photo too large for attachment: "
  6029. f"{len(photo_bytes)} bytes"
  6030. )
  6031. except Exception as e:
  6032. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  6033. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6034. await notification_service.on_print_complete(
  6035. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  6036. )
  6037. else:
  6038. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6039. # Send user-specific email notification
  6040. if archive_data:
  6041. created_by_id = archive_data.get("created_by_id")
  6042. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6043. await _dispatch_user_print_email(
  6044. print_status,
  6045. created_by_id,
  6046. printer_name,
  6047. raw_filename,
  6048. db,
  6049. )
  6050. logger.info("[NOTIFY-BG] Completed")
  6051. except Exception as e:
  6052. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  6053. async def _background_maintenance_check():
  6054. """Check for maintenance due in background."""
  6055. if print_status != "completed":
  6056. return
  6057. try:
  6058. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  6059. async with async_session() as db:
  6060. from backend.app.models.printer import Printer
  6061. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6062. printer = result.scalar_one_or_none()
  6063. printer_name = printer.name if printer else f"Printer {printer_id}"
  6064. await ensure_default_types(db)
  6065. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  6066. items_needing_attention = [
  6067. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  6068. for item in overview.maintenance_items
  6069. if item.enabled and (item.is_due or item.is_warning)
  6070. ]
  6071. if items_needing_attention:
  6072. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  6073. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  6074. # MQTT relay - publish maintenance alerts
  6075. for item in items_needing_attention:
  6076. try:
  6077. await mqtt_relay.on_maintenance_alert(
  6078. printer_id=printer_id,
  6079. printer_name=printer_name,
  6080. maintenance_type=item["name"],
  6081. current_value=0, # Not easily available here
  6082. threshold=0, # Not easily available here
  6083. )
  6084. except Exception:
  6085. pass # Don't fail if MQTT fails
  6086. else:
  6087. logger.info("[MAINT-BG] Completed (no items need attention)")
  6088. except Exception as e:
  6089. logger.warning("[MAINT-BG] Failed: %s", e)
  6090. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  6091. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  6092. # Notification task waits for photo capture to complete first (with timeout).
  6093. # When a timelapse was recording, photo sourcing polls the per-print
  6094. # timelapse for up to 60s (#1397) — extend the budget so the notification
  6095. # carries the correct bed-up photo instead of falling through to the
  6096. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  6097. #
  6098. # #2547: both budgets now have to cover a plate restore as well.
  6099. #
  6100. # Without timelapse, the wait is on the moment producer, which raises the
  6101. # plate before its grab — so this has to outlast that producer's own budget.
  6102. #
  6103. # With timelapse, the capture polls up to
  6104. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  6105. # falls back to a live grab, which is the case that raises the plate. At the
  6106. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  6107. # restore would have moved the plate for a photo nobody waited for.
  6108. photo_wait_timeout = (
  6109. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  6110. if data.get("timelapse_was_active")
  6111. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  6112. )
  6113. async def _photo_then_notify():
  6114. """Wait for photo capture, then send notification with photo URL."""
  6115. finish_photo = None
  6116. try:
  6117. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  6118. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  6119. except TimeoutError:
  6120. logger.warning(
  6121. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  6122. photo_wait_timeout,
  6123. )
  6124. except Exception as e:
  6125. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  6126. try:
  6127. await _background_notifications(finish_photo)
  6128. except Exception as e:
  6129. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  6130. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  6131. # Stitch external camera layer timelapse if session was active
  6132. print_status = data.get("status", "completed")
  6133. async def _background_layer_timelapse():
  6134. """Stitch layer timelapse and attach to archive."""
  6135. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  6136. try:
  6137. if print_status == "completed":
  6138. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  6139. timelapse_path = await tl_complete(printer_id)
  6140. if timelapse_path and archive_id:
  6141. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6142. async with async_session() as db:
  6143. service = ArchiveService(db)
  6144. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6145. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  6146. # Clean up the temp file
  6147. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6148. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6149. elif timelapse_path:
  6150. # Timelapse created but no archive - just clean up
  6151. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6152. else:
  6153. # Print failed or cancelled - cancel timelapse session
  6154. cancel_session(printer_id)
  6155. logger.info(
  6156. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  6157. )
  6158. except Exception as e:
  6159. logger.warning("[LAYER-TL] Failed: %s", e)
  6160. # Try to cancel session on error
  6161. try:
  6162. cancel_session(printer_id)
  6163. except Exception:
  6164. pass # Best-effort timelapse session cancellation on error
  6165. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  6166. log_timing("All background tasks scheduled")
  6167. # Auto-scan for timelapse if recording was active during the print
  6168. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  6169. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  6170. # Schedule timelapse scan as background task with retries
  6171. # The printer needs time to encode the video after print completion
  6172. baseline = _timelapse_baselines.pop(printer_id, None)
  6173. spawn_background_task(
  6174. _scan_for_timelapse_with_retries(archive_id, baseline),
  6175. name=f"scan-timelapse-{archive_id}",
  6176. )
  6177. log_timing("Timelapse scan scheduled")
  6178. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  6179. # AMS sensor history recording
  6180. _ams_history_task: asyncio.Task | None = None
  6181. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  6182. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  6183. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  6184. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  6185. _ams_alarm_cooldown: dict[str, datetime] = {}
  6186. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  6187. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  6188. # through a cycle and the cool-down after it (#1802). Stored in the settings
  6189. # table rather than alongside _ams_alarm_cooldown above, because a restart
  6190. # partway through a cool-down would otherwise resume alarming about heat the
  6191. # user asked for — the same internal-timestamp-row pattern as
  6192. # support.py's debug_logging_enabled_at.
  6193. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  6194. # Upper bound on that suppression. The latch normally clears as soon as the unit
  6195. # reads at or below the threshold; see utils.ams_drying for why this cap only
  6196. # matters when it never does.
  6197. AMS_DRYING_GRACE_MINUTES = 120
  6198. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  6199. """Read the persisted per-AMS drying latch, dropping entries out of window.
  6200. Anything older than the grace cap would expire on its next visit anyway, so
  6201. discarding it here costs nothing and stops rows for deleted printers from
  6202. accumulating.
  6203. Stamps ahead of now get two defences, because a box whose clock jumps
  6204. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  6205. ones are discarded outright, and the rest are clamped to now. Without the
  6206. clamp the cap would measure from a moment that has not happened yet and hold
  6207. the alarm quiet for the skew on top of the cap. One unnecessary notification
  6208. after a clock jump is a far better failure than an alarm silently disabled
  6209. for hours.
  6210. """
  6211. from backend.app.models.settings import Settings
  6212. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6213. setting = result.scalar_one_or_none()
  6214. if not setting or not setting.value:
  6215. return {}
  6216. try:
  6217. raw = json.loads(setting.value)
  6218. except (ValueError, TypeError):
  6219. return {} # Corrupted row → no latch, alarms behave as they did before
  6220. if not isinstance(raw, dict):
  6221. return {}
  6222. now = datetime.now(timezone.utc)
  6223. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  6224. latch: dict[str, datetime] = {}
  6225. for key, value in raw.items():
  6226. try:
  6227. stamp = datetime.fromisoformat(str(value))
  6228. except (ValueError, TypeError):
  6229. continue
  6230. if stamp.tzinfo is None:
  6231. stamp = stamp.replace(tzinfo=timezone.utc)
  6232. if not (now - window <= stamp <= now + window):
  6233. continue
  6234. # Nothing may sit in the future: suppression is measured as now minus
  6235. # the stamp, so a stamp ahead of now would extend it by the skew on top
  6236. # of the cap. Clamping the survivors keeps the cap an actual cap.
  6237. latch[str(key)] = min(stamp, now)
  6238. return latch
  6239. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  6240. """Persist the latch, writing only when it actually changed.
  6241. Adds the session change but does not commit — the caller's own commit
  6242. carries it, so the latch lands in the same transaction as the sensor rows
  6243. that produced it.
  6244. """
  6245. from backend.app.models.settings import Settings
  6246. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  6247. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6248. setting = result.scalar_one_or_none()
  6249. if setting is None:
  6250. # Don't create the row on installs that never dry anything.
  6251. if payload != "{}":
  6252. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  6253. elif setting.value != payload:
  6254. setting.value = payload
  6255. def _ams_has_filament(ams_data: dict) -> bool:
  6256. """True if this AMS unit has at least one tray slot holding filament.
  6257. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  6258. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  6259. still report sensor readings, but those readings are ambient and not
  6260. actionable: no filament to dry, no humidity to push down. #1619 — gate
  6261. humidity/temperature alarms on this check so empty units don't generate
  6262. hourly noise. Sensor history still records regardless so the UI charts
  6263. stay continuous.
  6264. Fallback path inspects the `tray` array's `tray_type` fields for setups
  6265. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  6266. """
  6267. bits = ams_data.get("tray_exist_bits")
  6268. if isinstance(bits, str) and bits.strip():
  6269. try:
  6270. return int(bits, 16) > 0
  6271. except ValueError:
  6272. pass
  6273. trays = ams_data.get("tray")
  6274. if isinstance(trays, list):
  6275. return any(
  6276. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  6277. )
  6278. return False
  6279. async def record_ams_history():
  6280. """Background task to record AMS humidity and temperature data."""
  6281. logger = logging.getLogger(__name__)
  6282. # Wait a short time for MQTT connections to establish on startup
  6283. await asyncio.sleep(10)
  6284. while True:
  6285. try:
  6286. from backend.app.models.ams_history import AMSSensorHistory
  6287. from backend.app.models.printer import Printer
  6288. from backend.app.models.settings import Settings
  6289. async with async_session() as db:
  6290. # Get all active printers
  6291. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6292. printers = result.scalars().all()
  6293. # Get alarm thresholds from settings
  6294. humidity_threshold = 60.0 # Default: fair threshold
  6295. temp_threshold = 35.0 # Default: fair threshold
  6296. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  6297. setting = result.scalar_one_or_none()
  6298. if setting:
  6299. try:
  6300. humidity_threshold = float(setting.value)
  6301. except (ValueError, TypeError):
  6302. pass # Keep default threshold if stored value is invalid
  6303. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  6304. setting = result.scalar_one_or_none()
  6305. if setting:
  6306. try:
  6307. temp_threshold = float(setting.value)
  6308. except (ValueError, TypeError):
  6309. pass # Keep default threshold if stored value is invalid
  6310. # Per-filament humidity threshold overrides (#1605) — resolved
  6311. # per-AMS below from the loaded tray types. Reuses the same
  6312. # resolver as the auto-drying scheduler so behavior stays in
  6313. # lockstep across both consumers.
  6314. from backend.app.services.print_scheduler import PrintScheduler
  6315. per_type_humidity_thresholds: dict[str, int] = {}
  6316. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  6317. setting = result.scalar_one_or_none()
  6318. if setting and setting.value:
  6319. try:
  6320. raw = json.loads(setting.value)
  6321. if isinstance(raw, dict):
  6322. for k, v in raw.items():
  6323. try:
  6324. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  6325. v
  6326. )
  6327. except (TypeError, ValueError):
  6328. continue
  6329. except (ValueError, TypeError):
  6330. pass # Invalid JSON → no overrides, fall through to global threshold
  6331. # Per-AMS drying latch (#1802), loaded once per pass and written
  6332. # back below only if a unit changed it.
  6333. drying_latch = await _load_ams_drying_latch(db)
  6334. drying_latch_before = dict(drying_latch)
  6335. recorded_count = 0
  6336. for printer in printers:
  6337. # Get current state from printer manager
  6338. state = printer_manager.get_status(printer.id)
  6339. if not state or not state.connected or not state.raw_data:
  6340. continue # Skip disconnected printers - don't use stale data
  6341. raw_data = state.raw_data
  6342. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  6343. continue
  6344. # Record data for each AMS unit
  6345. for ams_data in raw_data["ams"]:
  6346. ams_id = int(ams_data.get("id", 0))
  6347. # Get humidity (prefer humidity_raw)
  6348. humidity_raw = ams_data.get("humidity_raw")
  6349. humidity_idx = ams_data.get("humidity")
  6350. humidity = None
  6351. if humidity_raw is not None:
  6352. try:
  6353. humidity = float(humidity_raw)
  6354. except (ValueError, TypeError):
  6355. pass # Skip unparseable humidity; will try fallback
  6356. if humidity is None and humidity_idx is not None:
  6357. try:
  6358. humidity = float(humidity_idx)
  6359. except (ValueError, TypeError):
  6360. pass # Skip unparseable humidity index value
  6361. # Get temperature
  6362. temperature = None
  6363. temp_str = ams_data.get("temp")
  6364. if temp_str is not None:
  6365. try:
  6366. temperature = float(temp_str)
  6367. except (ValueError, TypeError):
  6368. pass # Skip unparseable temperature value
  6369. # Skip if no data
  6370. if humidity is None and temperature is None:
  6371. continue
  6372. # Record the data point
  6373. history = AMSSensorHistory(
  6374. printer_id=printer.id,
  6375. ams_id=ams_id,
  6376. humidity=humidity,
  6377. humidity_raw=float(humidity_raw) if humidity_raw else None,
  6378. temperature=temperature,
  6379. )
  6380. db.add(history)
  6381. recorded_count += 1
  6382. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  6383. is_ams_ht = ams_id >= 128
  6384. if is_ams_ht:
  6385. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  6386. else:
  6387. ams_label = f"AMS-{chr(65 + ams_id)}"
  6388. # Skip alarm dispatch for empty AMS units — humidity /
  6389. # temperature readings are ambient with no filament to
  6390. # protect, and the hourly notification just becomes
  6391. # noise. Sensor history was already recorded above so
  6392. # the UI charts stay continuous (#1619). Per-AMS check
  6393. # so a multi-AMS setup with one loaded + one empty
  6394. # still alarms on the loaded unit.
  6395. if not _ams_has_filament(ams_data):
  6396. continue
  6397. # Resolve per-filament humidity threshold for this AMS
  6398. # unit (#1605). Falls back to the global ams_humidity_fair
  6399. # when no per-type overrides are configured.
  6400. trays = ams_data.get("tray", []) or []
  6401. effective_humidity_threshold = float(
  6402. PrintScheduler.resolve_humidity_threshold(
  6403. trays, per_type_humidity_thresholds, int(humidity_threshold)
  6404. )
  6405. )
  6406. # Check humidity alarm (only if above threshold)
  6407. if humidity is not None and humidity > effective_humidity_threshold:
  6408. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  6409. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  6410. now = datetime.now(timezone.utc)
  6411. if (
  6412. last_alarm is None
  6413. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  6414. ):
  6415. _ams_alarm_cooldown[cooldown_key] = now
  6416. logger.info(
  6417. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  6418. )
  6419. try:
  6420. # Call different notification method based on AMS type
  6421. if is_ams_ht:
  6422. await notification_service.on_ams_ht_humidity_high(
  6423. printer.id,
  6424. printer.name,
  6425. ams_label,
  6426. humidity,
  6427. effective_humidity_threshold,
  6428. db,
  6429. )
  6430. else:
  6431. await notification_service.on_ams_humidity_high(
  6432. printer.id,
  6433. printer.name,
  6434. ams_label,
  6435. humidity,
  6436. effective_humidity_threshold,
  6437. db,
  6438. )
  6439. except Exception as e:
  6440. logger.warning("Failed to send humidity alarm: %s", e)
  6441. # A drying cycle heats the unit far past ams_temp_fair on
  6442. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  6443. # AMS-HT, against a 35 C default — so the alarm fired
  6444. # once an hour for the whole cycle and kept firing while
  6445. # the unit cooled back down (#1802). Latch on the
  6446. # firmware's own drying state and hold until the reading
  6447. # returns to normal. Humidity is deliberately left alone:
  6448. # it falls during drying, which is the whole point.
  6449. latch_key = f"{printer.id}:{ams_id}"
  6450. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  6451. drying_active=is_drying_active(ams_data),
  6452. temperature=temperature,
  6453. threshold=temp_threshold,
  6454. latched_at=drying_latch.get(latch_key),
  6455. now=datetime.now(timezone.utc),
  6456. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  6457. )
  6458. if new_latch is None:
  6459. drying_latch.pop(latch_key, None)
  6460. else:
  6461. drying_latch[latch_key] = new_latch
  6462. # Check temperature alarm (only if above threshold)
  6463. if temperature is not None and temperature > temp_threshold and not suppress_temp_alarm:
  6464. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  6465. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  6466. now = datetime.now(timezone.utc)
  6467. if (
  6468. last_alarm is None
  6469. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  6470. ):
  6471. _ams_alarm_cooldown[cooldown_key] = now
  6472. logger.info(
  6473. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  6474. )
  6475. try:
  6476. # Call different notification method based on AMS type
  6477. if is_ams_ht:
  6478. await notification_service.on_ams_ht_temperature_high(
  6479. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  6480. )
  6481. else:
  6482. await notification_service.on_ams_temperature_high(
  6483. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  6484. )
  6485. except Exception as e:
  6486. logger.warning("Failed to send temperature alarm: %s", e)
  6487. if drying_latch != drying_latch_before:
  6488. await _save_ams_drying_latch(db, drying_latch)
  6489. await db.commit()
  6490. if recorded_count > 0:
  6491. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  6492. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  6493. global _ams_cleanup_counter
  6494. _ams_cleanup_counter += 1
  6495. if _ams_cleanup_counter >= 288:
  6496. _ams_cleanup_counter = 0
  6497. # Get retention days from settings
  6498. from backend.app.models.settings import Settings
  6499. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  6500. setting = result.scalar_one_or_none()
  6501. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  6502. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  6503. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  6504. await db.commit()
  6505. if result.rowcount > 0:
  6506. logger.info(
  6507. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  6508. )
  6509. # Wait until next recording interval
  6510. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  6511. except asyncio.CancelledError:
  6512. break
  6513. except Exception as e:
  6514. logger.warning("AMS history recording failed: %s", e)
  6515. await asyncio.sleep(60) # Wait a bit before retrying
  6516. def start_ams_history_recording():
  6517. """Start the AMS history recording background task."""
  6518. global _ams_history_task
  6519. if _ams_history_task is None:
  6520. _ams_history_task = asyncio.create_task(record_ams_history())
  6521. logging.getLogger(__name__).info("AMS history recording started")
  6522. def stop_ams_history_recording():
  6523. """Stop the AMS history recording background task."""
  6524. global _ams_history_task
  6525. if _ams_history_task:
  6526. _ams_history_task.cancel()
  6527. _ams_history_task = None
  6528. logging.getLogger(__name__).info("AMS history recording stopped")
  6529. # Printer sensor history recording (nozzle / bed / chamber)
  6530. _printer_sensor_history_task: asyncio.Task | None = None
  6531. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  6532. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  6533. _printer_sensor_cleanup_counter = 0
  6534. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  6535. # MQTT parser writes, so we don't need to handle per-model field aliases here
  6536. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  6537. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  6538. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  6539. _SENSOR_TARGET_KEYS = {
  6540. "nozzle": "nozzle_target",
  6541. "nozzle_2": "nozzle_2_target",
  6542. "bed": "bed_target",
  6543. "chamber": "chamber_target",
  6544. }
  6545. async def record_printer_sensor_history():
  6546. """Background task to record nozzle / bed / chamber readings.
  6547. Pulls from `state.temperatures` (already normalised across all printer
  6548. models by the MQTT parser) rather than re-parsing raw_data, so we get
  6549. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  6550. """
  6551. logger = logging.getLogger(__name__)
  6552. await asyncio.sleep(10)
  6553. while True:
  6554. try:
  6555. from backend.app.models.printer import Printer
  6556. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  6557. from backend.app.models.settings import Settings
  6558. async with async_session() as db:
  6559. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6560. printers = result.scalars().all()
  6561. recorded_count = 0
  6562. for printer in printers:
  6563. state = printer_manager.get_status(printer.id)
  6564. if not state or not state.connected:
  6565. continue
  6566. temps = getattr(state, "temperatures", None) or {}
  6567. if not isinstance(temps, dict):
  6568. continue
  6569. for kind in _SENSOR_KINDS:
  6570. if kind not in temps:
  6571. continue
  6572. try:
  6573. value = float(temps[kind])
  6574. except (ValueError, TypeError):
  6575. continue
  6576. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  6577. target_val: float | None = None
  6578. if target_raw is not None:
  6579. try:
  6580. target_val = float(target_raw)
  6581. except (ValueError, TypeError):
  6582. target_val = None
  6583. db.add(
  6584. PrinterSensorHistory(
  6585. printer_id=printer.id,
  6586. sensor_kind=kind,
  6587. value=value,
  6588. target=target_val,
  6589. )
  6590. )
  6591. recorded_count += 1
  6592. await db.commit()
  6593. if recorded_count > 0:
  6594. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  6595. # Periodic cleanup — once every ~24h at this interval.
  6596. global _printer_sensor_cleanup_counter
  6597. _printer_sensor_cleanup_counter += 1
  6598. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  6599. if _printer_sensor_cleanup_counter >= cleanup_every:
  6600. _printer_sensor_cleanup_counter = 0
  6601. result = await db.execute(
  6602. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  6603. )
  6604. setting = result.scalar_one_or_none()
  6605. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  6606. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  6607. cleanup = await db.execute(
  6608. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  6609. )
  6610. await db.commit()
  6611. if cleanup.rowcount > 0:
  6612. logger.info(
  6613. "Cleaned up %s old printer sensor history entries (older than %s days)",
  6614. cleanup.rowcount,
  6615. retention_days,
  6616. )
  6617. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  6618. except asyncio.CancelledError:
  6619. break
  6620. except Exception as e:
  6621. logger.warning("Printer sensor history recording failed: %s", e)
  6622. await asyncio.sleep(60)
  6623. def start_printer_sensor_history_recording():
  6624. global _printer_sensor_history_task
  6625. if _printer_sensor_history_task is None:
  6626. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  6627. logging.getLogger(__name__).info("Printer sensor history recording started")
  6628. def stop_printer_sensor_history_recording():
  6629. global _printer_sensor_history_task
  6630. if _printer_sensor_history_task:
  6631. _printer_sensor_history_task.cancel()
  6632. _printer_sensor_history_task = None
  6633. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  6634. # Printer runtime tracking
  6635. _runtime_tracking_task: asyncio.Task | None = None
  6636. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  6637. async def track_printer_runtime():
  6638. """Background task to track printer active runtime (RUNNING state only).
  6639. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  6640. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  6641. which track mechanical wear. Pause time has no motion and no wear, so
  6642. counting it inflates maintenance warnings (#1521).
  6643. """
  6644. logger = logging.getLogger(__name__)
  6645. # Wait for MQTT connections to establish on startup
  6646. await asyncio.sleep(15)
  6647. while True:
  6648. try:
  6649. from backend.app.models.printer import Printer
  6650. # Fetch printer IDs in a short-lived read-only session
  6651. async with async_session() as db:
  6652. result = await db.execute(
  6653. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  6654. Printer.is_active.is_(True)
  6655. )
  6656. )
  6657. printer_rows = result.all()
  6658. now = datetime.now(timezone.utc)
  6659. updated_count = 0
  6660. # Update each printer in its own short session to minimise write-lock
  6661. # hold time and avoid blocking critical commits like queue status
  6662. # updates (#897).
  6663. for pid, pname, runtime_secs, last_update in printer_rows:
  6664. state = printer_manager.get_status(pid)
  6665. if not state:
  6666. logger.debug("[%s] Runtime tracking: no state available", pname)
  6667. continue
  6668. if not state.connected:
  6669. logger.debug("[%s] Runtime tracking: not connected", pname)
  6670. continue
  6671. needs_commit = False
  6672. new_runtime = runtime_secs
  6673. new_last_update = last_update
  6674. if state.state == "RUNNING":
  6675. if last_update:
  6676. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  6677. elapsed = (now - lu).total_seconds()
  6678. if elapsed > 0:
  6679. new_runtime = runtime_secs + int(elapsed)
  6680. updated_count += 1
  6681. needs_commit = True
  6682. logger.debug(
  6683. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  6684. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  6685. )
  6686. else:
  6687. needs_commit = True
  6688. logger.debug("[%s] Runtime tracking: first active detection", pname)
  6689. new_last_update = now
  6690. else:
  6691. if last_update is not None:
  6692. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  6693. new_last_update = None
  6694. needs_commit = True
  6695. if needs_commit:
  6696. try:
  6697. async with async_session() as db:
  6698. result = await db.execute(select(Printer).where(Printer.id == pid))
  6699. printer = result.scalar_one_or_none()
  6700. if printer:
  6701. printer.runtime_seconds = new_runtime
  6702. printer.last_runtime_update = new_last_update
  6703. await db.commit()
  6704. except Exception as e:
  6705. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  6706. if updated_count > 0:
  6707. logger.debug("Updated runtime for %s printer(s)", updated_count)
  6708. except asyncio.CancelledError:
  6709. logger.info("Runtime tracking cancelled")
  6710. break
  6711. except Exception as e:
  6712. logger.warning("Runtime tracking failed: %s", e)
  6713. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  6714. def start_runtime_tracking():
  6715. """Start the printer runtime tracking background task."""
  6716. global _runtime_tracking_task
  6717. if _runtime_tracking_task is None:
  6718. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  6719. logging.getLogger(__name__).info("Printer runtime tracking started")
  6720. def stop_runtime_tracking():
  6721. """Stop the printer runtime tracking background task."""
  6722. global _runtime_tracking_task
  6723. if _runtime_tracking_task:
  6724. _runtime_tracking_task.cancel()
  6725. _runtime_tracking_task = None
  6726. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  6727. # SpoolBuddy device watchdog
  6728. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  6729. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  6730. async def _spoolbuddy_watchdog_loop():
  6731. """Periodic check for SpoolBuddy devices that have gone offline."""
  6732. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  6733. while True:
  6734. try:
  6735. await spoolbuddy_watchdog()
  6736. except asyncio.CancelledError:
  6737. break
  6738. except Exception as e:
  6739. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  6740. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  6741. def start_spoolbuddy_watchdog():
  6742. global _spoolbuddy_watchdog_task
  6743. if _spoolbuddy_watchdog_task is None:
  6744. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  6745. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  6746. def stop_spoolbuddy_watchdog():
  6747. global _spoolbuddy_watchdog_task
  6748. if _spoolbuddy_watchdog_task:
  6749. _spoolbuddy_watchdog_task.cancel()
  6750. _spoolbuddy_watchdog_task = None
  6751. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  6752. # Dead-MQTT-session recovery
  6753. #
  6754. # check_staleness() covers the "connected but silent" half-broken session. It
  6755. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  6756. # is the only thing left watching at that point. When paho stops making
  6757. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  6758. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  6759. # offline with the UI open the whole time, recovered only when something
  6760. # happened to nudge it.
  6761. #
  6762. # This loop is that backstop. It only touches printers that had a working
  6763. # session and lost it, and only when the MQTT port still answers — a printer
  6764. # that is simply switched off is left to paho, since rebuilding a client
  6765. # against an unreachable host achieves nothing and would fill the log every
  6766. # night.
  6767. _connection_watchdog_task: asyncio.Task | None = None
  6768. CONNECTION_WATCHDOG_INTERVAL = 60
  6769. # How long a printer must have been silent before we stop trusting paho.
  6770. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  6771. # so a session that is recovering on its own is never interrupted.
  6772. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  6773. # Per-printer floor between rebuild attempts.
  6774. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  6775. _connection_watchdog_last_attempt: dict[int, float] = {}
  6776. async def _recover_dead_printer_sessions() -> int:
  6777. """Rebuild MQTT clients that have been offline too long to still be trying.
  6778. Returns the number of printers a rebuild was attempted for (for tests and
  6779. for the caller's logging). Never raises: one unreachable printer must not
  6780. stop the sweep for the rest of the farm.
  6781. """
  6782. logger = logging.getLogger(__name__)
  6783. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  6784. now = time.monotonic()
  6785. recovered = 0
  6786. for printer_id, client in list(printer_manager._clients.items()):
  6787. try:
  6788. if client.state.connected:
  6789. _connection_watchdog_last_attempt.pop(printer_id, None)
  6790. continue
  6791. # Time since the last inbound message is the age of the last known
  6792. # good session — no extra bookkeeping needed, and it is the same
  6793. # clock is_stale() reads. 0 means this client has never had one:
  6794. # that is the initial-connect path, where paho retrying is the
  6795. # correct and only behaviour, so leave it be.
  6796. last_msg = client._last_message_time
  6797. if not last_msg:
  6798. continue
  6799. offline_for = time.time() - last_msg
  6800. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  6801. continue
  6802. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  6803. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  6804. continue
  6805. if not await check_port(client.ip_address, PORT_MQTT):
  6806. # Switched off, unplugged, or off the network. Paho's retry is
  6807. # the right handler; say so at debug level and move on.
  6808. logger.debug(
  6809. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  6810. "— leaving the reconnect to paho",
  6811. printer_id,
  6812. offline_for,
  6813. )
  6814. _connection_watchdog_last_attempt[printer_id] = now
  6815. continue
  6816. _connection_watchdog_last_attempt[printer_id] = now
  6817. recovered += 1
  6818. logger.warning(
  6819. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  6820. "rebuilding the client with a fresh session (last connect error: %s)",
  6821. printer_id,
  6822. offline_for,
  6823. PORT_MQTT,
  6824. client.last_connect_error or "none recorded",
  6825. )
  6826. # Async context, so this takes the hard-reset path: fresh client_id,
  6827. # paho's QoS 1 queue dropped. That matters — a project_file left
  6828. # unacked on the dead session would otherwise replay into the new
  6829. # one and trip 0500_4003 on the printer (#1136).
  6830. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  6831. except Exception as e:
  6832. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  6833. return recovered
  6834. async def _connection_watchdog_loop():
  6835. logger = logging.getLogger(__name__)
  6836. # Let the initial connects settle before judging anyone offline.
  6837. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  6838. while True:
  6839. try:
  6840. await _recover_dead_printer_sessions()
  6841. except asyncio.CancelledError:
  6842. break
  6843. except Exception as e:
  6844. logger.warning("Connection watchdog sweep failed: %s", e)
  6845. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  6846. def start_connection_watchdog():
  6847. global _connection_watchdog_task
  6848. if _connection_watchdog_task is None:
  6849. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  6850. logging.getLogger(__name__).info("Printer connection watchdog started")
  6851. def stop_connection_watchdog():
  6852. global _connection_watchdog_task
  6853. if _connection_watchdog_task:
  6854. _connection_watchdog_task.cancel()
  6855. _connection_watchdog_task = None
  6856. _connection_watchdog_last_attempt.clear()
  6857. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  6858. # Camera stream orphan cleanup
  6859. _camera_cleanup_task: asyncio.Task | None = None
  6860. CAMERA_CLEANUP_INTERVAL = 60
  6861. async def _camera_cleanup_loop():
  6862. """Periodically clean up orphaned ffmpeg processes."""
  6863. from backend.app.api.routes.camera import cleanup_orphaned_streams
  6864. while True:
  6865. try:
  6866. await cleanup_orphaned_streams()
  6867. except asyncio.CancelledError:
  6868. break
  6869. except Exception as e:
  6870. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  6871. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  6872. def start_camera_cleanup():
  6873. global _camera_cleanup_task
  6874. if _camera_cleanup_task is None:
  6875. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  6876. logging.getLogger(__name__).info("Camera stream cleanup started")
  6877. def stop_camera_cleanup():
  6878. global _camera_cleanup_task
  6879. if _camera_cleanup_task:
  6880. _camera_cleanup_task.cancel()
  6881. _camera_cleanup_task = None
  6882. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  6883. # ---------------------------------------------------------------------------
  6884. # Expected-print TTL eviction
  6885. # ---------------------------------------------------------------------------
  6886. def _evict_stale_expected_prints() -> None:
  6887. """Remove entries from _expected_prints / _expected_print_creators that are
  6888. older than _EXPECTED_PRINT_TTL_SECONDS.
  6889. This prevents unbounded growth when a print is registered (via
  6890. register_expected_print) but on_print_start never fires — e.g. because the
  6891. printer disconnects, the app restarts, or the print is started directly from
  6892. the printer panel without going through the queue.
  6893. """
  6894. # Use monotonic time so the TTL is unaffected by system clock adjustments
  6895. # (e.g. NTP sync, DST changes).
  6896. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  6897. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  6898. if not stale_keys:
  6899. return
  6900. evicted_archive_ids: set[int] = set()
  6901. for key in stale_keys:
  6902. archive_id = _expected_prints.pop(key, None)
  6903. if archive_id is not None:
  6904. evicted_archive_ids.add(archive_id)
  6905. _expected_print_creators.pop(key, None)
  6906. _expected_print_registered_at.pop(key, None)
  6907. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  6908. # that have no remaining live keys in _expected_prints (all variants
  6909. # were just evicted).
  6910. live_archive_ids = set(_expected_prints.values())
  6911. for archive_id in evicted_archive_ids:
  6912. if archive_id not in live_archive_ids:
  6913. _print_ams_mappings.pop(archive_id, None)
  6914. _print_cost_center_ids.pop(archive_id, None)
  6915. _print_plate_ids.pop(archive_id, None)
  6916. logging.getLogger(__name__).info(
  6917. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  6918. )
  6919. async def _expected_prints_cleanup_loop() -> None:
  6920. """Background task: periodically evict stale expected-print entries."""
  6921. while True:
  6922. try:
  6923. _evict_stale_expected_prints()
  6924. except asyncio.CancelledError:
  6925. raise
  6926. except Exception as e:
  6927. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  6928. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  6929. def start_expected_prints_cleanup() -> None:
  6930. global _expected_prints_cleanup_task
  6931. if _expected_prints_cleanup_task is None:
  6932. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  6933. logging.getLogger(__name__).info("Expected prints cleanup started")
  6934. def stop_expected_prints_cleanup() -> None:
  6935. global _expected_prints_cleanup_task
  6936. if _expected_prints_cleanup_task:
  6937. _expected_prints_cleanup_task.cancel()
  6938. _expected_prints_cleanup_task = None
  6939. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  6940. # ---------------------------------------------------------------------------
  6941. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  6942. # ---------------------------------------------------------------------------
  6943. _auth_cleanup_task: asyncio.Task | None = None
  6944. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  6945. async def _run_auth_cleanup() -> None:
  6946. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  6947. from backend.app.core.database import async_session
  6948. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  6949. from backend.app.models.user_totp import UserTOTP
  6950. now = datetime.now(timezone.utc)
  6951. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  6952. try:
  6953. async with async_session() as db:
  6954. stale_cutoff = now - timedelta(hours=1)
  6955. result = await db.execute(
  6956. select(UserTOTP).where(
  6957. UserTOTP.is_enabled.is_(False),
  6958. UserTOTP.created_at < stale_cutoff,
  6959. )
  6960. )
  6961. stale_records = result.scalars().all()
  6962. if stale_records:
  6963. for rec in stale_records:
  6964. await db.delete(rec)
  6965. await db.commit()
  6966. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  6967. except Exception as e:
  6968. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  6969. # Remove expired revoked-JTI entries (they are no longer needed once the
  6970. # original token's exp has passed — the token would be rejected by JWT
  6971. # signature verification regardless).
  6972. try:
  6973. async with async_session() as db:
  6974. await db.execute(
  6975. delete(AuthEphemeralToken).where(
  6976. AuthEphemeralToken.token_type == "revoked_jti",
  6977. AuthEphemeralToken.expires_at < now,
  6978. )
  6979. )
  6980. await db.commit()
  6981. except Exception as e:
  6982. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  6983. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  6984. # Events outside this window can never affect rate-limit decisions — they only
  6985. # consume DB space. Use the same window constant as the rate limiter so the
  6986. # two are always in sync.
  6987. try:
  6988. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  6989. async with async_session() as db:
  6990. await db.execute(
  6991. delete(AuthRateLimitEvent).where(
  6992. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  6993. )
  6994. )
  6995. await db.commit()
  6996. except Exception as e:
  6997. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  6998. async def _auth_cleanup_loop() -> None:
  6999. """Periodic background task: run auth cleanup every hour."""
  7000. while True:
  7001. try:
  7002. await _run_auth_cleanup()
  7003. except asyncio.CancelledError:
  7004. break
  7005. except Exception as e:
  7006. logging.warning("Auth cleanup loop error: %s", e)
  7007. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  7008. def start_auth_cleanup() -> None:
  7009. global _auth_cleanup_task
  7010. if _auth_cleanup_task is None:
  7011. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  7012. logging.getLogger(__name__).info("Auth periodic cleanup started")
  7013. def stop_auth_cleanup() -> None:
  7014. global _auth_cleanup_task
  7015. if _auth_cleanup_task:
  7016. _auth_cleanup_task.cancel()
  7017. _auth_cleanup_task = None
  7018. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  7019. @asynccontextmanager
  7020. async def lifespan(app: FastAPI):
  7021. # Startup
  7022. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  7023. # anything else can spawn tasks that might trip it.
  7024. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  7025. install_proactor_reset_filter()
  7026. await init_db()
  7027. # After migrations, so the is_env_managed column exists. Never raises --
  7028. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  7029. # startup (see apply_env_oidc_provider).
  7030. from backend.app.core.oidc_env import apply_env_oidc_provider
  7031. async with async_session() as oidc_db:
  7032. await apply_env_oidc_provider(oidc_db)
  7033. # Close out batches that finished before `completed` was a reachable status
  7034. # (#342). Without this the Batches tab opens on every batch created since
  7035. # the feature shipped, all still marked active. Never blocks startup.
  7036. try:
  7037. from backend.app.services.print_batch import backfill_batch_statuses
  7038. async with async_session() as batch_db:
  7039. await backfill_batch_statuses(batch_db)
  7040. except Exception as exc:
  7041. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  7042. # Register an app-scoped httpx client for Bambu Cloud services so
  7043. # per-request BambuCloudService instances reuse the same connection pool
  7044. # (important for routes like /cloud/filament-info that chain many
  7045. # get_setting_detail calls). The shared client stores no region/token
  7046. # state, so the per-request ownership pattern that fixed the region-bleed
  7047. # bug is preserved.
  7048. import httpx as _httpx
  7049. from backend.app.services.bambu_cloud import set_shared_http_client
  7050. from backend.app.services.makerworld import (
  7051. set_shared_http_client as set_shared_makerworld_http_client,
  7052. )
  7053. from backend.app.services.orca_cloud import (
  7054. set_shared_http_client as set_shared_orca_http_client,
  7055. )
  7056. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  7057. set_shared_http_client(_shared_cloud_http_client)
  7058. # Reuse the same connection pool for MakerWorld — different host, same
  7059. # keep-alive pool saves a TLS handshake per request.
  7060. set_shared_makerworld_http_client(_shared_cloud_http_client)
  7061. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  7062. # each spun up (and never closed) its own client, leaking sockets.
  7063. set_shared_orca_http_client(_shared_cloud_http_client)
  7064. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  7065. # This can happen when a print was cancelled mid-print on versions before this fix.
  7066. try:
  7067. async with async_session() as db:
  7068. from backend.app.models.print_queue import PrintQueueItem
  7069. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  7070. aborted_items = result.scalars().all()
  7071. if aborted_items:
  7072. for item in aborted_items:
  7073. item.status = "cancelled"
  7074. await db.commit()
  7075. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  7076. except Exception as e:
  7077. logging.warning("Failed to fix aborted queue items: %s", e)
  7078. # Restore debug logging state from previous session
  7079. await init_debug_logging()
  7080. # Set up printer manager callbacks
  7081. loop = asyncio.get_event_loop()
  7082. printer_manager.set_event_loop(loop)
  7083. printer_manager.set_status_change_callback(on_printer_status_change)
  7084. printer_manager.set_print_start_callback(on_print_start)
  7085. printer_manager.set_print_complete_callback(on_print_complete)
  7086. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  7087. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  7088. printer_manager.set_ams_change_callback(on_ams_change)
  7089. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  7090. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  7091. await printer_manager.load_awaiting_plate_clear_from_db()
  7092. # Layer change callback for external camera timelapse
  7093. async def on_layer_change(printer_id: int, layer_num: int):
  7094. """Capture timelapse frame on layer change + first layer notification."""
  7095. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  7096. await tl_layer_change(printer_id, layer_num)
  7097. # #1867: bank a recent in-print frame so the finish-photo path has a
  7098. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  7099. # #2547 added `on_print_progress` as a second driver — this one alone
  7100. # stops firing once the final layer begins.
  7101. await _maybe_bank_inprint_frame(printer_id, layer_num)
  7102. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  7103. # Gate on actual printing state — Bambu firmware ticks layer_num during
  7104. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  7105. # nozzle clean), so a bare layer_num check can fire minutes before the
  7106. # first real extrusion. We require gcode_state == RUNNING and
  7107. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  7108. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  7109. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  7110. # edge fires later; _first_layer_notified stays clear until we actually send
  7111. # so a deferred re-evaluation can win. See issue #1837.
  7112. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  7113. client = printer_manager.get_client(printer_id)
  7114. state = client.state if client else None
  7115. if not state or state.state != "RUNNING":
  7116. return
  7117. if state.mc_print_sub_stage not in (None, 0):
  7118. return
  7119. _first_layer_notified[printer_id] = True
  7120. try:
  7121. async with async_session() as db:
  7122. from backend.app.models.printer import Printer
  7123. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7124. printer = result.scalar_one_or_none()
  7125. if not printer:
  7126. return
  7127. printer_name = printer.name
  7128. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  7129. total_layers = state.total_layers if state else 0
  7130. image_data = await _capture_snapshot_for_notification(
  7131. printer_id, printer, logging.getLogger(__name__)
  7132. )
  7133. await notification_service.on_first_layer_complete(
  7134. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  7135. )
  7136. except Exception as e:
  7137. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  7138. printer_manager.set_layer_change_callback(on_layer_change)
  7139. async def on_print_progress(printer_id: int, percent: int):
  7140. """#2547: keep the in-print frame bank fresh through the final layer.
  7141. `on_layer_change` stops the moment the last layer starts, which on the
  7142. H2C capture that closed #2547 left the bank stale for the three minutes
  7143. that layer took. Progress is the only field that keeps advancing there,
  7144. and it freezes before the End G-code runs — so banking on it stays
  7145. inside the print and never sees a swapped plate.
  7146. """
  7147. client = printer_manager.get_client(printer_id)
  7148. state = client.state if client else None
  7149. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  7150. printer_manager.set_print_progress_callback(on_print_progress)
  7151. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  7152. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  7153. waiter = _bed_cool_waiters.get(printer_id)
  7154. if not waiter:
  7155. return
  7156. threshold = waiter["threshold"]
  7157. if bed_temp > threshold:
  7158. return
  7159. # Bed is at or below threshold — fire notification and remove waiter
  7160. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  7161. if not waiter_info:
  7162. return # Another callback already handled it
  7163. bed_cool_logger = logging.getLogger(__name__)
  7164. bed_cool_logger.info(
  7165. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  7166. bed_temp,
  7167. printer_id,
  7168. threshold,
  7169. )
  7170. try:
  7171. printer_info = printer_manager.get_printer(printer_id)
  7172. p_name = printer_info.name if printer_info else "Unknown"
  7173. async with async_session() as db:
  7174. await notification_service.on_bed_cooled(
  7175. printer_id=printer_id,
  7176. printer_name=p_name,
  7177. bed_temp=bed_temp,
  7178. threshold=threshold,
  7179. filename=waiter_info["filename"],
  7180. db=db,
  7181. )
  7182. except Exception as e:
  7183. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  7184. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  7185. async def on_drying_complete(printer_id: int, ams_id: int):
  7186. """Smart-plug auto-off-after-drying trigger (#1349).
  7187. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  7188. manager walks all plugs linked to this printer and turns off only
  7189. the ones with ``auto_off_after_drying`` enabled, after their
  7190. per-plug delay. Multiple AMS units finishing close together (e.g. a
  7191. dual-AMS dry that ends within the same MQTT push) call this once
  7192. per unit — the manager's ``_cancel_pending_off`` collapses
  7193. repeated scheduling on the same plug to one timer, so duplicate
  7194. fires are safe.
  7195. """
  7196. try:
  7197. async with async_session() as db:
  7198. await smart_plug_manager.on_drying_complete(printer_id, db)
  7199. except Exception as e:
  7200. logging.getLogger(__name__).warning(
  7201. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  7202. printer_id,
  7203. ams_id,
  7204. e,
  7205. )
  7206. printer_manager.set_drying_complete_callback(on_drying_complete)
  7207. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  7208. """Surface the read-back result of a spool assignment to the UI (#2582).
  7209. The MQTT client confirms (or fails to confirm) that the tray telemetry
  7210. echoed back the filament id we pushed. We relay that as a websocket
  7211. event so the frontend can toast "loaded" / "assignment didn't take"
  7212. instead of the historic silent fire-and-forget, which made the
  7213. AMS→Studio hand-off feel random to users.
  7214. """
  7215. try:
  7216. from backend.app.services.spool_assignment_notifications import (
  7217. _slot_label_from_global_tray,
  7218. )
  7219. if ams_id == 255:
  7220. global_id = 254 + tray_id
  7221. elif ams_id >= 128:
  7222. global_id = ams_id
  7223. else:
  7224. global_id = ams_id * 4 + tray_id
  7225. slot_label = _slot_label_from_global_tray(global_id)
  7226. printer_info = printer_manager.get_printer(printer_id)
  7227. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7228. await ws_manager.broadcast(
  7229. {
  7230. "type": "spool_assignment_verified",
  7231. "printer_id": printer_id,
  7232. "printer_name": printer_name,
  7233. "ams_id": ams_id,
  7234. "tray_id": tray_id,
  7235. "slot": slot_label,
  7236. "verified": verified,
  7237. # Present on success: False means the filament setting landed
  7238. # but the K-profile (cali_idx) did not — the reporter's exact
  7239. # "loaded but no flow profile" symptom.
  7240. "kprofile_applied": detail.get("kprofile_applied", True),
  7241. # Present on failure: whether any tray telemetry was seen in
  7242. # the window (distinguishes "printer silent" from "printer
  7243. # stored something else").
  7244. "saw_tray": detail.get("saw_tray", False),
  7245. }
  7246. )
  7247. except Exception as e:
  7248. logging.getLogger(__name__).warning(
  7249. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  7250. printer_id,
  7251. ams_id,
  7252. tray_id,
  7253. e,
  7254. )
  7255. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  7256. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  7257. """Persist a mid-print tray change for completion-time attribution.
  7258. AMS filament backup switches trays without telling the slicer, so the
  7259. tray-change log is the only record of which spool fed which layers.
  7260. Keeping it only in memory meant a restart mid-print charged everything
  7261. to the tray that finished the job.
  7262. """
  7263. try:
  7264. from backend.app.services.usage_tracker import record_tray_change
  7265. async with async_session() as db:
  7266. await record_tray_change(db, printer_id, tray_global, layer_num)
  7267. except Exception as e:
  7268. logging.getLogger(__name__).warning(
  7269. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  7270. printer_id,
  7271. tray_global,
  7272. layer_num,
  7273. e,
  7274. )
  7275. printer_manager.set_tray_change_callback(on_tray_change)
  7276. # Initialize MQTT relay from settings
  7277. async with async_session() as db:
  7278. from backend.app.api.routes.settings import get_setting
  7279. mqtt_settings = {
  7280. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  7281. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  7282. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  7283. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  7284. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  7285. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  7286. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  7287. }
  7288. await mqtt_relay.configure(mqtt_settings)
  7289. # Restore MQTT smart plug subscriptions
  7290. if mqtt_settings.get("mqtt_enabled"):
  7291. from backend.app.models.smart_plug import SmartPlug
  7292. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  7293. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  7294. mqtt_plugs = result.scalars().all()
  7295. restored = 0
  7296. for plug in mqtt_plugs:
  7297. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  7298. restored += 1
  7299. if restored:
  7300. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  7301. # Connect to all active printers
  7302. async with async_session() as db:
  7303. await init_printer_connections(db)
  7304. # Auto-connect to Spoolman if enabled
  7305. async with async_session() as db:
  7306. from backend.app.api.routes.settings import get_setting
  7307. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  7308. spoolman_url = await get_setting(db, "spoolman_url")
  7309. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  7310. try:
  7311. client = await init_spoolman_client(spoolman_url)
  7312. if await client.health_check():
  7313. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  7314. # Ensure the 'tag' extra field exists for RFID/UUID storage
  7315. field_ok = await client.ensure_tag_extra_field()
  7316. if not field_ok:
  7317. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  7318. # Register the BambuStudio slicer-preset fields used by the
  7319. # spool-edit / assign flow. Spoolman rejects PATCHes with
  7320. # unknown extra keys, so these must exist before any update
  7321. # that touches them.
  7322. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  7323. if not await client.ensure_extra_field(field_name):
  7324. logging.warning(
  7325. "Spoolman extra field %r registration failed — "
  7326. "spool slicer-preset edits will return 502",
  7327. field_name,
  7328. )
  7329. else:
  7330. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  7331. except Exception as e:
  7332. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  7333. # Start the print scheduler
  7334. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  7335. # Start the smart plug scheduler for time-based on/off
  7336. smart_plug_manager.start_scheduler()
  7337. # Start the Home Assistant sensor poller (#1148)
  7338. ha_sensor_manager.start()
  7339. # Resume any pending auto-offs that were interrupted by restart
  7340. await smart_plug_manager.resume_pending_auto_offs()
  7341. # Start the notification digest scheduler
  7342. notification_service.start_digest_scheduler()
  7343. # Start the GitHub backup scheduler
  7344. await github_backup_service.start_scheduler()
  7345. # Start the local backup scheduler
  7346. await local_backup_service.start_scheduler()
  7347. await obico_detection_service.start()
  7348. # Start the library trash sweeper (#1008)
  7349. await library_trash_service.start_scheduler()
  7350. # Start the archive auto-purge sweeper (#1008 follow-up)
  7351. await archive_purge_service.start_scheduler()
  7352. # Start AMS history recording
  7353. start_ams_history_recording()
  7354. # Start printer sensor (nozzle / bed / chamber) history recording
  7355. start_printer_sensor_history_recording()
  7356. # Start printer runtime tracking
  7357. start_runtime_tracking()
  7358. # Start SpoolBuddy device watchdog
  7359. start_spoolbuddy_watchdog()
  7360. # Start camera stream orphan cleanup
  7361. start_camera_cleanup()
  7362. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  7363. start_connection_watchdog()
  7364. # One-shot sweep for timelapse session directories orphaned by a crash
  7365. # or restart that happened mid-print (in-memory session tracking can't
  7366. # survive that, and nothing else reaps the leftover frames/output file)
  7367. try:
  7368. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  7369. removed = cleanup_orphaned_timelapse_sessions()
  7370. if removed:
  7371. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  7372. except Exception as e:
  7373. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  7374. # Start expected-print TTL eviction (prevents memory leak when prints are
  7375. # registered but on_print_start never fires)
  7376. start_expected_prints_cleanup()
  7377. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  7378. start_auth_cleanup()
  7379. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  7380. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  7381. from backend.app.services.loop_watchdog import start_loop_watchdog
  7382. start_loop_watchdog()
  7383. # Initialize virtual printer manager and sync from DB
  7384. from backend.app.services.virtual_printer import virtual_printer_manager
  7385. virtual_printer_manager.set_session_factory(async_session)
  7386. virtual_printer_manager.set_printer_manager(printer_manager)
  7387. try:
  7388. await virtual_printer_manager.sync_from_db()
  7389. logging.info("Virtual printer manager synced from database")
  7390. except Exception as e:
  7391. logging.warning("Failed to sync virtual printers: %s", e)
  7392. yield
  7393. # Shutdown
  7394. print_scheduler.stop()
  7395. smart_plug_manager.stop_scheduler()
  7396. ha_sensor_manager.stop()
  7397. notification_service.stop_digest_scheduler()
  7398. github_backup_service.stop_scheduler()
  7399. local_backup_service.stop_scheduler()
  7400. library_trash_service.stop_scheduler()
  7401. archive_purge_service.stop_scheduler()
  7402. obico_detection_service.stop()
  7403. stop_ams_history_recording()
  7404. stop_printer_sensor_history_recording()
  7405. stop_runtime_tracking()
  7406. stop_spoolbuddy_watchdog()
  7407. stop_camera_cleanup()
  7408. stop_connection_watchdog()
  7409. from backend.app.services.loop_watchdog import stop_loop_watchdog
  7410. stop_loop_watchdog()
  7411. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  7412. # cleanly rather than waiting on a queue that nothing will ever fill.
  7413. try:
  7414. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  7415. await shutdown_all_broadcasters()
  7416. except Exception as e:
  7417. logging.warning("Failed to shut down camera broadcasters: %s", e)
  7418. stop_expected_prints_cleanup()
  7419. stop_auth_cleanup()
  7420. printer_manager.disconnect_all()
  7421. await close_spoolman_client()
  7422. # Stop all virtual printer services
  7423. await virtual_printer_manager.stop_all()
  7424. await mqtt_smart_plug_service.disconnect(timeout=2)
  7425. await mqtt_relay.disconnect(timeout=2)
  7426. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  7427. set_shared_http_client(None)
  7428. set_shared_makerworld_http_client(None)
  7429. set_shared_orca_http_client(None)
  7430. await _shared_cloud_http_client.aclose()
  7431. # Checkpoint WAL (SQLite only) and close all database connections
  7432. from backend.app.core.db_dialect import is_sqlite
  7433. if is_sqlite():
  7434. try:
  7435. async with engine.begin() as conn:
  7436. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  7437. logging.info("WAL checkpoint completed")
  7438. except Exception as e:
  7439. logging.warning("WAL checkpoint failed: %s", e)
  7440. await engine.dispose()
  7441. app = FastAPI(
  7442. title=app_settings.app_name,
  7443. description="Archive and manage Bambu Lab 3MF files",
  7444. version=APP_VERSION,
  7445. lifespan=lifespan,
  7446. )
  7447. # =============================================================================
  7448. # Authentication Middleware - Secures ALL API routes by default
  7449. # =============================================================================
  7450. # Public routes that don't require authentication even when auth is enabled
  7451. PUBLIC_API_ROUTES = {
  7452. # Auth routes needed before/during login
  7453. "/api/v1/auth/status",
  7454. "/api/v1/auth/login",
  7455. "/api/v1/auth/setup", # Needed for initial setup and recovery
  7456. # Advanced auth status needed for login page
  7457. "/api/v1/auth/advanced-auth/status",
  7458. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  7459. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  7460. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  7461. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  7462. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  7463. # OIDC routes that must be reachable without a JWT
  7464. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  7465. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  7466. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  7467. # Version check for updates (no sensitive data)
  7468. "/api/v1/updates/version",
  7469. # Metrics endpoint handles its own prometheus_token authentication
  7470. "/api/v1/metrics",
  7471. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  7472. # this BEFORE a JWT is available to pick up the firstboot wizard's
  7473. # hostname / timezone / locale and the chrony NTP-gate state. The
  7474. # response contains user-set defaults and a public sync flag — no
  7475. # secrets. Without this entry the global auth middleware returns 401
  7476. # before the route handler runs, regardless of the route's own
  7477. # "no auth required" intent.
  7478. "/api/v1/system/appliance",
  7479. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  7480. # authenticates with a long-lived ``camwall``-scoped token in the query
  7481. # string — exactly like the camera streams two lists below, and for the same
  7482. # reason (no header to put a JWT in). "Public" here only means the middleware
  7483. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  7484. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  7485. # plain ``camera_stream`` token does NOT open this door.
  7486. "/api/v1/camwall/printers",
  7487. }
  7488. # Route prefixes that are public (for routes with dynamic segments)
  7489. PUBLIC_API_PREFIXES = [
  7490. # WebSocket connections handle their own auth
  7491. "/api/v1/ws",
  7492. # OIDC authorize redirects — include provider_id in path
  7493. "/api/v1/auth/oidc/authorize/",
  7494. ]
  7495. # Route patterns that are public (read-only display data)
  7496. # These are checked with "in path" - needed because browsers load images/videos
  7497. # via <img src> and <video src> which don't include Authorization headers
  7498. PUBLIC_API_PATTERNS = [
  7499. # Thumbnails
  7500. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  7501. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  7502. # Images and media
  7503. "/photos/", # /archives/{id}/photos/{filename}
  7504. "/project-image/", # /archives/{id}/project-image/{path}
  7505. "/qrcode", # /archives/{id}/qrcode
  7506. "/timelapse", # /archives/{id}/timelapse (video)
  7507. "/cover", # /printers/{id}/cover
  7508. "/icon", # /external-links/{id}/icon
  7509. # Camera (streams loaded via <img> tag)
  7510. "/camera/stream", # /printers/{id}/camera/stream
  7511. "/camera/snapshot", # /printers/{id}/camera/snapshot
  7512. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  7513. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  7514. # string (same reasoning as the camera streams above — no header to carry a
  7515. # JWT). "Public" only means the middleware steps aside; the route still runs
  7516. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  7517. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  7518. "/overlay-status", # /printers/{id}/overlay-status
  7519. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  7520. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  7521. # download token in the URL path instead.
  7522. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  7523. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  7524. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  7525. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  7526. ]
  7527. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  7528. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  7529. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  7530. Format: comma-separated list of ``scheme://host[:port]`` origins.
  7531. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  7532. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  7533. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  7534. Invalid entries are dropped with a warning rather than failing startup, so
  7535. a typo in one origin doesn't take the whole deployment down.
  7536. """
  7537. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  7538. if not raw:
  7539. return ()
  7540. valid: list[str] = []
  7541. for item in raw.split(","):
  7542. candidate = item.strip()
  7543. if not candidate:
  7544. continue
  7545. try:
  7546. parsed = urlparse(candidate)
  7547. except ValueError as e:
  7548. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  7549. continue
  7550. if parsed.scheme not in ("http", "https"):
  7551. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  7552. continue
  7553. if not parsed.netloc:
  7554. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  7555. continue
  7556. if parsed.path and parsed.path != "/":
  7557. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  7558. continue
  7559. if parsed.query or parsed.fragment:
  7560. _security_headers_logger.warning(
  7561. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  7562. )
  7563. continue
  7564. if "*" in parsed.netloc:
  7565. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  7566. continue
  7567. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  7568. if valid:
  7569. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  7570. return tuple(valid)
  7571. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  7572. def _frame_ancestors(default_value: str) -> str:
  7573. """Compose the ``frame-ancestors`` CSP directive (#1191).
  7574. ``default_value`` is the strict directive used when the operator has not
  7575. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  7576. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  7577. Settings URL builder's preview). When trusted origins
  7578. are configured, ``'self'`` is always included so same-origin embedding never
  7579. breaks even if an operator forgets to add their own origin to the list.
  7580. """
  7581. if _TRUSTED_FRAME_ORIGINS:
  7582. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  7583. return f"frame-ancestors {default_value};"
  7584. @app.middleware("http")
  7585. async def security_headers_middleware(request, call_next):
  7586. """Add standard HTTP security headers to every response."""
  7587. # Per-request nonce stamped into `script-src` (#1460). On its own this
  7588. # changes nothing for Bambuddy's own pages — index.html has no inline
  7589. # scripts since the SW registration moved to /sw-register.js. The reason
  7590. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  7591. # script injected into the HTML on the edge, with a fresh hash on every
  7592. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  7593. # it clones the same nonce onto its injected <script>, and the inline
  7594. # script passes the policy without us needing 'unsafe-inline'. See
  7595. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  7596. csp_nonce = secrets.token_urlsafe(16)
  7597. response = await call_next(request)
  7598. response.headers["X-Content-Type-Options"] = "nosniff"
  7599. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  7600. # browsers honour CSP frame-ancestors instead, and the legacy
  7601. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  7602. # When operators have explicitly allowlisted trusted frame origins (#1191
  7603. # — typically Home Assistant on a different port), drop X-Frame-Options
  7604. # and let the CSP-side frame-ancestors directive govern embedding.
  7605. if not _TRUSTED_FRAME_ORIGINS:
  7606. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  7607. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  7608. # Content-Security-Policy for the React SPA.
  7609. # Notes:
  7610. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  7611. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  7612. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  7613. # - media-src blob:: timelapse video player uses Blob URLs.
  7614. # - font-src data:: some icon fonts are embedded as data URIs.
  7615. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  7616. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  7617. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  7618. # default CSP would render a blank page.
  7619. response.headers["Content-Security-Policy"] = (
  7620. "default-src 'self'; "
  7621. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  7622. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  7623. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  7624. "connect-src 'self'; "
  7625. "font-src 'self' data: https://fonts.gstatic.com; "
  7626. "worker-src 'self' blob:; "
  7627. "object-src 'none'; "
  7628. "base-uri 'self'; " + _frame_ancestors("'none'")
  7629. )
  7630. else:
  7631. # The streaming overlay is embedded same-origin by the URL builder's
  7632. # preview in Settings (#1422), so this branch allows 'self'.
  7633. # Embedding from anywhere else is still refused: 'self'
  7634. # only permits a framer on this origin, which is Bambuddy's own UI, so
  7635. # a clickjacking page on another host is blocked exactly as before.
  7636. # (The overlay draws status over a camera feed and its only interactive
  7637. # element is the logo link, so there is nothing to bait a click into
  7638. # even from a same-origin framer.) Cross-origin embedding of the
  7639. # overlay — Home Assistant on another port — remains what
  7640. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  7641. # allowlist in.
  7642. embeddable_same_origin = request.url.path.startswith("/overlay/")
  7643. response.headers["Content-Security-Policy"] = (
  7644. "default-src 'self'; "
  7645. f"script-src 'self' 'nonce-{csp_nonce}'; "
  7646. "style-src 'self' 'unsafe-inline'; "
  7647. "img-src 'self' data: blob:; "
  7648. "media-src 'self' blob:; "
  7649. "connect-src 'self' ws: wss:; "
  7650. "font-src 'self' data:; "
  7651. "object-src 'none'; "
  7652. "base-uri 'self'; "
  7653. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  7654. )
  7655. if request.url.scheme == "https":
  7656. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  7657. return response
  7658. @app.middleware("http")
  7659. async def auth_middleware(request, call_next):
  7660. """Enforce authentication on all API routes when auth is enabled.
  7661. This middleware provides defense-in-depth by checking auth at the API gateway level,
  7662. regardless of whether individual routes have auth dependencies.
  7663. """
  7664. from starlette.responses import JSONResponse
  7665. path = request.url.path
  7666. # Only apply to API routes
  7667. if not path.startswith("/api/"):
  7668. return await call_next(request)
  7669. # Allow public routes
  7670. if path in PUBLIC_API_ROUTES:
  7671. return await call_next(request)
  7672. # Allow public prefixes
  7673. for prefix in PUBLIC_API_PREFIXES:
  7674. if path.startswith(prefix):
  7675. return await call_next(request)
  7676. # Allow public patterns (read-only display data like thumbnails)
  7677. for pattern in PUBLIC_API_PATTERNS:
  7678. if pattern in path:
  7679. return await call_next(request)
  7680. # Check if auth is enabled. Fail CLOSED on any exception during the
  7681. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  7682. # an attacker who could force a DB exception (e.g. file-descriptor
  7683. # exhaustion via login flood) bypass auth on every protected endpoint.
  7684. try:
  7685. async with async_session() as db:
  7686. from backend.app.core.auth import is_auth_enabled
  7687. auth_enabled = await is_auth_enabled(db)
  7688. if not auth_enabled:
  7689. # Auth disabled, allow all requests
  7690. return await call_next(request)
  7691. except Exception:
  7692. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  7693. return JSONResponse(
  7694. status_code=503,
  7695. content={"detail": "Authentication service temporarily unavailable"},
  7696. )
  7697. # Auth is enabled - require valid token
  7698. auth_header = request.headers.get("Authorization")
  7699. x_api_key = request.headers.get("X-API-Key")
  7700. # Check for API key auth first
  7701. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  7702. # API key authentication - let the request through to be validated by route handler
  7703. # API keys are validated per-route since they have different permission levels
  7704. return await call_next(request)
  7705. # Check for JWT auth
  7706. if not auth_header or not auth_header.startswith("Bearer "):
  7707. return JSONResponse(
  7708. status_code=401,
  7709. content={"detail": "Authentication required"},
  7710. headers={"WWW-Authenticate": "Bearer"},
  7711. )
  7712. # Validate JWT token
  7713. import jwt
  7714. try:
  7715. from backend.app.core.auth import (
  7716. ALGORITHM,
  7717. SECRET_KEY,
  7718. _is_token_fresh,
  7719. get_user_by_username,
  7720. is_jti_revoked,
  7721. )
  7722. token = auth_header.replace("Bearer ", "")
  7723. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  7724. username = payload.get("sub")
  7725. if not username:
  7726. raise ValueError("No username in token")
  7727. jti = payload.get("jti")
  7728. if not jti:
  7729. raise ValueError("No jti in token")
  7730. iat = payload.get("iat")
  7731. # Verify user exists, is active, and token is still fresh (L-R8-A).
  7732. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  7733. # this session so the gateway adds a single pooled checkout, not two (#2572).
  7734. async with async_session() as db:
  7735. if await is_jti_revoked(jti, db):
  7736. return JSONResponse(
  7737. status_code=401,
  7738. content={"detail": "Token has been revoked"},
  7739. headers={"WWW-Authenticate": "Bearer"},
  7740. )
  7741. user = await get_user_by_username(db, username)
  7742. if not user or not user.is_active:
  7743. return JSONResponse(
  7744. status_code=401,
  7745. content={"detail": "User not found or inactive"},
  7746. headers={"WWW-Authenticate": "Bearer"},
  7747. )
  7748. if not _is_token_fresh(iat, user):
  7749. return JSONResponse(
  7750. status_code=401,
  7751. content={"detail": "Token no longer valid"},
  7752. headers={"WWW-Authenticate": "Bearer"},
  7753. )
  7754. except jwt.ExpiredSignatureError:
  7755. return JSONResponse(
  7756. status_code=401,
  7757. content={"detail": "Token has expired"},
  7758. headers={"WWW-Authenticate": "Bearer"},
  7759. )
  7760. except (jwt.InvalidTokenError, ValueError, Exception):
  7761. return JSONResponse(
  7762. status_code=401,
  7763. content={"detail": "Invalid token"},
  7764. headers={"WWW-Authenticate": "Bearer"},
  7765. )
  7766. return await call_next(request)
  7767. @app.middleware("http")
  7768. async def trace_id_middleware(request, call_next):
  7769. """Stamp every HTTP request with a trace ID and echo it back.
  7770. Decorated AFTER auth_middleware on purpose: Starlette stacks
  7771. @app.middleware decorators LIFO, so the last-decorated runs first
  7772. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  7773. which means auth-middleware log lines (and every line emitted on the
  7774. way down to and back from the route handler) all carry the same
  7775. trace ID. If we put it before auth, auth's logs would be stamped
  7776. with the *previous* request's ID — useless for correlation.
  7777. Honours an inbound ``X-Trace-Id`` header so callers running their
  7778. own tracing can correlate their span IDs with our log lines, but
  7779. only if the value passes the whitelist gate in
  7780. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  7781. rejected (too long, contains control chars, etc.) silently triggers
  7782. a freshly minted server-side ID rather than failing the request.
  7783. The minted (or echoed) ID is set on a ContextVar so that every log
  7784. record emitted during the request — application logs *and* uvicorn's
  7785. access log — carries it via TraceIDFilter, and is also written to
  7786. the ``X-Trace-Id`` response header so clients can pin a server-side
  7787. log search to the exact request they made.
  7788. """
  7789. from backend.app.core.trace import (
  7790. generate_trace_id,
  7791. normalise_inbound_trace_id,
  7792. trace_id_var,
  7793. )
  7794. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  7795. trace_id = inbound if inbound is not None else generate_trace_id()
  7796. token = trace_id_var.set(trace_id)
  7797. try:
  7798. response = await call_next(request)
  7799. finally:
  7800. # Reset the ContextVar so a record emitted in a totally
  7801. # unrelated background task that just happens to inherit this
  7802. # context doesn't keep referencing this request's ID forever.
  7803. # In practice ContextVar.reset is best-effort under asyncio
  7804. # task-spawn semantics, but the cost is one attribute write so
  7805. # we may as well do it.
  7806. trace_id_var.reset(token)
  7807. response.headers["X-Trace-Id"] = trace_id
  7808. return response
  7809. # API routes
  7810. app.include_router(auth.router, prefix=app_settings.api_prefix)
  7811. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  7812. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  7813. app.include_router(users.router, prefix=app_settings.api_prefix)
  7814. app.include_router(groups.router, prefix=app_settings.api_prefix)
  7815. app.include_router(printers.router, prefix=app_settings.api_prefix)
  7816. app.include_router(archives.router, prefix=app_settings.api_prefix)
  7817. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  7818. app.include_router(finance.router, prefix=app_settings.api_prefix)
  7819. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  7820. app.include_router(labels.router, prefix=app_settings.api_prefix)
  7821. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  7822. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  7823. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  7824. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  7825. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  7826. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  7827. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  7828. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  7829. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  7830. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  7831. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  7832. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  7833. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  7834. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  7835. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  7836. app.include_router(updates.router, prefix=app_settings.api_prefix)
  7837. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  7838. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  7839. app.include_router(camera.router, prefix=app_settings.api_prefix)
  7840. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  7841. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  7842. app.include_router(projects.router, prefix=app_settings.api_prefix)
  7843. app.include_router(library.router, prefix=app_settings.api_prefix)
  7844. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  7845. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  7846. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  7847. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  7848. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  7849. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  7850. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  7851. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  7852. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  7853. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  7854. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  7855. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  7856. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  7857. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  7858. app.include_router(system.router, prefix=app_settings.api_prefix)
  7859. app.include_router(support.router, prefix=app_settings.api_prefix)
  7860. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  7861. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  7862. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  7863. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  7864. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  7865. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  7866. app.include_router(obico.router, prefix=app_settings.api_prefix)
  7867. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  7868. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  7869. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  7870. # Serve static files (React build)
  7871. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  7872. app.mount(
  7873. "/assets",
  7874. StaticFiles(directory=app_settings.static_dir / "assets"),
  7875. name="assets",
  7876. )
  7877. if (app_settings.static_dir / "img").exists():
  7878. app.mount(
  7879. "/img",
  7880. StaticFiles(directory=app_settings.static_dir / "img"),
  7881. name="img",
  7882. )
  7883. if (app_settings.static_dir / "icons").exists():
  7884. app.mount(
  7885. "/icons",
  7886. StaticFiles(directory=app_settings.static_dir / "icons"),
  7887. name="icons",
  7888. )
  7889. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  7890. # falls through to the SPA catch-all and returns index.html, which the
  7891. # browser's font sanitizer rejects ("downloadable font: rejected by
  7892. # sanitizer").
  7893. if (app_settings.static_dir / "fonts").exists():
  7894. app.mount(
  7895. "/fonts",
  7896. StaticFiles(directory=app_settings.static_dir / "fonts"),
  7897. name="fonts",
  7898. )
  7899. @app.get("/")
  7900. async def serve_frontend():
  7901. """Serve the React frontend."""
  7902. index_file = app_settings.static_dir / "index.html"
  7903. if index_file.exists():
  7904. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  7905. return {
  7906. "message": "Bambuddy API",
  7907. "docs": "/docs",
  7908. "frontend": "Build and place React app in /static directory",
  7909. }
  7910. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  7911. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  7912. # forever, but the HTML wrapping it is the only file that knows which hash
  7913. # is current. Without explicit cache-control headers Chromium decides
  7914. # heuristically (typically 10% of the time since Last-Modified) and on
  7915. # long-running kiosks happily serves stale HTML across browser restarts.
  7916. # That stale HTML references an old bundle hash, the old bundle is also
  7917. # in the disk cache, and the user ends up running pre-update JS forever
  7918. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  7919. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  7920. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  7921. @app.get("/health")
  7922. async def health_check():
  7923. """Health check endpoint."""
  7924. return {"status": "healthy"}
  7925. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  7926. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  7927. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  7928. # in deployment debugging.
  7929. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  7930. async def serve_manifest():
  7931. """Serve PWA manifest."""
  7932. manifest_file = app_settings.static_dir / "manifest.json"
  7933. if manifest_file.exists():
  7934. return FileResponse(manifest_file, media_type="application/manifest+json")
  7935. return {"error": "Manifest not found"}
  7936. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  7937. async def serve_service_worker():
  7938. """Serve service worker."""
  7939. sw_file = app_settings.static_dir / "sw.js"
  7940. if sw_file.exists():
  7941. return FileResponse(
  7942. sw_file,
  7943. media_type="application/javascript",
  7944. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  7945. )
  7946. return {"error": "Service worker not found"}
  7947. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  7948. async def serve_sw_register():
  7949. """Serve the service-worker registration bootstrap script.
  7950. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  7951. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  7952. """
  7953. reg_file = app_settings.static_dir / "sw-register.js"
  7954. if reg_file.exists():
  7955. return FileResponse(reg_file, media_type="application/javascript")
  7956. return {"error": "sw-register.js not found"}
  7957. # ── GCode viewer static files ────────────────────────────────────────────────
  7958. # Catch-all route for React Router (must be last)
  7959. @app.get("/{full_path:path}")
  7960. async def serve_spa(full_path: str):
  7961. """Serve React app for client-side routing."""
  7962. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  7963. if full_path.startswith("api/"):
  7964. from fastapi import HTTPException
  7965. raise HTTPException(status_code=404, detail="Not found")
  7966. index_file = app_settings.static_dir / "index.html"
  7967. if index_file.exists():
  7968. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  7969. return {"error": "Frontend not built"}