main.py 408 KB

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