main.py 402 KB

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