main.py 498 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, or_, select, text
  19. from backend.app.api.routes import (
  20. ams_history,
  21. api_keys,
  22. archive_purge,
  23. archives,
  24. auth,
  25. bug_report,
  26. camera,
  27. camwall,
  28. cloud,
  29. connected_apps,
  30. discovery,
  31. external_links,
  32. filaments,
  33. finance,
  34. firmware,
  35. github_backup,
  36. groups,
  37. ha_sensors,
  38. inventory,
  39. kprofiles,
  40. labels,
  41. library,
  42. library_tags,
  43. library_trash,
  44. library_variants,
  45. local_backup,
  46. local_presets,
  47. location_ha_sensors,
  48. maintenance,
  49. makerworld,
  50. metrics,
  51. mfa,
  52. notification_templates,
  53. notifications,
  54. obico,
  55. orca_cloud,
  56. pending_uploads,
  57. pipeline_runs,
  58. print_log,
  59. print_queue,
  60. printer_sensor_history,
  61. printers,
  62. projects,
  63. scheduled_dryings,
  64. settings as settings_routes,
  65. slice_jobs,
  66. slicer_pipelines,
  67. slicer_presets,
  68. smart_plugs,
  69. sponsor_prompt,
  70. spoolbuddy,
  71. spoolman,
  72. spoolman_inventory,
  73. support,
  74. system,
  75. updates,
  76. user_notifications,
  77. users,
  78. virtual_printers,
  79. webhook,
  80. websocket,
  81. )
  82. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  83. from backend.app.api.routes.support import init_debug_logging
  84. from backend.app.core.config import APP_VERSION, settings as app_settings
  85. from backend.app.core.database import async_session, engine, init_db
  86. from backend.app.core.tasks import spawn_background_task
  87. from backend.app.core.websocket import ws_manager
  88. from backend.app.services import print_dispatch_context
  89. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  90. from backend.app.services.archive_purge import archive_purge_service
  91. from backend.app.services.bambu_ftp import (
  92. FileNotOnPrinterError,
  93. cache_3mf_download,
  94. clear_3mf_cache,
  95. download_file_async,
  96. download_file_try_paths_async,
  97. ftps_handshake_blocked,
  98. get_cached_3mf,
  99. get_ftp_retry_settings,
  100. normalize_3mf_name,
  101. with_ftp_retry,
  102. )
  103. from backend.app.services.bambu_mqtt import PrinterState
  104. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  105. from backend.app.services.github_backup import github_backup_service
  106. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  107. from backend.app.services.homeassistant import homeassistant_service
  108. from backend.app.services.library_trash import library_trash_service
  109. from backend.app.services.local_backup import local_backup_service
  110. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  111. from backend.app.services.mqtt_relay import mqtt_relay
  112. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  113. from backend.app.services.notification_service import notification_service
  114. from backend.app.services.obico_detection import obico_detection_service
  115. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  116. from backend.app.services.print_scheduler import scheduler as print_scheduler
  117. from backend.app.services.print_storage import (
  118. REASON_FTP_TRANSFER_FAILED,
  119. REASON_FTPS_COOLOFF,
  120. external_storage_present,
  121. ftp_probe_paths,
  122. print_file_reachable_over_ftp,
  123. )
  124. from backend.app.services.printer_manager import (
  125. init_printer_connections,
  126. parse_plate_id,
  127. printer_manager,
  128. printer_state_to_dict,
  129. resolve_plate_id,
  130. )
  131. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  132. from backend.app.services.slot_nozzle import (
  133. nozzle_diameter_for_extruder,
  134. nozzle_flow_for_extruder,
  135. resolve_slot_nozzle,
  136. )
  137. from backend.app.services.smart_plug_manager import smart_plug_manager
  138. from backend.app.services.spool_assignment_notifications import (
  139. notify_missing_spool_assignments_on_print_start,
  140. )
  141. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  142. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  143. from backend.app.services.spoolman_tracking import (
  144. cleanup_tracking as _cleanup_spoolman_tracking,
  145. report_usage as _report_spoolman_usage,
  146. store_print_data as _store_spoolman_print_data,
  147. )
  148. from backend.app.services.tasmota import tasmota_service
  149. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  150. from backend.app.utils.ams_humidity import ams_humidity_percent
  151. from backend.app.utils.filament_types import printer_filament_type
  152. from backend.app.utils.fts_routing import extruder_for_inlet
  153. from backend.app.utils.local_time import utcnow_naive
  154. from backend.app.utils.print_jobs import is_internal_printer_job
  155. # =============================================================================
  156. # Dependency Check - runs before other imports to give helpful error messages
  157. # =============================================================================
  158. def _start_error_server(missing_packages: list):
  159. """Start a minimal HTTP server to display dependency errors in browser."""
  160. import os
  161. import signal
  162. from http.server import BaseHTTPRequestHandler, HTTPServer
  163. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  164. html = f"""<!DOCTYPE html>
  165. <html>
  166. <head>
  167. <title>Bambuddy - Setup Required</title>
  168. <style>
  169. body {{
  170. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  171. background: #0f172a; color: #e2e8f0;
  172. display: flex; justify-content: center; align-items: center;
  173. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  174. }}
  175. .container {{
  176. background: #1e293b; border-radius: 12px; padding: 40px;
  177. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  178. }}
  179. h1 {{ color: #f87171; margin-bottom: 10px; }}
  180. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  181. .packages {{
  182. background: #0f172a; border-radius: 8px; padding: 20px;
  183. margin: 20px 0; text-align: left;
  184. }}
  185. .packages ul {{ margin: 0; padding-left: 20px; }}
  186. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  187. .command {{
  188. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  189. margin: 15px 0; font-family: monospace; color: #4ade80;
  190. text-align: left; overflow-x: auto;
  191. }}
  192. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  193. </style>
  194. </head>
  195. <body>
  196. <div class="container">
  197. <h1>Setup Required</h1>
  198. <h2>Missing Python packages</h2>
  199. <div class="packages"><ul>{packages_html}</ul></div>
  200. <p>To fix, run this command on your server:</p>
  201. <div class="command">pip install -r requirements.txt</div>
  202. <p>Or if using a virtual environment:</p>
  203. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  204. <p class="note">After installing, restart Bambuddy:<br>
  205. <code>sudo systemctl restart bambuddy</code></p>
  206. </div>
  207. </body>
  208. </html>"""
  209. class ErrorHandler(BaseHTTPRequestHandler):
  210. def do_GET(self):
  211. self.send_response(503)
  212. self.send_header("Content-type", "text/html")
  213. self.end_headers()
  214. self.wfile.write(html.encode())
  215. def log_message(self, format, *args):
  216. print(f"[Error Server] {args[0]}")
  217. port = int(os.environ.get("PORT", 8000))
  218. print(f"\nStarting error server on http://0.0.0.0:{port}")
  219. print("Visit this URL in your browser to see the error details.\n")
  220. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  221. def shutdown(signum, frame):
  222. print("\nShutting down error server...")
  223. raise SystemExit(0)
  224. signal.signal(signal.SIGTERM, shutdown)
  225. signal.signal(signal.SIGINT, shutdown)
  226. server.serve_forever()
  227. def check_dependencies():
  228. """Check that all required packages are installed."""
  229. missing = []
  230. # Map of import name -> package name (for pip install)
  231. required = {
  232. "jwt": "PyJWT",
  233. "fastapi": "fastapi",
  234. "uvicorn": "uvicorn",
  235. "sqlalchemy": "sqlalchemy",
  236. "aiosqlite": "aiosqlite",
  237. "pydantic": "pydantic",
  238. "paho.mqtt": "paho-mqtt",
  239. }
  240. for module, package in required.items():
  241. try:
  242. __import__(module)
  243. except ImportError:
  244. missing.append(package)
  245. if missing:
  246. print("\n" + "=" * 60)
  247. print("ERROR: Missing required Python packages!")
  248. print("=" * 60)
  249. print(f"\nMissing packages: {', '.join(missing)}")
  250. print("\nTo fix, run:")
  251. print(" pip install -r requirements.txt")
  252. print("\nOr if using a virtual environment:")
  253. print(" ./venv/bin/pip install -r requirements.txt")
  254. print("=" * 60 + "\n")
  255. _start_error_server(missing)
  256. check_dependencies()
  257. # =============================================================================
  258. # Import settings first for logging configuration
  259. # Configure logging based on settings
  260. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  261. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  262. log_level = getattr(logging, log_level_str, logging.INFO)
  263. # Trace ID column ([-] when no request scope is active — startup, MQTT
  264. # callbacks, scheduled tasks not chained from a request — so the column
  265. # stays visually aligned and missing values are obvious in grep). See
  266. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  267. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  268. # Create root logger
  269. root_logger = logging.getLogger()
  270. root_logger.setLevel(log_level)
  271. # Trace-ID injection: this filter populates record.trace_id from the
  272. # per-request ContextVar so the format string above can reference it.
  273. # Attached to each HANDLER (not the root logger) because Python's
  274. # logging semantics only invoke a logger's filters on records that
  275. # *originated* at that logger — records propagated up from child
  276. # loggers (every named logger in the app) never trigger root's filter.
  277. # Putting it on the handlers means every record any handler emits gets
  278. # trace_id injected just before the formatter runs, regardless of which
  279. # logger created the record. Without this, the formatter raises
  280. # KeyError on every child-logger record and the record is silently
  281. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  282. # partially" bug we hit. See backend/app/core/trace.py for the
  283. # ContextVar the filter reads.
  284. from backend.app.core.trace import TraceIDFilter
  285. _trace_id_filter = TraceIDFilter()
  286. # Console handler - always enabled
  287. console_handler = logging.StreamHandler()
  288. console_handler.setLevel(log_level)
  289. console_handler.setFormatter(logging.Formatter(log_format))
  290. console_handler.addFilter(_trace_id_filter)
  291. root_logger.addHandler(console_handler)
  292. # File handler - only in production or if explicitly enabled
  293. if app_settings.log_to_file:
  294. log_file = app_settings.log_dir / "bambuddy.log"
  295. file_handler = RotatingFileHandler(
  296. log_file,
  297. maxBytes=app_settings.log_max_bytes,
  298. backupCount=app_settings.log_backup_count,
  299. encoding="utf-8",
  300. )
  301. file_handler.setLevel(log_level)
  302. file_handler.setFormatter(logging.Formatter(log_format))
  303. file_handler.addFilter(_trace_id_filter)
  304. root_logger.addHandler(file_handler)
  305. logging.info("Logging to file: %s", log_file)
  306. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  307. # access logger with propagate=False by default, so without this attach
  308. # there is no on-disk record of which endpoint triggered a server-state
  309. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  310. # for exactly this reason. Filtered to write methods only
  311. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  312. # frontend don't churn the rotation window faster than it's useful.
  313. from backend.app.core.logging_filters import (
  314. CancelledPoolNoiseFilter,
  315. WriteRequestsOnlyFilter,
  316. )
  317. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  318. uvicorn_access_logger.addHandler(file_handler)
  319. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  320. # Uvicorn's access logger has propagate=False (its own default), so the
  321. # root-attached TraceIDFilter never sees these records. Attach a
  322. # second instance directly so HTTP access lines carry the same trace
  323. # ID column as the application logs they correlate with.
  324. uvicorn_access_logger.addFilter(TraceIDFilter())
  325. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  326. # BaseHTTPMiddleware cancelling the inner task scope on client
  327. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  328. # underlying transaction leak; this filter only suppresses the residual
  329. # log records that pre-existing pools still emit during their cleanup.
  330. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  331. # Reduce noise from third-party libraries in production
  332. if not app_settings.debug:
  333. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  334. logging.getLogger("httpcore").setLevel(logging.WARNING)
  335. logging.getLogger("httpx").setLevel(logging.WARNING)
  336. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  337. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  338. # Track active prints: {(printer_id, filename): archive_id}
  339. _active_prints: dict[tuple[int, str], int] = {}
  340. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  341. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  342. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  343. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  344. # instead of running its own grab-now chain when present, so the finish photo
  345. # captures the better-framed pre-bed-drop moment without us having to force
  346. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  347. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  348. #
  349. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  350. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  351. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  352. # bank and the others are not — so the consumer can't tell them apart and
  353. # must not rotate again.
  354. _stage22_finish_frames: dict[int, bytes] = {}
  355. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  356. # `finally` block (whether it captured a frame or not). The consumer in
  357. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  358. # so the FINISH-state fallback path — where moment and completion are dispatched
  359. # back-to-back — doesn't race past the producer with an empty pop, and the
  360. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  361. # grab (Bambu printers allow only one RTSP client at a time).
  362. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  363. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  364. # layer-change and on print-progress advances (#2547) while the model is still
  365. # printing, then consumed by the FINISH-state finish-photo path when the
  366. # dispatcher recorded that it injected End G-code into this print. Bambu
  367. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  368. # plate-swap) has run, so a live grab there would capture the swapped/empty
  369. # plate.
  370. #
  371. # The load-bearing property: both drivers are print telemetry that stops before
  372. # the End G-code executes — no further layer_num increases, and mc_percent
  373. # freezes — so the last banked frame is always the finished print before the
  374. # swap. Anything added as a third driver must hold that same property.
  375. _inprint_frame_bank: dict[int, bytes] = {}
  376. # Monotonic timestamp of the last banked frame per printer — throttles banking
  377. # so tall prints don't add a camera grab on every layer.
  378. _inprint_frame_bank_ts: dict[int, float] = {}
  379. # Minimum seconds between banked frames, except the final object layer which
  380. # always refreshes for the best framing.
  381. _INPRINT_BANK_MIN_INTERVAL = 25.0
  382. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  383. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  384. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  385. # the first connected status update for that connection; transitions back
  386. # to False whenever we observe `state.connected = False` so the next
  387. # reconnect re-arms reconciliation. Keyed by printer_id.
  388. _printer_reconciled_since_connect: dict[int, bool] = {}
  389. # Same edge, same keying, for priming the printer's calibration table exactly
  390. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  391. # is otherwise filled only when someone opens the Profiles page or Configure
  392. # Slot, when a GitHub backup runs, or when the printer happens to answer
  393. # somebody else's query on the report topic. Until then the AMS slot card has
  394. # no K value to show on the printers whose trays carry none of their own
  395. # (#2854 — H2-series report cali_idx and nothing more).
  396. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  397. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  398. # {(printer_id, filename): archive_id}
  399. _expected_prints: dict[tuple[int, str], int] = {}
  400. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  401. # Used by usage tracker to map 3MF slots to physical AMS trays
  402. _print_ams_mappings: dict[int, list[int]] = {}
  403. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  404. _print_cost_center_ids: dict[int, int] = {}
  405. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  406. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  407. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  408. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  409. # for the queue path. Cleared on print completion or TTL eviction.
  410. _print_plate_ids: dict[int, int] = {}
  411. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  412. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  413. _last_progress_milestone: dict[int, int] = {}
  414. # Track whether first layer complete notification has been sent for current print
  415. _first_layer_notified: dict[int, bool] = {}
  416. # Track whether we already sent a kill-switch stop for the current unauthorized print
  417. _unauthorized_print_kill_sent: set[int] = set()
  418. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  419. # lookup briefly so an unknown active print does not query the database on
  420. # every status frame. A short TTL keeps settings changes responsive.
  421. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  422. _kill_switch_setting_cache: tuple[bool, float] | None = None
  423. # Provider notification started when the kill switch stops a print. The later
  424. # MQTT print-complete callback awaits this task and only sends its regular
  425. # provider notification when the immediate attempt failed.
  426. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  427. # Track HMS errors that have been notified: {printer_id: set of error codes}
  428. # This prevents sending duplicate notifications for the same error
  429. _notified_hms_errors: dict[int, set[str]] = {}
  430. # Track when HMS errors were last seen: {printer_id: timestamp}
  431. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  432. _hms_last_seen: dict[int, float] = {}
  433. _HMS_CLEAR_GRACE_SECONDS = 30.0
  434. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  435. # Used for snapshot-diff detection at print completion
  436. _timelapse_baselines: dict[int, set[str]] = {}
  437. # Track printers waiting for bed to cool after print completion.
  438. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  439. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  440. _bed_cool_waiters: dict[int, dict] = {}
  441. # Track printers where the user explicitly stopped the print from the queue UI.
  442. # When on_print_complete fires with status "failed" for these printers we treat it
  443. # as "cancelled" (stopped by user) so the correct notification email is sent.
  444. _user_stopped_printers: set[int] = set()
  445. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  446. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  447. # holds the previous observation so we only fire on the True → False edge (a
  448. # False → False repeat doesn't notify; an initial False at startup doesn't
  449. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  450. # holds the per-printer pending asyncio task that fires the notification
  451. # after a debounce window — cancelled if the printer reconnects before the
  452. # window elapses, so transient MQTT blips don't flood the user.
  453. _printer_last_connected: dict[int, bool] = {}
  454. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  455. # Debounce: a printer must stay offline this long before we notify. Sized
  456. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  457. # so a single stale-trigger cooldown isn't enough to fire — only a real
  458. # offline that survives one reconnect attempt notifies.
  459. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  460. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  461. # when status="failed" to label the print's failure_reason in archives.
  462. #
  463. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  464. # which is wrong on two counts:
  465. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  466. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  467. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  468. # the public wiki) as part of its user-cancel sequence. Matching on the module
  469. # alone caused user-cancellations to be archived as "Layer shift" failures.
  470. # We now match by full short code only — anything not in this map leaves
  471. # failure_reason=None rather than guessing.
  472. # Values are the canonical camelCase failure-reason keys, NOT display labels
  473. # (issue #2974). The vocabulary is enforced on writes by
  474. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  475. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  476. # Statistics breakdown. Storing a label here instead put a second spelling of
  477. # the same cause into one column: the Failure Analysis widget groups on the raw
  478. # value, so a print the backend classified and an identical one a user
  479. # classified counted as two different reasons, and the label form could never
  480. # be translated because there was no key for ``t()`` to resolve.
  481. _HMS_FAILURE_REASONS: dict[str, str] = {
  482. # Layer shift / step loss
  483. "0300_4057": "layerShift",
  484. "0300_4068": "layerShift",
  485. "0300_800C": "layerShift",
  486. # Filament runout (printer-side & per-AMS-slot)
  487. "0300_8004": "filamentRunout",
  488. "0700_8011": "filamentRunout",
  489. "0701_8011": "filamentRunout",
  490. "0702_8011": "filamentRunout",
  491. "0703_8011": "filamentRunout",
  492. "0704_8011": "filamentRunout",
  493. "0705_8011": "filamentRunout",
  494. "0706_8011": "filamentRunout",
  495. "0707_8011": "filamentRunout",
  496. "07FF_8011": "filamentRunout",
  497. # Clogged nozzle / extruder
  498. "0300_4006": "cloggedNozzle",
  499. "0300_8016": "cloggedNozzle",
  500. "0300_801C": "cloggedNozzle",
  501. "0700_8003": "cloggedNozzle",
  502. "0700_8007": "cloggedNozzle",
  503. "0700_8013": "cloggedNozzle",
  504. "0701_8003": "cloggedNozzle",
  505. "0701_8007": "cloggedNozzle",
  506. "0701_8013": "cloggedNozzle",
  507. "0702_8003": "cloggedNozzle",
  508. }
  509. def _hms_short_code(attr: int, code: int | str) -> str:
  510. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  511. if isinstance(code, str):
  512. code_int = int(code.replace("0x", ""), 16) if code else 0
  513. else:
  514. code_int = int(code or 0)
  515. attr_int = int(attr or 0)
  516. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  517. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  518. """Derive a human-readable failure_reason for an archived print.
  519. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  520. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  521. no HMS code matches (don't guess — null is honest).
  522. """
  523. if status in ("aborted", "cancelled"):
  524. return "userCancelled"
  525. if status != "failed":
  526. return None
  527. for err in hms_errors or []:
  528. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  529. if short_code in _HMS_FAILURE_REASONS:
  530. return _HMS_FAILURE_REASONS[short_code]
  531. return None
  532. # Track created_by_id for expected prints so the user email can be sent even when
  533. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  534. # {(printer_id, filename): created_by_id}
  535. _expected_print_creators: dict[tuple[int, str], int] = {}
  536. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  537. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  538. # updates for the same printer in quick succession (~30 ms apart, observed in
  539. # the wild on H2D + dual AMS).
  540. #
  541. # Without this serialisation, two concurrent on_ams_change callbacks each read
  542. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  543. # the second commit hits
  544. # IntegrityError: duplicate key value violates unique constraint
  545. # "spool_assignment_printer_id_ams_id_tray_id_key"
  546. # SQLite's WAL serial-write semantics had been silently swallowing the race
  547. # until optional Postgres support landed (asyncpg allows true concurrent
  548. # transactions and surfaces the constraint violation).
  549. #
  550. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  551. # assign) are inside the lock. The Spoolman sync block further down stays
  552. # concurrent because it's network-bound and idempotent.
  553. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  554. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  555. """Return the per-printer assignment lock, creating it on first use."""
  556. lock = _ams_assignment_locks.get(printer_id)
  557. if lock is None:
  558. lock = asyncio.Lock()
  559. _ams_assignment_locks[printer_id] = lock
  560. return lock
  561. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  562. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  563. # tag tuple changes for the slot. Cleared when the slot is reported empty
  564. # so remove + reinsert reliably re-prompts the UI.
  565. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  566. async def _broadcast_unknown_tag(
  567. *,
  568. printer_id: int,
  569. ams_id: int,
  570. tray_id: int,
  571. tag_uid: str,
  572. tray_uuid: str,
  573. tray_type: str | None = None,
  574. tray_color: str | None = None,
  575. tray_sub_brands: str | None = None,
  576. tray_count: int | None = None,
  577. ) -> None:
  578. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  579. _logger = logging.getLogger(__name__)
  580. slot_key = (ams_id, tray_id)
  581. tag_key = (tag_uid or "", tray_uuid or "")
  582. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  583. if per_printer.get(slot_key) == tag_key:
  584. _logger.debug(
  585. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  586. printer_id,
  587. ams_id,
  588. tray_id,
  589. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  590. )
  591. return
  592. _logger.info(
  593. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  594. printer_id,
  595. ams_id,
  596. tray_id,
  597. tray_type,
  598. tray_color,
  599. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  600. )
  601. # Broadcast first; only commit the dedup if the WS write succeeds.
  602. # If broadcast raises, the next MQTT push retries instead of being
  603. # permanently silenced by a poisoned dedup entry.
  604. await ws_manager.broadcast(
  605. {
  606. "type": "unknown_tag",
  607. "printer_id": printer_id,
  608. "ams_id": ams_id,
  609. "tray_id": tray_id,
  610. "tag_uid": tag_uid,
  611. "tray_uuid": tray_uuid,
  612. "tray_type": tray_type,
  613. "tray_color": tray_color,
  614. "tray_sub_brands": tray_sub_brands,
  615. "tray_count": tray_count,
  616. }
  617. )
  618. per_printer[slot_key] = tag_key
  619. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  620. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  621. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  622. if per_printer is None:
  623. return
  624. per_printer.pop((ams_id, tray_id), None)
  625. # TTL for expected-print entries: evict registrations older than this to prevent
  626. # unbounded growth when a print is registered but never starts (e.g. printer
  627. # disconnect, app restart, print started from the printer panel).
  628. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  629. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  630. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  631. # Cleanup loop interval
  632. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  633. _expected_prints_cleanup_task: asyncio.Task | None = None
  634. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  635. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  636. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  637. possible_keys: list[tuple[int, str]] = []
  638. filename = (state.gcode_file or state.current_print or "").strip()
  639. subtask_name = (state.subtask_name or "").strip()
  640. if subtask_name:
  641. possible_keys.append((printer_id, subtask_name))
  642. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  643. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  644. if filename:
  645. base_name = filename.rsplit("/", 1)[-1]
  646. if base_name.endswith(".gcode.3mf"):
  647. root_name = base_name[: -len(".gcode.3mf")]
  648. possible_keys.append((printer_id, root_name))
  649. possible_keys.append((printer_id, base_name))
  650. possible_keys.append((printer_id, f"{root_name}.gcode"))
  651. possible_keys.append((printer_id, f"{root_name}.3mf"))
  652. elif base_name.endswith(".3mf"):
  653. root_name = base_name[: -len(".3mf")]
  654. possible_keys.append((printer_id, root_name))
  655. possible_keys.append((printer_id, base_name))
  656. elif base_name.endswith(".gcode"):
  657. root_name = base_name[: -len(".gcode")]
  658. possible_keys.append((printer_id, root_name))
  659. possible_keys.append((printer_id, f"{root_name}.3mf"))
  660. possible_keys.append((printer_id, base_name))
  661. else:
  662. possible_keys.append((printer_id, base_name))
  663. possible_keys.append((printer_id, f"{base_name}.3mf"))
  664. return possible_keys
  665. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  666. """Check the cheap, process-local print ownership signals."""
  667. if printer_manager.get_current_print_user(printer_id):
  668. return True
  669. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  670. async def _is_printer_kill_switch_enabled_cached() -> bool:
  671. """Return the kill-switch setting without querying on every MQTT frame."""
  672. global _kill_switch_setting_cache
  673. now = time.monotonic()
  674. if _kill_switch_setting_cache is not None:
  675. enabled, expires_at = _kill_switch_setting_cache
  676. if now < expires_at:
  677. return enabled
  678. async with async_session() as db:
  679. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  680. enabled = await is_printer_kill_switch_enabled(db)
  681. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  682. return enabled
  683. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  684. """Resolve whether the current print was started by Bambuddy.
  685. ``None`` means identity is not yet safe to decide. The kill switch must
  686. defer in that case: stopping a print is irreversible, and the first status
  687. frames after a restart may arrive before all subtask fields are populated.
  688. """
  689. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  690. return True
  691. possible_keys = _build_status_print_keys(printer_id, state)
  692. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  693. # is on disk. subtask_id is minted per print and pins the answer to the job
  694. # actually running, rather than to an unrelated one that reuses a filename.
  695. raw_subtask_id = getattr(state, "subtask_id", None)
  696. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  697. if subtask_id in ("", "0"):
  698. return None
  699. from backend.app.models.archive import PrintArchive
  700. result = await db.execute(
  701. select(PrintArchive)
  702. .where(
  703. PrintArchive.printer_id == printer_id,
  704. PrintArchive.status == "printing",
  705. PrintArchive.subtask_id == subtask_id,
  706. )
  707. .order_by(PrintArchive.created_at.desc())
  708. .limit(1)
  709. )
  710. archive = result.scalar_one_or_none()
  711. # An archive row on its own proves nothing: `on_print_start` archives every
  712. # print it observes, including ones started from Bambu Studio or Handy, and
  713. # stamps them with the same status and subtask_id. Authorizing on its mere
  714. # existence would disable the kill switch the moment the 3MF finishes
  715. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  716. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  717. # (carried over from the queue item that started it).
  718. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  719. # Rehydrate the fast in-memory path for subsequent status frames. Include
  720. # both the archive filename and every normalized key reported by MQTT.
  721. _active_prints[(printer_id, archive.filename)] = archive.id
  722. for key in possible_keys:
  723. _active_prints[key] = archive.id
  724. return True
  725. # No dispatch marker. Before calling this someone else's print, check whether
  726. # Bambuddy has a job of its own running on this printer: a library-file
  727. # dispatch has no archive at send time, and an archive created seconds later
  728. # by `on_print_start` carries neither marker. The queue row, which the
  729. # scheduler commits to status="printing" before the MQTT send, is the one
  730. # durable record every Bambuddy print has. It cannot be tied to this
  731. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  732. # print is irreversible, and refusing to act costs nothing but a log line.
  733. from backend.app.models.print_queue import PrintQueueItem
  734. dispatched_here = await db.scalar(
  735. select(PrintQueueItem.id)
  736. .where(
  737. PrintQueueItem.printer_id == printer_id,
  738. PrintQueueItem.status == "printing",
  739. )
  740. .limit(1)
  741. )
  742. if dispatched_here is not None:
  743. return None
  744. return False
  745. async def _send_kill_switch_provider_notification(
  746. printer_id: int,
  747. printer_name: str,
  748. data: dict,
  749. ) -> bool:
  750. """Send the immediate print-stopped provider notification.
  751. Returning a success flag lets the normal MQTT completion path retry when
  752. this early notification could not be delivered.
  753. """
  754. logger = logging.getLogger(__name__)
  755. try:
  756. async with async_session() as db:
  757. await notification_service.on_print_complete(
  758. printer_id,
  759. printer_name,
  760. "stopped",
  761. data,
  762. db,
  763. )
  764. return True
  765. except Exception as e:
  766. logger.warning(
  767. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  768. printer_id,
  769. e,
  770. )
  771. return False
  772. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  773. """Wait for an immediate kill-switch notification, if one was scheduled."""
  774. if task is None:
  775. return False
  776. try:
  777. return await task
  778. except Exception as e:
  779. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  780. return False
  781. async def _get_plug_energy(plug, db) -> dict | None:
  782. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  783. For HA plugs, configures the service with current settings from DB.
  784. For MQTT plugs, returns data from the subscription service.
  785. For REST plugs, polls the status URL with JSON path extraction.
  786. """
  787. if plug.plug_type == "homeassistant":
  788. from backend.app.api.routes.settings import get_homeassistant_settings
  789. ha_settings = await get_homeassistant_settings(db)
  790. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  791. return await homeassistant_service.get_energy(plug)
  792. elif plug.plug_type == "mqtt":
  793. # MQTT plugs report "today" energy, not lifetime total
  794. # For per-print tracking, we use "today" as the counter (resets at midnight)
  795. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  796. if mqtt_data:
  797. return {
  798. "power": mqtt_data.power,
  799. "today": mqtt_data.energy,
  800. "total": mqtt_data.energy, # Use today as total for per-print calculations
  801. }
  802. return None
  803. elif plug.plug_type == "rest":
  804. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  805. return await rest_smart_plug_service.get_energy(plug)
  806. else:
  807. return await tasmota_service.get_energy(plug)
  808. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  809. """Capture the smart plug lifetime counter on the archive at print start.
  810. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  811. tracking survives a backend restart mid-print. The print-end handler reads
  812. this value back from the DB and computes the delta against the current
  813. plug counter.
  814. """
  815. _logger = logging.getLogger(__name__)
  816. try:
  817. candidates = await energy_plug_candidates(db, printer_id)
  818. if not candidates:
  819. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  820. return False
  821. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  822. if selected is None:
  823. # Naming the plugs matters here: with several linked to one printer
  824. # this is the difference between "the meter is offline" and "you
  825. # linked only accessories" (#2859).
  826. _logger.warning(
  827. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  828. printer_id,
  829. archive.id,
  830. ", ".join(plug.name for plug in candidates),
  831. )
  832. return False
  833. plug, energy = selected
  834. archive.energy_start_kwh = float(energy["total"])
  835. await db.commit()
  836. _logger.info(
  837. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  838. f" ({context})" if context else "",
  839. archive.id,
  840. plug.name,
  841. energy["total"],
  842. )
  843. return True
  844. except Exception as e:
  845. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  846. return False
  847. def register_expected_print(
  848. printer_id: int,
  849. filename: str,
  850. archive_id: int,
  851. ams_mapping: list[int] | None = None,
  852. created_by_id: int | None = None,
  853. cost_center_id: int | None = None,
  854. plate_id: int | None = None,
  855. ):
  856. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  857. # Store with multiple filename variations to catch different naming patterns
  858. _expected_prints[(printer_id, filename)] = archive_id
  859. # Also store without .3mf extension if present
  860. if filename.endswith(".3mf"):
  861. base = filename[:-4]
  862. _expected_prints[(printer_id, base)] = archive_id
  863. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  864. # Store AMS mapping for usage tracking at print completion
  865. if ams_mapping is not None:
  866. _print_ams_mappings[archive_id] = ams_mapping
  867. if cost_center_id is not None:
  868. _print_cost_center_ids[archive_id] = cost_center_id
  869. # Store plate_id for usage tracking when this is a single-plate dispatch from
  870. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  871. # file's filament total to the spool instead of just the printed plate (#1697).
  872. if plate_id is not None:
  873. _print_plate_ids[archive_id] = plate_id
  874. # Store created_by_id so the user start email can be sent even when the archive
  875. # itself has no created_by_id (e.g. library-file-based queue prints)
  876. if created_by_id is not None:
  877. _expected_print_creators[(printer_id, filename)] = created_by_id
  878. if filename.endswith(".3mf"):
  879. base = filename[:-4]
  880. _expected_print_creators[(printer_id, base)] = created_by_id
  881. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  882. # Record registration time for TTL-based eviction
  883. _registered_at = time.monotonic()
  884. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  885. if filename.endswith(".3mf"):
  886. base = filename[:-4]
  887. _expected_print_registered_at[(printer_id, base)] = _registered_at
  888. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  889. logging.getLogger(__name__).info(
  890. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  891. )
  892. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  893. """Undo :func:`register_expected_print` when the print never went out.
  894. Registration has to happen *before* the MQTT print command, because the
  895. printer can report the print before the line after the send executes. So
  896. every path that registers and then fails to send — a cancel winning the
  897. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  898. between — leaves an expectation for a print that will never arrive.
  899. The TTL sweep evicts those after two hours, which is far longer than it
  900. takes a user to react to a failed dispatch by pressing print again: that
  901. reprint would be folded into the *old* archive and take the stale
  902. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  903. Mirrors the sweep's rules, including the one that is easy to get wrong:
  904. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  905. file, so they may only be dropped once no live key still points at that
  906. archive.
  907. """
  908. keys = [(printer_id, filename)]
  909. if filename.endswith(".3mf"):
  910. base = filename[:-4]
  911. keys.append((printer_id, base))
  912. keys.append((printer_id, f"{base}.gcode"))
  913. removed = False
  914. for key in keys:
  915. if _expected_prints.pop(key, None) is not None:
  916. removed = True
  917. _expected_print_creators.pop(key, None)
  918. _expected_print_registered_at.pop(key, None)
  919. if archive_id not in set(_expected_prints.values()):
  920. _print_ams_mappings.pop(archive_id, None)
  921. _print_plate_ids.pop(archive_id, None)
  922. if removed:
  923. logging.getLogger(__name__).info(
  924. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  925. printer_id,
  926. filename,
  927. archive_id,
  928. )
  929. def _compute_run_filament_grams(
  930. status: str,
  931. archive_filament_used_grams: float | None,
  932. progress: float | int | None,
  933. usage_results: list[dict] | None,
  934. ) -> float | None:
  935. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  936. Priority for every status:
  937. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  938. weight delta — same source that drives "Total Consumed" on the
  939. Inventory page, so Stats and Inventory totals stay aligned).
  940. 2. For ``completed``: the slicer estimate (no tracker available, fall
  941. back to the canonical "this print used X" value).
  942. 3. For partial statuses: ``estimate * progress%``.
  943. 4. ``None`` if nothing is known.
  944. """
  945. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  946. if tracked_grams > 0:
  947. return round(tracked_grams, 1)
  948. if status == "completed":
  949. return archive_filament_used_grams
  950. if archive_filament_used_grams:
  951. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  952. if scale > 0:
  953. return round(archive_filament_used_grams * scale, 1)
  954. return None
  955. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  956. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  957. stored_ams_mapping = data.get("ams_mapping")
  958. if not stored_ams_mapping and archive_id:
  959. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  960. return stored_ams_mapping
  961. def _get_start_plate_id(archive_id: int | None) -> int | None:
  962. """Resolve plate_id for print start without consuming stored direct-Print state.
  963. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  964. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  965. read it back at print-start without popping (the entry is popped on print
  966. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  967. """
  968. if archive_id is None:
  969. return None
  970. return _print_plate_ids.get(archive_id)
  971. def _partial_progress_scale(progress: int | float | None) -> float:
  972. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  973. Used by every site that multiplies a "would-have-used" slicer estimate
  974. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  975. so the three sites in ``_background_notifications`` (and the per-plate
  976. override helper) can't drift apart on the coercion shape.
  977. """
  978. return max(0.0, min((progress or 0) / 100.0, 1.0))
  979. def _scope_notification_archive_data_to_plate(
  980. archive_data: dict,
  981. archive_file_path: str | None,
  982. plate_id: int | None,
  983. print_status: str,
  984. progress: int | float | None,
  985. base_dir: Path,
  986. ) -> dict:
  987. """Override summed-across-plates totals in ``archive_data`` with the values
  988. for ``plate_id`` so the completion notification reports what was actually
  989. printed, not the whole project (#1785).
  990. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  991. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  992. the archive card's "whole project" headline, wrong for the completion
  993. notification of a single-plate print. The queue UI already re-reads the
  994. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  995. notification payload (filament grams, time estimate, per-slot breakdown).
  996. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  997. no per-plate values — in every fail case the original ``archive_data`` is
  998. returned unchanged so the notification still sends.
  999. """
  1000. if plate_id is None or not archive_file_path:
  1001. return archive_data
  1002. from backend.app.utils.threemf_tools import (
  1003. extract_filament_usage_from_3mf,
  1004. extract_print_time_from_3mf,
  1005. )
  1006. archive_path = base_dir / archive_file_path
  1007. if not archive_path.exists():
  1008. return archive_data
  1009. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1010. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1011. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1012. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1013. if plate_time:
  1014. archive_data["print_time_seconds"] = plate_time
  1015. # Gate both the grams headline AND the per-slot breakdown on the same
  1016. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1017. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1018. # to the project-level grams the archive columns already provide rather
  1019. # than ship a project-level headline next to an all-zero per-plate
  1020. # breakdown.
  1021. if plate_grams > 0:
  1022. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1023. archive_data["filament_slots"] = [
  1024. {
  1025. "slot_id": s.get("slot_id"),
  1026. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1027. "type": s.get("type", ""),
  1028. "color": s.get("color", ""),
  1029. }
  1030. for s in plate_slots
  1031. ]
  1032. return archive_data
  1033. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1034. """Best-effort filament metadata from the MQTT print-start snapshot.
  1035. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1036. file during print, see #1533) so the fallback PrintArchive still has
  1037. enough filament info to support the inventory views and AMS-expansion
  1038. planning the operator opens it for. Returns a dict with optional
  1039. ``filament_type`` and ``filament_color`` keys in the same
  1040. comma-separated format the 3MF extractor produces, so the rest of the
  1041. codebase treats the fallback archive identically to a normal one.
  1042. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1043. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1044. entries). When supplied, only the slots actually consumed by this
  1045. print contribute. Without it the function falls back to every loaded
  1046. AMS slot — less accurate but still useful.
  1047. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1048. that the unit tests pass directly, AND the on_print_start callback
  1049. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1050. bambu_mqtt service hands to main.py at runtime. The original
  1051. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1052. handled the inner shape and silently returned ``{}`` for every real
  1053. print start, leaving fallback archives' filament fields NULL — the
  1054. exact regression the fix was meant to close. Reported with a log
  1055. proving the AMS state was right there at
  1056. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1057. """
  1058. result: dict[str, str] = {}
  1059. # Look at the on_print_start wrapper first, then the inner shape.
  1060. raw_data = (data or {}).get("raw_data")
  1061. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1062. if not isinstance(ams_root, dict):
  1063. ams_root = (data or {}).get("ams") or {}
  1064. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1065. if not isinstance(ams_units, list) or not ams_units:
  1066. return result
  1067. # Map global tray id (unit * 4 + tray) → (type, color).
  1068. loaded: dict[int, tuple[str, str]] = {}
  1069. for unit in ams_units:
  1070. if not isinstance(unit, dict):
  1071. continue
  1072. try:
  1073. unit_id = int(unit.get("id", 0))
  1074. except (TypeError, ValueError):
  1075. continue
  1076. for tray in unit.get("tray") or []:
  1077. if not isinstance(tray, dict):
  1078. continue
  1079. try:
  1080. tray_id = int(tray.get("id", 0))
  1081. except (TypeError, ValueError):
  1082. continue
  1083. ttype = (tray.get("tray_type") or "").strip()
  1084. tcolor = (tray.get("tray_color") or "").strip().upper()
  1085. if not ttype:
  1086. continue # Empty / unloaded slot.
  1087. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1088. if not loaded:
  1089. return result
  1090. if ams_mapping:
  1091. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1092. filaments = [loaded[g] for g in used_ids if g in loaded]
  1093. if not filaments:
  1094. return result # Mapping points entirely at slots we have no data for.
  1095. else:
  1096. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1097. types_joined = ",".join(f[0] for f in filaments)
  1098. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1099. # Column limits per backend/app/models/archive.py: filament_type=50,
  1100. # filament_color=200.
  1101. if types_joined:
  1102. result["filament_type"] = types_joined[:50]
  1103. if colors_joined:
  1104. result["filament_color"] = colors_joined[:200]
  1105. return result
  1106. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1107. """Start a layer-timelapse session for *archive_id* when the printer has
  1108. an external camera configured. Returns True if a session was started.
  1109. Three call sites in on_print_start (expected-archive promotion, fallback
  1110. archive creation, fresh-archive creation) used to inline this same
  1111. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1112. on the first pass). Centralising the conditional + call here makes the
  1113. contract testable in isolation and keeps the three sites locked in step.
  1114. """
  1115. if not (printer.external_camera_enabled and printer.external_camera_url):
  1116. return False
  1117. from backend.app.services.layer_timelapse import start_session
  1118. start_session(
  1119. printer_id,
  1120. archive_id,
  1121. printer.external_camera_url,
  1122. printer.external_camera_type or "mjpeg",
  1123. snapshot_url=printer.external_camera_snapshot_url,
  1124. rotation=getattr(printer, "camera_rotation", 0),
  1125. )
  1126. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1127. return True
  1128. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1129. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1130. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1131. — since #2926 — the description the parser already resolved, which is preferred
  1132. when present so the queue's failure reason reads the same as the status
  1133. response. The short code still produces the bracketed label, and still
  1134. resolves the sentence for a caller whose entries predate the field. Falls back
  1135. to the bare short code when no description is on file. Returns None for an
  1136. empty list so callers can leave error_message unset.
  1137. """
  1138. if not hms_errors:
  1139. return None
  1140. from backend.app.services.hms_errors import get_error_description
  1141. parts: list[str] = []
  1142. for err in hms_errors:
  1143. try:
  1144. # `_hms_short_code` rather than a local derivation: this one used to
  1145. # format the error without masking it to 16 bits, so an `hms[]` entry
  1146. # whose code carries an alert-level group produced a five-digit label
  1147. # like "0500_3000A" — not a code the user can look up, and never a
  1148. # catalogue key, so the sentence was lost with it.
  1149. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1150. except (TypeError, ValueError):
  1151. continue
  1152. description = err.get("description") or get_error_description(short_code)
  1153. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  1154. return "; ".join(parts) if parts else None
  1155. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1156. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1157. print completes successfully. Gated to status=='completed': failed, cancelled
  1158. and aborted prints do not count as usage. Caller is responsible for committing
  1159. the session. No-op when the queue item has no linked library file (e.g. reprints
  1160. from an archive). See #1008."""
  1161. if queue_status != "completed" or item.library_file_id is None:
  1162. return
  1163. from backend.app.models.library import LibraryFile
  1164. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1165. if lib_file is None:
  1166. return
  1167. lib_file.print_count = (lib_file.print_count or 0) + 1
  1168. lib_file.last_printed_at = datetime.now(timezone.utc)
  1169. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1170. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1171. When on_print_complete fires with status 'failed' for a printer in this set we
  1172. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1173. rather than a 'print failed' notification.
  1174. """
  1175. _user_stopped_printers.add(printer_id)
  1176. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1177. _last_status_broadcast: dict[int, str] = {}
  1178. # Track printers where we've updated nozzle_count
  1179. _nozzle_count_updated: set[int] = set()
  1180. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1181. """Wait the debounce window then fire `on_printer_offline` if the printer
  1182. is still offline.
  1183. Scheduled by `on_printer_status_change` on the connected → disconnected
  1184. edge (#1752). Cancelled by the same handler if the printer reconnects
  1185. before the window elapses, so a single MQTT blip + recovery doesn't
  1186. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1187. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1188. route through the same status-change callback, so this covers both.
  1189. """
  1190. logger = logging.getLogger(__name__)
  1191. try:
  1192. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1193. still_offline = not printer_manager.is_connected(printer_id)
  1194. logger.info(
  1195. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1196. printer_id,
  1197. still_offline,
  1198. )
  1199. if not still_offline:
  1200. return
  1201. async with async_session() as db:
  1202. from backend.app.models.printer import Printer
  1203. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1204. printer = result.scalar_one_or_none()
  1205. if not printer:
  1206. logger.warning(
  1207. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1208. printer_id,
  1209. )
  1210. return
  1211. logger.info(
  1212. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1213. printer_id,
  1214. printer.name,
  1215. )
  1216. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1217. except asyncio.CancelledError:
  1218. raise
  1219. except Exception as e:
  1220. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1221. finally:
  1222. _printer_offline_notify_tasks.pop(printer_id, None)
  1223. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1224. """Handle printer status changes - broadcast via WebSocket."""
  1225. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1226. # transitions disconnected → connected — which covers both Bambuddy
  1227. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1228. # `reconcile_stale_active_prints` exactly once for this connection so
  1229. # any archive still in `status="printing"` that can't actually be
  1230. # running anymore (printer IDLE / different subtask / empty subtask)
  1231. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1232. # finished during a disconnect window + a smart-plug power cycle
  1233. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1234. # next boot. Reconciliation runs concurrently — it must not block the
  1235. # WebSocket dedup / broadcast logic below, and the connected edge is
  1236. # marked True BEFORE the await so concurrent status updates inside
  1237. # the same connection don't re-trigger reconciliation.
  1238. #
  1239. # Wait for a real push_status before reconciling (#1679): MQTT
  1240. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1241. # the connection, BEFORE `_request_push_all` round-trips. At that
  1242. # instant the `PrinterState` is still on construction defaults — most
  1243. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1244. # If reconcile spawns here, every in-flight archive falls through to
  1245. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1246. # creates a duplicate archive on the real PRINT COMPLETE and
  1247. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1248. # keeps the #1542 mechanism intact: once the first real push_status
  1249. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1250. # fires again with the flag still False — reconcile then runs against
  1251. # actual evidence.
  1252. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1253. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1254. _printer_reconciled_since_connect[printer_id] = True
  1255. spawn_background_task(
  1256. reconcile_stale_active_prints(printer_id),
  1257. name=f"reconcile-stale-prints-{printer_id}",
  1258. )
  1259. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1260. # Re-arm so the next reconnect triggers reconciliation again.
  1261. _printer_reconciled_since_connect[printer_id] = False
  1262. # Same edge, for the calibration table the AMS card reads its K values from.
  1263. #
  1264. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1265. # tables to ask for. A `state_known` gate alone is not enough: the first
  1266. # real push_status is what makes the state known, and the nozzle fields do
  1267. # not always arrive in it. Latching there would spend this connection's one
  1268. # attempt on a printer that could not yet say what was fitted.
  1269. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1270. if (
  1271. state.connected
  1272. and state_known
  1273. and nozzle_known
  1274. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1275. ):
  1276. _printer_kprofiles_primed_since_connect[printer_id] = True
  1277. spawn_background_task(
  1278. prime_kprofile_table(printer_id),
  1279. name=f"prime-kprofiles-{printer_id}",
  1280. )
  1281. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1282. _printer_kprofiles_primed_since_connect[printer_id] = False
  1283. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1284. # connected → disconnected. The "back online" channel is already covered
  1285. # by the print-failure notification (firmware reports gcode_state=FAILED
  1286. # on reconnect of an interrupted print), so we don't add a symmetric
  1287. # online event here.
  1288. prev_connected = _printer_last_connected.get(printer_id)
  1289. _printer_last_connected[printer_id] = state.connected
  1290. if prev_connected is True and not state.connected:
  1291. existing = _printer_offline_notify_tasks.get(printer_id)
  1292. if existing is None or existing.done():
  1293. logging.getLogger(__name__).info(
  1294. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1295. printer_id,
  1296. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1297. )
  1298. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1299. _maybe_notify_printer_offline(printer_id),
  1300. name=f"printer-offline-notify-{printer_id}",
  1301. )
  1302. elif state.connected:
  1303. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1304. if pending is not None and not pending.done():
  1305. logging.getLogger(__name__).info(
  1306. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1307. printer_id,
  1308. )
  1309. pending.cancel()
  1310. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1311. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1312. temps = state.temperatures or {}
  1313. nozzle_temp = round(temps.get("nozzle", 0))
  1314. bed_temp = round(temps.get("bed", 0))
  1315. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1316. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1317. # Auto-detect dual-nozzle printers from MQTT temperature data
  1318. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1319. _nozzle_count_updated.add(printer_id)
  1320. # Update nozzle_count in database
  1321. async with async_session() as db:
  1322. from backend.app.models.printer import Printer
  1323. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1324. printer = result.scalar_one_or_none()
  1325. if printer and printer.nozzle_count != 2:
  1326. printer.nozzle_count = 2
  1327. await db.commit()
  1328. logging.getLogger(__name__).info(
  1329. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1330. )
  1331. # Include target temps for heating phase detection
  1332. bed_target = round(temps.get("bed_target", 0))
  1333. nozzle_target = round(temps.get("nozzle_target", 0))
  1334. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1335. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1336. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  1337. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  1338. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1339. #
  1340. # The filament identity fields are here because Configure Slot writes
  1341. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1342. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1343. # matched, this function returned before broadcasting, and the card kept
  1344. # showing the old filament until the 30s fallback poll or a page reload —
  1345. # even though the configure route asks the printer for a fresh pushall and
  1346. # that push does carry the new values. Reset always worked, because it
  1347. # clears tray_type.
  1348. #
  1349. # These fields only change when someone configures a slot or swaps a spool,
  1350. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1351. ams_tray_key = (
  1352. tuple(
  1353. (
  1354. t.get("id"),
  1355. t.get("tray_type", ""),
  1356. t.get("state"),
  1357. t.get("tray_color", ""),
  1358. t.get("tray_info_idx", ""),
  1359. t.get("tray_sub_brands", ""),
  1360. t.get("cali_idx"),
  1361. )
  1362. for a in (state.raw_data.get("ams") or [])
  1363. for t in a.get("tray", [])
  1364. )
  1365. if state.raw_data
  1366. else ()
  1367. )
  1368. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1369. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1370. # in the AMS change-hash (tray fields only, and widening that would fire
  1371. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1372. # screen changed no key at all and the card's inlet badges sat stale until a
  1373. # reload. Like the filament-backup flag, these only move when someone
  1374. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1375. fts_key = (
  1376. state.fila_switch.installed if state.fila_switch else False,
  1377. tuple(sorted(state.ams_switch_inlet.items())),
  1378. # Which hotend holds which slot. Unlike the two above this does move
  1379. # mid-print, on every filament change — but only between discrete slots,
  1380. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1381. # it live: it decides which hotend the Load dialog may offer and whether
  1382. # Unload has anything to act on.
  1383. tuple(
  1384. sorted(
  1385. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1386. # Sort on the extruder id alone: the other members are nullable
  1387. # and comparing None with an int raises.
  1388. key=lambda entry: entry[0],
  1389. )
  1390. ),
  1391. )
  1392. status_key = (
  1393. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1394. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1395. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1396. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1397. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1398. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1399. )
  1400. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1401. if not is_active_print:
  1402. _unauthorized_print_kill_sent.discard(printer_id)
  1403. elif printer_id in _unauthorized_print_kill_sent:
  1404. # stop_print() was already sent for this print; avoid all further
  1405. # ownership and settings work until the printer leaves an active state.
  1406. pass
  1407. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1408. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1409. _unauthorized_print_kill_sent.discard(printer_id)
  1410. else:
  1411. kill_switch_enabled = False
  1412. authorization: bool | None = None
  1413. status_logger = logging.getLogger(__name__)
  1414. try:
  1415. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1416. if kill_switch_enabled:
  1417. async with async_session() as db:
  1418. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1419. except Exception as e:
  1420. # Fail safe: a database/reconciliation error must never turn into an
  1421. # irreversible stop of a print whose ownership is still unknown.
  1422. authorization = None
  1423. status_logger.warning(
  1424. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1425. )
  1426. if not kill_switch_enabled or authorization is True:
  1427. _unauthorized_print_kill_sent.discard(printer_id)
  1428. elif authorization is None:
  1429. _unauthorized_print_kill_sent.discard(printer_id)
  1430. status_logger.debug(
  1431. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1432. printer_id,
  1433. )
  1434. else:
  1435. try:
  1436. stopped = printer_manager.stop_print(printer_id)
  1437. if stopped:
  1438. _unauthorized_print_kill_sent.add(printer_id)
  1439. printer_info = printer_manager.get_printer(printer_id)
  1440. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1441. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1442. notification_data = {
  1443. "status": "stopped",
  1444. "filename": state.gcode_file or state.current_print or "",
  1445. "subtask_name": state.subtask_name or "",
  1446. "progress": state.progress,
  1447. "reason": "unauthorized_print",
  1448. }
  1449. status_logger.warning(
  1450. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1451. printer_id,
  1452. state.state,
  1453. )
  1454. try:
  1455. await ws_manager.broadcast(
  1456. {
  1457. "type": "kill_switch_triggered",
  1458. "printer_id": printer_id,
  1459. "printer_name": printer_name,
  1460. "filename": filename,
  1461. "reason": "unauthorized_print",
  1462. }
  1463. )
  1464. except Exception as e:
  1465. status_logger.warning(
  1466. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1467. )
  1468. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1469. if previous_task is not None and not previous_task.done():
  1470. previous_task.cancel()
  1471. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1472. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1473. name=f"kill-switch-notification-{printer_id}",
  1474. )
  1475. else:
  1476. status_logger.warning(
  1477. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1478. printer_id,
  1479. state.state,
  1480. )
  1481. except Exception as e:
  1482. status_logger.warning(
  1483. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1484. )
  1485. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1486. try:
  1487. printer_info = printer_manager.get_printer(printer_id)
  1488. if printer_info:
  1489. await mqtt_relay.on_printer_status(
  1490. printer_id,
  1491. state,
  1492. printer_info.name,
  1493. printer_info.serial_number,
  1494. printer_manager.is_awaiting_plate_clear(printer_id),
  1495. )
  1496. except Exception:
  1497. pass # Don't fail status callback if MQTT fails
  1498. if _last_status_broadcast.get(printer_id) == status_key:
  1499. return # No change, skip WebSocket broadcast
  1500. _last_status_broadcast[printer_id] = status_key
  1501. # Check for progress milestone notifications (25%, 50%, 75%)
  1502. progress = state.progress or 0
  1503. is_printing = state.state in ("RUNNING", "PRINTING")
  1504. if is_printing and progress > 0:
  1505. # Determine which milestone we've reached
  1506. current_milestone = 0
  1507. if progress >= 75:
  1508. current_milestone = 75
  1509. elif progress >= 50:
  1510. current_milestone = 50
  1511. elif progress >= 25:
  1512. current_milestone = 25
  1513. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1514. # If we've crossed a new milestone, send notification
  1515. if current_milestone > last_milestone:
  1516. _last_progress_milestone[printer_id] = current_milestone
  1517. try:
  1518. from backend.app.models.printer import Printer
  1519. # Read the printer in a short session and release the connection
  1520. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1521. # pinned a pooled connection per milestone, per printer (issue #2572).
  1522. async with async_session() as db:
  1523. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1524. printer = result.scalar_one_or_none()
  1525. printer_name = printer.name if printer else f"Printer {printer_id}"
  1526. filename = state.subtask_name or state.gcode_file or "Unknown"
  1527. # remaining_time is in minutes, convert to seconds for notification
  1528. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1529. # Capture camera snapshot for notification image attachment (no DB held).
  1530. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1531. # Notification send needs a session (provider/template lookups).
  1532. async with async_session() as db:
  1533. await notification_service.on_print_progress(
  1534. printer_id,
  1535. printer_name,
  1536. filename,
  1537. current_milestone,
  1538. db,
  1539. remaining_time_seconds,
  1540. image_data=image_data,
  1541. )
  1542. except Exception as e:
  1543. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1544. elif progress < 5:
  1545. # Reset milestone tracking when print restarts or new print begins
  1546. _last_progress_milestone[printer_id] = 0
  1547. _first_layer_notified[printer_id] = False
  1548. # HMS error codes that should not trigger notifications even though they
  1549. # have known descriptions (e.g. user-initiated actions, not real errors).
  1550. _HMS_NOTIFICATION_SUPPRESS = {
  1551. "0500_400E", # Printing was cancelled (user action, not an error)
  1552. }
  1553. # Check for new HMS errors and send notifications
  1554. current_hms_errors = getattr(state, "hms_errors", []) or []
  1555. if current_hms_errors:
  1556. # Build set of current error codes (using attr for uniqueness)
  1557. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1558. previously_notified = _notified_hms_errors.get(printer_id, set())
  1559. # Find new errors that haven't been notified yet
  1560. new_error_codes = current_error_codes - previously_notified
  1561. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1562. _notified_hms_errors[printer_id] = current_error_codes
  1563. _hms_last_seen[printer_id] = time.time()
  1564. if new_error_codes:
  1565. # Get the actual new errors for the notification
  1566. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1567. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1568. try:
  1569. from backend.app.models.printer import Printer
  1570. # Read the printer in a short session and release the connection
  1571. # BEFORE the ~15s camera snapshot below (issue #2572).
  1572. async with async_session() as db:
  1573. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1574. printer = result.scalar_one_or_none()
  1575. printer_name = printer.name if printer else f"Printer {printer_id}"
  1576. # Format error details for notification
  1577. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1578. module_names = {
  1579. 0x03: "Print/Task",
  1580. 0x05: "Nozzle/Extruder",
  1581. 0x07: "AMS/Filament",
  1582. 0x0C: "Motion Controller",
  1583. 0x12: "Chamber",
  1584. }
  1585. # Capture camera snapshot once for all error notifications (no DB held).
  1586. error_image_data = await _capture_snapshot_for_notification(
  1587. printer_id, printer, logging.getLogger(__name__)
  1588. )
  1589. # Notification sends need a session (provider/template lookups).
  1590. async with async_session() as db:
  1591. sent_count = 0
  1592. for error in new_errors:
  1593. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1594. # Build short code like "0700_8010"
  1595. # Mask to 16 bits to handle printers that send larger values
  1596. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1597. error_code_masked = error_code_int & 0xFFFF
  1598. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1599. # Only notify for errors with known descriptions — printers
  1600. # send many undocumented/phantom codes that aren't real errors.
  1601. # Resolved at parse time (#2926); short_code is still needed
  1602. # for the suppression set below.
  1603. description = error.description
  1604. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1605. continue
  1606. error_type = f"{module_name} Error"
  1607. error_detail = description
  1608. await notification_service.on_printer_error(
  1609. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1610. )
  1611. sent_count += 1
  1612. if sent_count:
  1613. logging.getLogger(__name__).info(
  1614. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1615. )
  1616. # Also publish to MQTT relay (no DB).
  1617. printer_info = printer_manager.get_printer(printer_id)
  1618. if printer_info:
  1619. errors_data = [
  1620. {
  1621. "code": e.code,
  1622. "attr": e.attr,
  1623. "module": e.module,
  1624. "severity": e.severity,
  1625. }
  1626. for e in new_errors
  1627. ]
  1628. await mqtt_relay.on_printer_error(
  1629. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1630. )
  1631. except Exception as e:
  1632. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1633. else:
  1634. # No HMS errors — only clear tracking after a grace period to prevent
  1635. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1636. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1637. # on/off every few seconds as conditions fluctuate around thresholds.
  1638. if printer_id in _notified_hms_errors:
  1639. last_seen = _hms_last_seen.get(printer_id, 0)
  1640. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1641. _notified_hms_errors.pop(printer_id, None)
  1642. _hms_last_seen.pop(printer_id, None)
  1643. await ws_manager.send_printer_status(
  1644. printer_id,
  1645. printer_state_to_dict(
  1646. state,
  1647. printer_id,
  1648. printer_manager.get_model(printer_id),
  1649. printer_manager.get_drying_targets(printer_id),
  1650. ),
  1651. )
  1652. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1653. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1654. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1655. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1656. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1657. K-profiles are per-nozzle and the printer's calibration table is numbered
  1658. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1659. switch's other inlet therefore silently invalidates every configured slot in
  1660. it: the index stays put and now resolves against the other nozzle's table.
  1661. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1662. and 0.020 on the right kept the left profile after the move, and a manual
  1663. RFID re-read only re-asserted the same wrong one.
  1664. Configuring a slot is a deliberate preparation step, so this re-selects
  1665. rather than re-configures: only the calibration binding moves, and only for
  1666. slots whose spool already has a stored profile for the new nozzle. A slot
  1667. Bambuddy knows nothing about is left exactly as the operator left it.
  1668. """
  1669. logger = logging.getLogger(__name__)
  1670. target_extruder = extruder_for_inlet(inlet)
  1671. if target_extruder is None:
  1672. return
  1673. client = printer_manager.get_client(printer_id)
  1674. state = printer_manager.get_status(printer_id)
  1675. if not client or not state or not state.raw_data:
  1676. return
  1677. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1678. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1679. # the nozzle width, which changes both the K profile to select and the
  1680. # preset the slot should carry.
  1681. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1682. ams_raw = state.raw_data.get("ams")
  1683. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1684. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1685. if not unit:
  1686. return
  1687. try:
  1688. async with async_session() as db:
  1689. for tray in unit.get("tray", []):
  1690. tray_id = int(tray.get("id", -1))
  1691. if tray_id < 0 or not tray.get("tray_type"):
  1692. continue
  1693. current_idx = tray.get("cali_idx")
  1694. profile = await find_slot_kprofile_for_extruder(
  1695. db,
  1696. printer_id,
  1697. ams_id,
  1698. tray_id,
  1699. target_extruder,
  1700. nozzle_diameter,
  1701. printer_manager.get_model(printer_id),
  1702. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1703. )
  1704. if profile is None or profile.cali_idx is None:
  1705. continue
  1706. if current_idx == profile.cali_idx:
  1707. continue # Already on the right one.
  1708. logger.info(
  1709. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1710. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1711. printer_id,
  1712. ams_id,
  1713. tray_id,
  1714. inlet,
  1715. target_extruder,
  1716. profile.name,
  1717. current_idx,
  1718. profile.cali_idx,
  1719. profile.k_value,
  1720. )
  1721. client.extrusion_cali_sel(
  1722. ams_id=ams_id,
  1723. tray_id=tray_id,
  1724. cali_idx=profile.cali_idx,
  1725. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1726. nozzle_diameter=nozzle_diameter,
  1727. )
  1728. except Exception as e:
  1729. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1730. async def on_ams_change(printer_id: int, ams_data: list):
  1731. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1732. logger = logging.getLogger(__name__)
  1733. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1734. # on_print_complete may pop _active_sessions during our awaits (#880).
  1735. from backend.app.services.usage_tracker import _active_sessions
  1736. _print_active = printer_id in _active_sessions
  1737. # A slot that reports empty while a print is running is a filament runout,
  1738. # not a spool swap: the spool is still physically in the AMS, just
  1739. # consumed. Dropping either inventory backend's slot link there loses the
  1740. # only record of which spool fed the print, so the completion path can't
  1741. # charge the runout segment to anything. Both cleanup passes below consult
  1742. # this; computed once, up front, so neither depends on the other having run.
  1743. _unlink_state = printer_manager.get_status(printer_id)
  1744. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  1745. # MQTT relay - publish AMS change
  1746. try:
  1747. printer_info = printer_manager.get_printer(printer_id)
  1748. if printer_info:
  1749. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1750. except Exception:
  1751. pass # Don't fail AMS callback if MQTT fails
  1752. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1753. # This ensures frontend gets immediate updates when AMS slots are configured
  1754. try:
  1755. state = printer_manager.get_status(printer_id)
  1756. if state:
  1757. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1758. await ws_manager.send_printer_status(
  1759. printer_id,
  1760. printer_state_to_dict(
  1761. state,
  1762. printer_id,
  1763. printer_manager.get_model(printer_id),
  1764. printer_manager.get_drying_targets(printer_id),
  1765. ),
  1766. )
  1767. except Exception as e:
  1768. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1769. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1770. # Auto-unlink spool assignments with stale fingerprints
  1771. try:
  1772. async with async_session() as db:
  1773. from sqlalchemy.orm import selectinload
  1774. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1775. from backend.app.models.spool import Spool as _Spool
  1776. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1777. from backend.app.services.ams_slot_presence import spool_present
  1778. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1779. # Built-in assignments only. Since #2812 they survive a switch to
  1780. # Spoolman mode rather than being deleted by it, and this pass ends
  1781. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1782. # time as the AMS contents changed under the other mode, undoing the
  1783. # preservation more slowly but just as completely.
  1784. assignments = []
  1785. if not await spoolman_owns_assignments(db):
  1786. result = await db.execute(
  1787. select(SA)
  1788. .where(SA.printer_id == printer_id)
  1789. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1790. )
  1791. assignments = result.scalars().all()
  1792. # ``printing_now`` (top of this function) keeps a runout from
  1793. # unlinking the spool that fed the print — the next idle-time pass
  1794. # unlinks it if the user really did take it out.
  1795. stale = []
  1796. for assignment in assignments:
  1797. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1798. if assignment.ams_id == 255:
  1799. ps = printer_manager.get_status(printer_id)
  1800. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1801. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1802. current_tray = None
  1803. for vt in vt_tray_raw:
  1804. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1805. current_tray = vt
  1806. break
  1807. if not current_tray:
  1808. # vt_tray data may not have arrived yet — keep assignment
  1809. continue
  1810. else:
  1811. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1812. if not current_tray:
  1813. if printing_now:
  1814. logger.info(
  1815. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1816. assignment.spool_id,
  1817. assignment.ams_id,
  1818. assignment.tray_id,
  1819. )
  1820. continue
  1821. logger.info(
  1822. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1823. assignment.spool_id,
  1824. assignment.ams_id,
  1825. assignment.tray_id,
  1826. )
  1827. stale.append(assignment) # Slot empty
  1828. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1829. # A Bambu Lab spool is in this slot — check if it's the same spool
  1830. # that's currently assigned. If yes, keep the assignment (avoids
  1831. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1832. # the printer's filament preset on every startup).
  1833. tray_uuid = current_tray.get("tray_uuid", "")
  1834. tag_uid = current_tray.get("tag_uid", "")
  1835. spool = assignment.spool
  1836. spool_matches = False
  1837. if spool:
  1838. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1839. spool.tag_uid
  1840. and tag_uid
  1841. and tag_uid != "0000000000000000"
  1842. and spool.tag_uid.upper() == tag_uid.upper()
  1843. ):
  1844. spool_matches = True
  1845. if spool_matches:
  1846. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1847. cur_color = current_tray.get("tray_color", "")
  1848. cur_type = current_tray.get("tray_type", "")
  1849. fp_color = assignment.fingerprint_color or ""
  1850. fp_type = assignment.fingerprint_type or ""
  1851. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1852. assignment.fingerprint_color = cur_color
  1853. assignment.fingerprint_type = cur_type
  1854. logger.debug(
  1855. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1856. assignment.spool_id,
  1857. assignment.ams_id,
  1858. assignment.tray_id,
  1859. )
  1860. continue
  1861. # Different BL spool or unrecognized — unlink so auto-assign can match
  1862. logger.info(
  1863. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1864. assignment.spool_id,
  1865. assignment.ams_id,
  1866. assignment.tray_id,
  1867. tray_uuid,
  1868. )
  1869. stale.append(assignment)
  1870. else:
  1871. cur_color = current_tray.get("tray_color", "")
  1872. cur_type = current_tray.get("tray_type", "")
  1873. cur_state = current_tray.get("state")
  1874. fp_color = assignment.fingerprint_color or ""
  1875. fp_type = assignment.fingerprint_type or ""
  1876. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1877. # the slot was empty when the user pre-assigned via SpoolBuddy
  1878. # (the firmware drops ams_filament_setting on empty slots, so
  1879. # MQTT was deferred). The moment any filament gets inserted
  1880. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1881. # reconfigured spool — fire the deferred configuration.
  1882. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1883. # extruder" code) OR, on firmwares that don't use the state
  1884. # enum meaningfully, a non-empty tray_type when state is
  1885. # NOT one of the firmware's explicit empty signals (9, 10).
  1886. # state-only was wrong for firmwares that never set 11 — A1
  1887. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1888. # always report state=3 — so the replay never fired for them
  1889. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1890. # explicit "empty" signals authoritative over any stale
  1891. # tray_type that might survive the relay's auto-clearing.
  1892. #
  1893. # tray_exist_bits comes first because that guard cannot tell
  1894. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  1895. # writes state=9 when the bit is 0 and leaves it there when the
  1896. # bit returns. A non-RFID spool inserted into a pre-assigned
  1897. # slot brings no tray_type with it, so the stale 9 made this
  1898. # expression false forever and the deferred config never fired
  1899. # — the deadlock #1322 removed from the assign path, still in
  1900. # place here (#3084, #3100).
  1901. loaded = spool_present(current_tray) is True or (
  1902. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1903. )
  1904. if not fp_type.strip() and loaded and assignment.spool:
  1905. try:
  1906. from backend.app.api.routes.inventory import (
  1907. apply_spool_to_slot_via_mqtt,
  1908. )
  1909. await apply_spool_to_slot_via_mqtt(
  1910. db=db,
  1911. current_user=None,
  1912. spool=assignment.spool,
  1913. printer_id=printer_id,
  1914. ams_id=assignment.ams_id,
  1915. tray_id=assignment.tray_id,
  1916. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1917. current_tray_type=cur_type,
  1918. )
  1919. logger.info(
  1920. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1921. assignment.spool_id,
  1922. printer_id,
  1923. assignment.ams_id,
  1924. assignment.tray_id,
  1925. )
  1926. except Exception:
  1927. logger.exception(
  1928. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1929. assignment.spool_id,
  1930. printer_id,
  1931. assignment.ams_id,
  1932. assignment.tray_id,
  1933. )
  1934. assignment.fingerprint_color = cur_color
  1935. assignment.fingerprint_type = cur_type
  1936. continue
  1937. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1938. # Blank tray data mid-print is a runout, not a swap: the
  1939. # firmware clears colour and type when it unloads a spool
  1940. # it just emptied. Unlinking here would erase the record
  1941. # of which spool fed the print so far.
  1942. if printing_now and not cur_color.strip() and not cur_type.strip():
  1943. logger.info(
  1944. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  1945. "(runout?)",
  1946. assignment.spool_id,
  1947. assignment.ams_id,
  1948. assignment.tray_id,
  1949. )
  1950. continue
  1951. # Same reasoning off the print, on firmware's own say-so:
  1952. # a blank tray report from a slot whose tray_exist_bits
  1953. # bit is set describes a spool the AMS cannot identify —
  1954. # a non-RFID one, or one whose slot was reset — not a
  1955. # spool that was taken out. Deleting the assignment there
  1956. # threw away the identity the user had supplied, which is
  1957. # the only place it existed (#3100). A slot the bit calls
  1958. # empty, or one that carries no bit at all, still unlinks.
  1959. if spool_present(current_tray) is True and not cur_color.strip() and not cur_type.strip():
  1960. logger.info(
  1961. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  1962. "tray reports no filament data yet",
  1963. assignment.spool_id,
  1964. assignment.ams_id,
  1965. assignment.tray_id,
  1966. )
  1967. continue
  1968. # Fingerprint mismatch — but check if tray now matches the
  1969. # assigned spool (e.g. auto-configure changed the tray).
  1970. # Both sides are reduced to the type the slot can carry
  1971. # before comparing: the assign path writes that rather
  1972. # than the spool's raw material (#2902), so a spool whose
  1973. # material is a product line — "PLA+", "HTPLA" — reports
  1974. # back as "PLA" and would otherwise fail this check and
  1975. # be auto-unlinked from the slot it was just assigned to.
  1976. # Reducing the printer's side too keeps slots configured
  1977. # by an older Bambuddy, still reporting "PLA+", matching.
  1978. spool = assignment.spool
  1979. if spool:
  1980. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1981. # Two ways the assign path can have arrived at the
  1982. # slot's type, so both count as "we wrote this".
  1983. # The material column is one; the spool's preset is
  1984. # the other, and it outranks the material when the
  1985. # spool has one -- a spool whose material says PLA
  1986. # and whose preset is "Bambu PLA Aero" puts
  1987. # PLA-AERO in the slot (#2902). Read from the stored
  1988. # preset name rather than resolving the preset,
  1989. # because this runs on every AMS push and a cloud
  1990. # lookup here would be both slow and unavailable on
  1991. # the unauthenticated replay path.
  1992. spool_types = {printer_filament_type(spool.material).upper()}
  1993. if spool.slicer_filament_name:
  1994. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  1995. # An imported local preset stores its type outright,
  1996. # which is what the assign path used -- and the name
  1997. # above may be unset. One keyed read, and only on a
  1998. # mismatch, which is rare.
  1999. #
  2000. # slicer_filament is free text up to fifty characters,
  2001. # so the digits have to be checked against the range
  2002. # of the integer primary key they are about to be
  2003. # compared with. Postgres raises on an out-of-range
  2004. # integer rather than simply not matching, and that
  2005. # would poison this session and abandon the rest of
  2006. # the cleanup pass.
  2007. lp_ref = (spool.slicer_filament or "").strip()
  2008. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2009. from backend.app.models.local_preset import LocalPreset as _LP
  2010. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2011. if lp_type:
  2012. spool_types.add(printer_filament_type(lp_type).upper())
  2013. if (
  2014. _colors_similar(cur_color, spool_color)
  2015. and printer_filament_type(cur_type).upper() in spool_types
  2016. ):
  2017. logger.info(
  2018. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2019. assignment.spool_id,
  2020. assignment.ams_id,
  2021. assignment.tray_id,
  2022. )
  2023. assignment.fingerprint_color = cur_color
  2024. assignment.fingerprint_type = cur_type
  2025. continue
  2026. logger.info(
  2027. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2028. assignment.spool_id,
  2029. assignment.ams_id,
  2030. assignment.tray_id,
  2031. cur_color,
  2032. cur_type,
  2033. fp_color,
  2034. fp_type,
  2035. spool.rgba if spool else "?",
  2036. spool.material if spool else "?",
  2037. )
  2038. stale.append(assignment) # Spool changed
  2039. # Snapshot slots before delete — ORM attribute access after the
  2040. # commit would refresh against a deleted row.
  2041. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2042. for a in stale:
  2043. await db.delete(a)
  2044. if stale:
  2045. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2046. # Commit any changes (stale deletions and/or fingerprint updates)
  2047. await db.commit()
  2048. # Tell open browsers the assignment is gone (#2575). Only the manual
  2049. # REST assign/unassign endpoints broadcast this event; without it the
  2050. # frontend's spool-assignments cache keeps rendering the unlinked
  2051. # spool on the slot until an unrelated refetch — which reads exactly
  2052. # like "the fix didn't work" (reporter verified: a browser refresh
  2053. # after the swap showed the correct state all along).
  2054. for ams_id, tray_id in unlinked_slots:
  2055. await ws_manager.broadcast(
  2056. {
  2057. "type": "spool_assignment_changed",
  2058. "printer_id": printer_id,
  2059. "ams_id": ams_id,
  2060. "tray_id": tray_id,
  2061. }
  2062. )
  2063. except Exception as e:
  2064. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2065. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2066. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2067. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2068. # "no existing assignment" for the same (printer, ams, tray) and race to
  2069. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2070. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2071. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2072. try:
  2073. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2074. from backend.app.api.routes.settings import get_setting
  2075. from backend.app.models.spool import Spool
  2076. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2077. from backend.app.services.spool_tag_matcher import (
  2078. auto_assign_spool,
  2079. create_spool_from_tray,
  2080. find_matching_untagged_spool,
  2081. get_spool_by_tag,
  2082. is_bambu_tag,
  2083. is_valid_tag,
  2084. link_tag_to_inventory_spool,
  2085. )
  2086. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2087. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2088. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2089. if not _spoolman_on or _spoolman_on.lower() != "true":
  2090. for ams_unit in ams_data:
  2091. if not isinstance(ams_unit, dict):
  2092. continue
  2093. ams_id = int(ams_unit.get("id", 0))
  2094. for tray in ams_unit.get("tray", []):
  2095. if not isinstance(tray, dict):
  2096. continue
  2097. tray_id = int(tray.get("id", 0))
  2098. tag_uid = tray.get("tag_uid", "")
  2099. tray_uuid = tray.get("tray_uuid", "")
  2100. tray_info_idx = tray.get("tray_info_idx", "")
  2101. if not tray.get("tray_type"):
  2102. # Slot reported empty — drop any cached unknown-tag
  2103. # broadcast so reinserting the same spool re-prompts.
  2104. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2105. continue # Empty slot
  2106. # Check if assignment already exists for this slot
  2107. existing = await db.execute(
  2108. select(SA)
  2109. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2110. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2111. )
  2112. existing_assignment = existing.scalar_one_or_none()
  2113. if existing_assignment:
  2114. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2115. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2116. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2117. # Skip during active prints: the usage tracker handles deduction
  2118. # precisely via 3MF data on print completion. Without this guard the
  2119. # AMS remain% SET and the usage tracker ADD both fire from the same
  2120. # MQTT message, doubling the deduction (#880).
  2121. if _print_active:
  2122. continue
  2123. remain_raw = tray.get("remain")
  2124. if (
  2125. remain_raw is not None
  2126. and existing_assignment.spool
  2127. and not existing_assignment.spool.weight_locked
  2128. ):
  2129. try:
  2130. remain_val = int(remain_raw)
  2131. except (TypeError, ValueError):
  2132. remain_val = -1
  2133. if 1 <= remain_val <= 100:
  2134. lw = existing_assignment.spool.label_weight or 1000
  2135. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2136. current_used = existing_assignment.spool.weight_used or 0
  2137. if new_used > current_used + 1:
  2138. logger.info(
  2139. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2140. existing_assignment.spool_id,
  2141. current_used,
  2142. new_used,
  2143. remain_val,
  2144. )
  2145. existing_assignment.spool.weight_used = new_used
  2146. await db.commit()
  2147. # Re-apply stored K-profile when the live tray's
  2148. # cali_idx drifted from the spool's stored profile.
  2149. # This catches "reset slot → re-read" and any other
  2150. # path where the firmware loses the user's K-profile
  2151. # selection while the SpoolAssignment row persists.
  2152. # Per the maintainer's rule: any time a spool tag is
  2153. # identified and matches inventory, the slot must be
  2154. # configured with the spool's stored settings. Without
  2155. # this block the existing-assignment branch only ran
  2156. # weight-sync and let the firmware-default cali_idx win.
  2157. try:
  2158. spool = existing_assignment.spool
  2159. if (
  2160. spool is not None
  2161. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2162. and spool.k_profiles
  2163. ):
  2164. state = printer_manager.get_status(printer_id)
  2165. slot_nozzle = resolve_slot_nozzle(
  2166. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2167. )
  2168. nozzle_diameter = slot_nozzle.diameter
  2169. slot_extruder = slot_nozzle.extruder
  2170. # Prefer exact extruder match, fall back to
  2171. # extruder-agnostic kp for the same printer +
  2172. # nozzle. Avoids hard-skipping when the AMS is
  2173. # mapped differently than at calibration time.
  2174. matching_kp = None
  2175. fallback_kp = None
  2176. for kp in spool.k_profiles:
  2177. if (
  2178. kp.printer_id != printer_id
  2179. or kp.nozzle_diameter != nozzle_diameter
  2180. or kp.cali_idx is None
  2181. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2182. ):
  2183. continue
  2184. if (
  2185. slot_extruder is not None
  2186. and kp.extruder is not None
  2187. and kp.extruder == slot_extruder
  2188. ):
  2189. matching_kp = kp
  2190. break
  2191. if fallback_kp is None:
  2192. fallback_kp = kp
  2193. chosen_kp = matching_kp or fallback_kp
  2194. if chosen_kp is not None:
  2195. live_cali_idx = tray.get("cali_idx")
  2196. # Only fire MQTT when the printer's live
  2197. # cali_idx differs from the stored value.
  2198. # Avoids spamming the broker on every
  2199. # MQTT push during steady-state operation.
  2200. if live_cali_idx != chosen_kp.cali_idx:
  2201. client = printer_manager.get_client(printer_id)
  2202. if client:
  2203. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2204. client.extrusion_cali_sel(
  2205. ams_id=ams_id,
  2206. tray_id=tray_id,
  2207. cali_idx=chosen_kp.cali_idx,
  2208. filament_id=cali_filament_id,
  2209. nozzle_diameter=nozzle_diameter,
  2210. )
  2211. logger.info(
  2212. "Re-applied K-profile cali_idx=%d for spool %d "
  2213. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2214. chosen_kp.cali_idx,
  2215. spool.id,
  2216. printer_id,
  2217. ams_id,
  2218. tray_id,
  2219. live_cali_idx,
  2220. )
  2221. except Exception:
  2222. logger.exception(
  2223. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2224. printer_id,
  2225. ams_id,
  2226. tray_id,
  2227. )
  2228. continue
  2229. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2230. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2231. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2232. if not spool:
  2233. # Try matching an untagged inventory spool (same material/color)
  2234. spool = await find_matching_untagged_spool(db, tray)
  2235. if spool:
  2236. await link_tag_to_inventory_spool(db, spool, tray)
  2237. elif _auto_add_unknown:
  2238. spool = await create_spool_from_tray(db, tray)
  2239. else:
  2240. # Auto-add disabled: surface the slot so the
  2241. # user can add it manually via the UI.
  2242. await _broadcast_unknown_tag(
  2243. printer_id=printer_id,
  2244. ams_id=ams_id,
  2245. tray_id=tray_id,
  2246. tag_uid=tag_uid,
  2247. tray_uuid=tray_uuid,
  2248. tray_type=tray.get("tray_type"),
  2249. tray_color=tray.get("tray_color"),
  2250. tray_sub_brands=tray.get("tray_sub_brands"),
  2251. tray_count=len(ams_unit.get("tray", [])),
  2252. )
  2253. continue
  2254. # Slot matched (existing tag, untagged inventory
  2255. # match, or freshly auto-created spool) — drop any
  2256. # stale dedup so a future tag swap re-prompts.
  2257. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2258. await auto_assign_spool(
  2259. printer_id,
  2260. ams_id,
  2261. tray_id,
  2262. spool,
  2263. printer_manager,
  2264. db,
  2265. tray_info_idx=tray_info_idx,
  2266. )
  2267. await db.commit()
  2268. await ws_manager.broadcast(
  2269. {
  2270. "type": "spool_auto_assigned",
  2271. "printer_id": printer_id,
  2272. "ams_id": ams_id,
  2273. "tray_id": tray_id,
  2274. "spool_id": spool.id,
  2275. }
  2276. )
  2277. logger.info(
  2278. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2279. spool.id,
  2280. printer_id,
  2281. ams_id,
  2282. tray_id,
  2283. )
  2284. elif is_valid_tag(tag_uid, tray_uuid):
  2285. # Non-BL spool with some tag — let user choose
  2286. await _broadcast_unknown_tag(
  2287. printer_id=printer_id,
  2288. ams_id=ams_id,
  2289. tray_id=tray_id,
  2290. tag_uid=tag_uid,
  2291. tray_uuid=tray_uuid,
  2292. tray_type=tray.get("tray_type"),
  2293. tray_color=tray.get("tray_color"),
  2294. tray_sub_brands=tray.get("tray_sub_brands"),
  2295. tray_count=len(ams_unit.get("tray", [])),
  2296. )
  2297. # No-tag slots (generic non-RFID filament) are left alone:
  2298. # nothing to identify, prompting "+ Add" would just create
  2299. # ghost spools with empty tags on every confirm.
  2300. except Exception as e:
  2301. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2302. try:
  2303. async with async_session() as db:
  2304. from backend.app.api.routes.settings import get_setting
  2305. from backend.app.models.printer import Printer
  2306. # Check if Spoolman is enabled
  2307. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2308. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2309. return
  2310. # Check sync mode
  2311. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2312. if sync_mode and sync_mode != "auto":
  2313. return # Only sync on auto mode
  2314. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2315. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2316. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2317. # always owned by per-print tracking, never by AMS auto-sync. The
  2318. # setting is still read by the settings UI for backwards compat but
  2319. # has no effect on the sync path here.
  2320. # Get Spoolman URL
  2321. spoolman_url = await get_setting(db, "spoolman_url")
  2322. if not spoolman_url:
  2323. return
  2324. # Get or create Spoolman client
  2325. client = await get_spoolman_client()
  2326. if not client:
  2327. try:
  2328. client = await init_spoolman_client(spoolman_url)
  2329. except ValueError as exc:
  2330. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2331. return
  2332. # Check if Spoolman is reachable
  2333. if not await client.health_check():
  2334. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2335. return
  2336. # Get printer name for location
  2337. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2338. printer = result.scalar_one_or_none()
  2339. printer_name = printer.name if printer else f"Printer {printer_id}"
  2340. # OPTIMIZATION: Fetch all spools once before processing trays
  2341. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2342. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2343. try:
  2344. cached_spools = await client.get_spools()
  2345. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2346. except Exception as e:
  2347. logger.error(
  2348. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2349. printer_id,
  2350. e,
  2351. )
  2352. return
  2353. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2354. from sqlalchemy.orm import selectinload
  2355. from backend.app.models.spool_assignment import SpoolAssignment
  2356. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2357. from backend.app.services.ams_slot_presence import spool_present
  2358. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2359. # Built-in remaining weight, used by sync_ams_tray only when the
  2360. # firmware reports an unusable remain%/tray_weight for a slot.
  2361. #
  2362. # Left empty since #2812. This block runs in Spoolman mode only,
  2363. # and until then the built-in table was emptied on the switch, so
  2364. # there was never anything here to read and the fallback was inert.
  2365. # Preserving those rows makes it live again, and it is keyed by slot
  2366. # rather than by spool: after a mode switch the tray may well hold
  2367. # different filament, and ``create_spool`` writes ``remaining_weight``
  2368. # unconditionally, so a stale figure would be seeded into a brand new
  2369. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2370. # intent survives for whoever revisits the cross-mode fallback.
  2371. inventory_weights: dict[tuple[int, int], float] = {}
  2372. if not await spoolman_owns_assignments(db):
  2373. try:
  2374. assign_result = await db.execute(
  2375. select(SpoolAssignment)
  2376. .options(selectinload(SpoolAssignment.spool))
  2377. .where(SpoolAssignment.printer_id == printer_id)
  2378. )
  2379. for assignment in assign_result.scalars().all():
  2380. spool = assignment.spool
  2381. if spool and spool.label_weight > 0:
  2382. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2383. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2384. except Exception as e:
  2385. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2386. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2387. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2388. try:
  2389. slot_result = await db.execute(
  2390. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2391. )
  2392. for slot in slot_result.scalars().all():
  2393. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2394. except Exception as e:
  2395. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2396. # Sync each AMS tray and collect slot changes for DB persistence
  2397. synced = 0
  2398. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2399. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2400. for ams_unit in ams_data:
  2401. if not isinstance(ams_unit, dict):
  2402. continue
  2403. ams_id = int(ams_unit.get("id", 0))
  2404. trays = ams_unit.get("tray", [])
  2405. for tray_data in trays:
  2406. if not isinstance(tray_data, dict):
  2407. continue
  2408. tray_id_raw = int(tray_data.get("id", 0))
  2409. tray = client.parse_ams_tray(ams_id, tray_data)
  2410. if not tray:
  2411. # Empty tray slot — record for local assignment cleanup
  2412. # and drop any cached unknown-tag broadcast so a
  2413. # reinserted spool re-prompts.
  2414. #
  2415. # Not during a running print: a slot that empties there
  2416. # is a filament runout, and the spool is still in the
  2417. # AMS. `spoolman_slot_assignments` is how a tag-less
  2418. # spool assigned through the Bambuddy UI is resolved at
  2419. # completion (#1459), so deleting the row mid-print
  2420. # loses the runout segment's usage — the same failure
  2421. # the internal inventory's auto-unlink had.
  2422. #
  2423. # Nor when firmware's presence bit says the slot is
  2424. # occupied. parse_ams_tray calls a tray with no type or
  2425. # no colour empty, and a spool the AMS cannot read has
  2426. # neither until something configures it — so a tag-less
  2427. # spool assigned through the UI had its row deleted by
  2428. # the first idle push after it was inserted. Same
  2429. # deletion as the internal inventory's in #3100, same
  2430. # answer, so the two modes stay in step.
  2431. if not printing_now and spool_present(tray_data) is not True:
  2432. empty_slots.append((ams_id, tray_id_raw))
  2433. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2434. continue
  2435. spool_tag = (
  2436. tray.tray_uuid
  2437. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2438. else tray.tag_uid
  2439. )
  2440. # Provide the hint only when no RFID is available
  2441. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2442. try:
  2443. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2444. result = await client.sync_ams_tray(
  2445. tray,
  2446. printer_name,
  2447. # Per-print tracking is the only weight writer (#1119).
  2448. # AMS auto-sync still maintains spool metadata / slot
  2449. # assignments but no longer touches remaining_weight.
  2450. disable_weight_sync=True,
  2451. cached_spools=cached_spools,
  2452. inventory_remaining=inv_remaining,
  2453. spoolman_spool_id_hint=hint,
  2454. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2455. )
  2456. if result is None and spool_tag and not auto_add_unknown_rfid:
  2457. # Spoolman skipped auto-create per user setting — surface
  2458. # the slot so the UI can offer "+ Add to inventory".
  2459. await _broadcast_unknown_tag(
  2460. printer_id=printer_id,
  2461. ams_id=ams_id,
  2462. tray_id=tray.tray_id,
  2463. tag_uid=tray.tag_uid or "",
  2464. tray_uuid=tray.tray_uuid or "",
  2465. tray_type=tray.tray_type,
  2466. tray_color=tray.tray_color,
  2467. tray_sub_brands=tray.tray_sub_brands,
  2468. tray_count=len(trays),
  2469. )
  2470. elif result:
  2471. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2472. if result:
  2473. synced += 1
  2474. if result.get("id"):
  2475. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2476. # If a new spool was created, add it to the cache
  2477. # so subsequent trays can find it if they reference the same tag
  2478. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2479. if not spool_exists:
  2480. cached_spools.append(result)
  2481. logger.debug(
  2482. "[Printer %s] Added newly created spool %s to cache",
  2483. printer_id,
  2484. result["id"],
  2485. )
  2486. # Reconcile slot_preset_mappings (the same row internal
  2487. # mode keeps in sync via inventory + spool_tag_matcher).
  2488. # Without this the slot card surfaces the previous spool's
  2489. # preset name — same bug shape, different inventory mode.
  2490. from backend.app.services.slot_preset_writer import (
  2491. upsert_slot_preset_for_spoolman_spool,
  2492. )
  2493. await upsert_slot_preset_for_spoolman_spool(
  2494. db=db,
  2495. spoolman_spool=result,
  2496. tray_info_idx=tray.tray_info_idx or "",
  2497. tray_sub_brands=tray.tray_sub_brands or "",
  2498. tray_type=tray.tray_type or "",
  2499. printer_id=printer_id,
  2500. ams_id=ams_id,
  2501. tray_id=tray.tray_id,
  2502. )
  2503. except Exception as e:
  2504. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2505. if synced > 0:
  2506. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2507. # Persist slot assignment changes to the local table
  2508. if slot_changes or empty_slots:
  2509. try:
  2510. for ams_id, tray_id, spool_id in slot_changes:
  2511. await db.execute(
  2512. text(
  2513. "INSERT INTO spoolman_slot_assignments"
  2514. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2515. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2516. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2517. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2518. ),
  2519. {
  2520. "printer_id": printer_id,
  2521. "ams_id": ams_id,
  2522. "tray_id": tray_id,
  2523. "spool_id": spool_id,
  2524. },
  2525. )
  2526. for ams_id, tray_id in empty_slots:
  2527. await db.execute(
  2528. delete(SpoolmanSlotAssignment).where(
  2529. SpoolmanSlotAssignment.printer_id == printer_id,
  2530. SpoolmanSlotAssignment.ams_id == ams_id,
  2531. SpoolmanSlotAssignment.tray_id == tray_id,
  2532. )
  2533. )
  2534. await db.commit()
  2535. except Exception as e:
  2536. await db.rollback()
  2537. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2538. else:
  2539. # Tell open browsers the slot changed. This loop rewrites
  2540. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2541. # above, and the AMS slot card reads that row ahead of the
  2542. # live tray_info_idx -- so with no event the card keeps
  2543. # showing the previous spool's preset name. Internal mode
  2544. # raises spool_auto_assigned for the same reason; this loop
  2545. # broadcast nothing at all, which made Spoolman mode the
  2546. # worse half of the same bug. On the else branch so a
  2547. # failed commit stays silent and a broadcast failure cannot
  2548. # roll back rows that are already committed.
  2549. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2550. await ws_manager.broadcast(
  2551. {
  2552. "type": "spool_assignment_changed",
  2553. "printer_id": printer_id,
  2554. "ams_id": ams_id,
  2555. "tray_id": tray_id,
  2556. }
  2557. )
  2558. except Exception as e:
  2559. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2560. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2561. """Capture a camera snapshot for notification image attachment.
  2562. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2563. Uses: external camera > buffered frame > fresh capture.
  2564. """
  2565. if not printer:
  2566. return None
  2567. try:
  2568. from backend.app.api.routes.settings import get_setting
  2569. async with async_session() as db:
  2570. capture_enabled = await get_setting(db, "capture_finish_photo")
  2571. if capture_enabled is not None and capture_enabled.lower() != "true":
  2572. return None
  2573. # Try external camera first
  2574. if printer.external_camera_enabled and printer.external_camera_url:
  2575. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2576. from backend.app.api.routes.camera import live_frame_for_capture
  2577. from backend.app.services.external_camera import capture_frame
  2578. # An external camera allows one reader, so capturing while a viewer
  2579. # is attached fails (#2707). A None here falls through to the paths
  2580. # below exactly as a failed capture did.
  2581. defer, buffered = live_frame_for_capture(printer_id)
  2582. if defer:
  2583. frame_data = buffered
  2584. else:
  2585. frame_data = await capture_frame(
  2586. printer.external_camera_url,
  2587. printer.external_camera_type or "mjpeg",
  2588. snapshot_url=printer.external_camera_snapshot_url,
  2589. )
  2590. if frame_data and len(frame_data) <= 2_500_000:
  2591. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2592. return _apply_camera_rotation(frame_data, printer, logger)
  2593. # Try buffered frame from active stream
  2594. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2595. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2596. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2597. buffered_frame = get_buffered_frame(printer_id)
  2598. if (active_for_printer or active_chamber) and buffered_frame:
  2599. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2600. if len(buffered_frame) <= 2_500_000:
  2601. return _apply_camera_rotation(buffered_frame, printer, logger)
  2602. # Fresh capture from printer camera
  2603. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2604. from backend.app.services.camera import capture_camera_frame_bytes
  2605. frame_data = await capture_camera_frame_bytes(
  2606. printer.ip_address, printer.access_code, printer.model, timeout=15
  2607. )
  2608. if frame_data and len(frame_data) <= 2_500_000:
  2609. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2610. return _apply_camera_rotation(frame_data, printer, logger)
  2611. except Exception as e:
  2612. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2613. return None
  2614. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2615. """#1867: bank a recent in-print camera frame for the finish photo.
  2616. Called on every layer change and (#2547) on every print-progress advance.
  2617. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2618. path has a pre-End-G-code image for prints that end with a plate swap.
  2619. Both drivers are print telemetry that stops the instant printing ends: no
  2620. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2621. plate swap) executes. So the last banked frame is always the finished print,
  2622. never the swapped plate — that property is what the #1867 path relies on and
  2623. it must survive any change to the throttle below.
  2624. Layer changes alone were not enough: they stop when the *final* layer
  2625. begins, which on a three-minute last layer left the bank stale by the whole
  2626. length of that layer (#2547). Progress keeps ticking through it.
  2627. Best-effort: any failure just leaves the previous banked frame.
  2628. """
  2629. logger = logging.getLogger(__name__)
  2630. client = printer_manager.get_client(printer_id)
  2631. state = client.state if client else None
  2632. if not state or state.state != "RUNNING":
  2633. return
  2634. # Only during actual extrusion — firmware ticks layer_num during the
  2635. # pre-print calibration sequence, whose sub-stages are non-zero.
  2636. if state.mc_print_sub_stage not in (None, 0):
  2637. return
  2638. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2639. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2640. # now that progress advances also drive banking, that exemption would fire a
  2641. # camera grab on every percent tick of the last layer. Bambu printers accept
  2642. # one RTSP client at a time, so each grab contends with the live view.
  2643. now = time.monotonic()
  2644. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2645. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2646. return
  2647. total = state.total_layers or 0
  2648. try:
  2649. async with async_session() as db:
  2650. from backend.app.models.printer import Printer
  2651. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2652. printer = result.scalar_one_or_none()
  2653. if not printer:
  2654. return
  2655. # Reuses the notification snapshot path, which honours the
  2656. # `capture_finish_photo` setting (returns None when disabled) so we
  2657. # don't bank frames the user never asked for.
  2658. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2659. if frame:
  2660. _inprint_frame_bank[printer_id] = frame
  2661. _inprint_frame_bank_ts[printer_id] = now
  2662. logger.debug(
  2663. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2664. printer_id,
  2665. layer_num,
  2666. total,
  2667. len(frame),
  2668. )
  2669. except Exception as e:
  2670. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2671. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2672. """Apply camera rotation to snapshot image if configured."""
  2673. from backend.app.services.camera import apply_camera_rotation
  2674. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2675. async def _send_print_start_notification(
  2676. printer_id: int,
  2677. data: dict,
  2678. archive_data: dict | None = None,
  2679. logger=None,
  2680. ):
  2681. """Helper to send print start notification with optional archive data."""
  2682. if logger is None:
  2683. logger = logging.getLogger(__name__)
  2684. try:
  2685. async with async_session() as db:
  2686. from backend.app.models.printer import Printer
  2687. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2688. printer = result.scalar_one_or_none()
  2689. printer_name = printer.name if printer else f"Printer {printer_id}"
  2690. # Capture camera snapshot for notification image attachment
  2691. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2692. if image_data:
  2693. if archive_data is None:
  2694. archive_data = {}
  2695. archive_data["image_data"] = image_data
  2696. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  2697. # Send user-specific email notification for print start
  2698. if archive_data and archive_data.get("created_by_id"):
  2699. await notification_service.send_user_print_email(
  2700. event_type="user_print_start",
  2701. created_by_id=archive_data["created_by_id"],
  2702. printer_name=printer_name,
  2703. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  2704. db=db,
  2705. )
  2706. except Exception as e:
  2707. logger.warning("Notification on_print_start failed: %s", e)
  2708. async def _dispatch_user_print_email(
  2709. status: str,
  2710. created_by_id: int | None,
  2711. printer_name: str,
  2712. filename: str,
  2713. db,
  2714. ) -> None:
  2715. """Send a user-specific print-completion email based on print status.
  2716. Maps the normalised print status to the correct event type and delegates
  2717. to :meth:`NotificationService.send_user_print_email`. A single helper
  2718. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  2719. "stopped"`` dispatch block at every call site.
  2720. Does nothing if *created_by_id* is ``None``.
  2721. """
  2722. if created_by_id is None:
  2723. return
  2724. if status == "completed":
  2725. event_type = "user_print_complete"
  2726. elif status == "failed":
  2727. event_type = "user_print_failed"
  2728. elif status in ("stopped", "aborted", "cancelled"):
  2729. event_type = "user_print_stopped"
  2730. else:
  2731. return
  2732. await notification_service.send_user_print_email(
  2733. event_type=event_type,
  2734. created_by_id=created_by_id,
  2735. printer_name=printer_name,
  2736. filename=filename,
  2737. db=db,
  2738. )
  2739. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  2740. """Extract printable objects from an archive's 3MF file and store in printer state."""
  2741. try:
  2742. from backend.app.services.archive import extract_printable_objects_from_archive
  2743. client = printer_manager.get_client(printer_id)
  2744. if not client:
  2745. return
  2746. # Extract with positions for UI overlay, scoped to the plate that
  2747. # is printing — resolve_plate_id is the same resolver /cover uses,
  2748. # so the object list can't disagree with the thumbnail it is drawn
  2749. # over (#2522).
  2750. printable_objects, bbox_all = extract_printable_objects_from_archive(
  2751. app_settings.base_dir / archive.file_path,
  2752. plate_number=resolve_plate_id(client.state),
  2753. )
  2754. if printable_objects:
  2755. client.state.printable_objects = printable_objects
  2756. client.state.printable_objects_bbox_all = bbox_all
  2757. client.state.skipped_objects = []
  2758. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  2759. except Exception as e:
  2760. logger.debug("Failed to extract printable objects from archive: %s", e)
  2761. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  2762. """Put the skip-objects list back after a restart mid-print.
  2763. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  2764. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  2765. which the #1304 guard suppresses on the first RUNNING push after startup.
  2766. Everything else this hook restores (the archive, the usage-tracking session,
  2767. the timelapse baseline) was already handled; the object list was not, so a
  2768. restart mid-print took skip-objects away for the rest of that print.
  2769. Nothing recovered it either: the printer card gates its Skip button on the
  2770. object count, and the one endpoint that can rebuild the list is reachable
  2771. only from the modal that button opens.
  2772. Anchored on ``subtask_id``, which the firmware mints per print, so a
  2773. leftover ``status="printing"`` row from a completion we never saw cannot
  2774. hand this print someone else's objects. Without one, nothing is loaded
  2775. rather than guessed — the reload path on ``GET /print/objects`` covers that
  2776. case on demand.
  2777. """
  2778. client = printer_manager.get_client(printer_id)
  2779. if client is None or client.state.printable_objects:
  2780. return
  2781. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  2782. if subtask_id in ("", "0"):
  2783. return
  2784. from backend.app.models.archive import PrintArchive
  2785. archive = await db.scalar(
  2786. select(PrintArchive)
  2787. .where(
  2788. PrintArchive.printer_id == printer_id,
  2789. PrintArchive.status == "printing",
  2790. PrintArchive.subtask_id == subtask_id,
  2791. )
  2792. .order_by(PrintArchive.created_at.desc())
  2793. .limit(1)
  2794. )
  2795. if archive is not None:
  2796. _load_objects_from_archive(archive, printer_id, logger)
  2797. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  2798. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  2799. # past it; the second covers a handshake that failed again on the way back and
  2800. # armed a fresh one. Module-level so tests can shrink them.
  2801. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  2802. # Retry ladder for the other temporary give-up: the file service answered and
  2803. # the transfer still did not finish, which at print start is usually the printer
  2804. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  2805. # to expire here, so the first attempt comes early -- #3063's reporter had the
  2806. # same 19MB file complete 48 seconds after the download budget ran out. The later
  2807. # two cover a printer that stays busy well into the print.
  2808. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  2809. # printer_id -> the in-flight retry task, so print completion can cancel it.
  2810. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  2811. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  2812. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  2813. # by view, so two views race), the cool-off retry task, and print completion.
  2814. # Without this they each read file_path == "" and each run a full copy, so the row
  2815. # ends up pointing at one timestamped directory while the others sit orphaned.
  2816. #
  2817. # Keyed by printer rather than archive because a printer runs one print at a time,
  2818. # which makes the two equally strong here — and it bounds the dict by printer
  2819. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  2820. # done safely: `Lock.locked()` reads False between release and the queued waiter
  2821. # resuming, so "no waiters" is not a question this API can answer.
  2822. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  2823. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2824. """Fill in a no-3MF archive from a 3MF that turned up later.
  2825. Returns True when the row was upgraded. Safe to call speculatively: it
  2826. verifies the archive still exists, is still a fallback, and that the file
  2827. is a readable 3MF before touching anything.
  2828. Serialised per printer — see ``_fallback_recovery_locks``.
  2829. """
  2830. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  2831. async with lock:
  2832. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  2833. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2834. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  2835. import zipfile
  2836. from backend.app.models.archive import PrintArchive
  2837. from backend.app.services.archive import ArchiveService
  2838. logger = logging.getLogger(__name__)
  2839. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  2840. return False
  2841. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  2842. # A truncated or half-written download is worse than no download: it
  2843. # would replace an honest empty archive with wrong metadata.
  2844. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  2845. return False
  2846. async with async_session() as db:
  2847. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2848. if archive is None or archive.deleted_at is not None:
  2849. return False
  2850. if archive.file_path:
  2851. # Already recovered, or never was a fallback. Either way there is a
  2852. # real 3MF attached and overwriting it is not this function's job.
  2853. return False
  2854. print_data = (archive.extra_data or {}).get("_print_data") or {}
  2855. service = ArchiveService(db)
  2856. recovered = await service.archive_print(
  2857. printer_id=printer_id,
  2858. source_file=source_3mf,
  2859. print_data={**print_data, "status": archive.status or "printing"},
  2860. subtask_id=archive.subtask_id,
  2861. update_archive_id=archive.id,
  2862. )
  2863. if recovered is None:
  2864. return False
  2865. logger.info(
  2866. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  2867. archive_id,
  2868. source_3mf,
  2869. recovered.file_size,
  2870. )
  2871. # `archive_updated`, not `archive_created` — the row was already on the
  2872. # Archives page as an empty card and is now filled in, not new.
  2873. await ws_manager.send_archive_updated(
  2874. {
  2875. "id": recovered.id,
  2876. "printer_id": recovered.printer_id,
  2877. "filename": recovered.filename,
  2878. "print_name": recovered.print_name,
  2879. "status": recovered.status,
  2880. }
  2881. )
  2882. return True
  2883. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  2884. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  2885. Called from the paths that pull a 3MF for a print that is already under way
  2886. — chiefly the cover endpoint, which downloads the very file the archive flow
  2887. could not get and, before #2957, used it for a thumbnail and nothing else.
  2888. The bytes are already local, so this costs a parse and a row update.
  2889. No-op when the running print has a real archive, which is the common case.
  2890. """
  2891. from backend.app.models.archive import PrintArchive
  2892. logger = logging.getLogger(__name__)
  2893. # `_active_prints` is keyed on the raw names seen at print start — the
  2894. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  2895. # Callers here arrive with whichever variant their own path produced, so
  2896. # match on the same normalization the download cache uses rather than on an
  2897. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  2898. # endpoint find an archive registered under "Desktop_Goose".
  2899. wanted = normalize_3mf_name(name)
  2900. archive_id = None
  2901. for (key_printer_id, key_name), value in list(_active_prints.items()):
  2902. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  2903. archive_id = value
  2904. break
  2905. if archive_id is None:
  2906. return False
  2907. async with async_session() as db:
  2908. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2909. # Cheap pre-check so the common case (a normal archive) does no work.
  2910. if archive is None or archive.file_path or archive.deleted_at is not None:
  2911. return False
  2912. try:
  2913. return await _recover_fallback_archive(archive_id, path, printer_id)
  2914. except Exception as e:
  2915. # Recovery is opportunistic. A failure here must never take down the
  2916. # caller, which is usually just trying to render a thumbnail.
  2917. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  2918. return False
  2919. def _schedule_fallback_3mf_retry(
  2920. printer_id: int,
  2921. archive_id: int,
  2922. filenames: list[str],
  2923. delays: tuple[float, ...] | None = None,
  2924. reason: str = REASON_FTPS_COOLOFF,
  2925. ) -> None:
  2926. """Re-attempt the 3MF download after a temporary give-up.
  2927. ``reason`` says which give-up this is, and picks the default ladder: an
  2928. FTPS cool-off has to be waited out, while a transfer that timed out under
  2929. contention is worth asking about again straight away (#3063). It is only
  2930. read for the ladder and the log line -- the retry itself is identical, since
  2931. in both cases the file is on the printer and the last attempt at it failed
  2932. for a reason that does not last.
  2933. """
  2934. logger = logging.getLogger(__name__)
  2935. if delays is None:
  2936. delays = (
  2937. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  2938. if reason == REASON_FTP_TRANSFER_FAILED
  2939. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  2940. )
  2941. async def _retry() -> None:
  2942. from backend.app.models.archive import PrintArchive
  2943. from backend.app.models.printer import Printer
  2944. for delay in delays:
  2945. await asyncio.sleep(delay)
  2946. async with async_session() as db:
  2947. archive = (
  2948. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2949. ).scalar_one_or_none()
  2950. if archive is None or archive.deleted_at is not None or archive.file_path:
  2951. return
  2952. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  2953. if printer is None:
  2954. return
  2955. # Read the fields while the session is open rather than touching
  2956. # a detached instance minutes later, mid-download.
  2957. printer_ip = printer.ip_address
  2958. printer_code = printer.access_code
  2959. printer_model = printer.model
  2960. # Someone else may have fetched it in the meantime — the cover
  2961. # endpoint routinely does, and its copy is the same bytes.
  2962. for name in filenames:
  2963. cached = get_cached_3mf(printer_id, name)
  2964. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  2965. return
  2966. if ftps_handshake_blocked(printer_ip):
  2967. logger.info(
  2968. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  2969. printer_id,
  2970. archive_id,
  2971. )
  2972. continue
  2973. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  2974. for candidate in filenames:
  2975. # Bare name only. These come from the print-start flow, which
  2976. # already strips the path, but the local temp write must not
  2977. # depend on that holding for every future caller — a name that
  2978. # is absolute or contains ".." would otherwise escape the data
  2979. # volume via the `/` operator.
  2980. name = Path(candidate).name
  2981. if not name or name in (".", ".."):
  2982. continue
  2983. if not name.endswith(".3mf"):
  2984. name = f"{name}.3mf"
  2985. temp_path = app_settings.archive_dir / "temp" / name
  2986. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2987. try:
  2988. hit = await download_file_try_paths_async(
  2989. printer_ip,
  2990. printer_code,
  2991. ftp_probe_paths(name),
  2992. temp_path,
  2993. socket_timeout=ftp_timeout,
  2994. printer_model=printer_model,
  2995. )
  2996. except Exception as e:
  2997. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  2998. continue
  2999. if not hit:
  3000. continue
  3001. cache_3mf_download(printer_id, name, temp_path)
  3002. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3003. return
  3004. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3005. async def _guarded() -> None:
  3006. try:
  3007. await _retry()
  3008. except asyncio.CancelledError:
  3009. raise
  3010. except Exception as e:
  3011. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3012. finally:
  3013. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3014. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3015. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3016. if existing and not existing.done():
  3017. existing.cancel()
  3018. task = asyncio.create_task(_guarded())
  3019. _fallback_3mf_retry_tasks[printer_id] = task
  3020. logger.info(
  3021. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3022. archive_id,
  3023. reason,
  3024. printer_id,
  3025. ", ".join(f"{d:g}s" for d in delays),
  3026. )
  3027. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3028. """Whether an archive created here should ask for the print's outcome (#1898).
  3029. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3030. branches below: a queued job already has its archive and takes the
  3031. expected-print branch, where the queue item's own ``confirm_outcome``
  3032. decides. The queue is still consulted, because a restart mid-print empties
  3033. ``_expected_prints`` — without the check the setting could override a queue
  3034. item that deliberately has the flag off. Any failure answers "don't ask":
  3035. an unwanted prompt is worse than a missing one, and this must never be the
  3036. reason a print goes unarchived.
  3037. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3038. leaves one behind when a completion cannot be matched to it
  3039. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3040. only takes it back once the printer has sat connected and terminal for
  3041. minutes. Until then every screen-started print on that printer would
  3042. silently lose its prompt, so the row is held against ``observed_name`` by
  3043. the same comparison a completion uses: a positive disagreement means the row
  3044. is about some other run and this print is external after all.
  3045. """
  3046. logger = logging.getLogger(__name__)
  3047. try:
  3048. from backend.app.api.routes.settings import get_setting, setting_is_true
  3049. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3050. return False
  3051. from backend.app.models.print_queue import PrintQueueItem
  3052. dispatched_here = await db.scalar(
  3053. select(PrintQueueItem)
  3054. .where(
  3055. PrintQueueItem.printer_id == printer_id,
  3056. PrintQueueItem.status == "printing",
  3057. )
  3058. .limit(1)
  3059. )
  3060. if dispatched_here is None:
  3061. return True
  3062. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3063. observed = (observed_name or "").strip()
  3064. if not expected or not observed or _subtask_names_match(expected, observed):
  3065. logger.info(
  3066. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3067. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3068. printer_id,
  3069. dispatched_here.id,
  3070. )
  3071. return False
  3072. logger.info(
  3073. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3074. "%r; treating this as an externally started print.",
  3075. dispatched_here.id,
  3076. printer_id,
  3077. expected,
  3078. observed,
  3079. )
  3080. return True
  3081. except Exception as e:
  3082. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3083. # A failed statement deactivates the transaction, so without this the
  3084. # caller's own add()/commit() would raise PendingRollbackError and the
  3085. # print would go unarchived over a question that answers "no".
  3086. try:
  3087. await db.rollback()
  3088. except Exception:
  3089. pass
  3090. return False
  3091. async def dispatch_outcome_confirmation(
  3092. db,
  3093. printer_id: int,
  3094. printer_name: str,
  3095. data: dict,
  3096. archive_id: int,
  3097. archive_data: dict | None = None,
  3098. ) -> bool:
  3099. """Emit the post-print outcome prompt for a completed archive (#1898).
  3100. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3101. queue item, or from ``confirm_outcome_external_prints`` for a print
  3102. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3103. question still open. Mints the per-archive capability token the one-tap
  3104. verdict links carry.
  3105. Lives here rather than inline in ``on_print_complete``'s notification task
  3106. because that task swallows every exception: extracted, the gate and the two
  3107. emissions can be driven by a test, which is the only thing standing between
  3108. a regression here and a farm that quietly stops asking.
  3109. Returns whether a prompt was sent.
  3110. """
  3111. logger = logging.getLogger(__name__)
  3112. from backend.app.models.archive import PrintArchive
  3113. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3114. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3115. return False
  3116. import secrets as _secrets
  3117. # A spent token stays on the row so the one-tap route can recognise it, so
  3118. # "has a token" no longer means "answerable". A prompt going out now needs a
  3119. # live one: mint a new token whenever the stored one is already spent, or
  3120. # every button in the new message would land on the already-answered page.
  3121. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3122. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3123. confirm_archive.confirm_token_used_at = None
  3124. await db.commit()
  3125. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3126. base = await get_external_base_url(db)
  3127. if not await get_setting(db, "external_url"):
  3128. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3129. # absolute URL, so an unconfigured install used to get a message body
  3130. # with two unusable relative paths and no buttons at all. The shared
  3131. # fallback at least produces tappable links; say which setting makes
  3132. # them resolve from a phone.
  3133. logger.warning(
  3134. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3135. "Set Settings → External URL so they resolve away from this host.",
  3136. base,
  3137. )
  3138. token = confirm_archive.confirm_token
  3139. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3140. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3141. confirm_url = f"{base}/archives?confirm={archive_id}"
  3142. await ws_manager.send_print_confirm_request(
  3143. printer_id,
  3144. {
  3145. "archive_id": archive_id,
  3146. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3147. },
  3148. )
  3149. await notification_service.on_print_confirm_request(
  3150. printer_id,
  3151. printer_name,
  3152. data,
  3153. db,
  3154. archive_data=archive_data,
  3155. good_url=good_url,
  3156. reject_url=reject_url,
  3157. confirm_url=confirm_url,
  3158. )
  3159. return True
  3160. async def on_print_start(printer_id: int, data: dict):
  3161. """Handle print start - archive the 3MF file immediately."""
  3162. logger = logging.getLogger(__name__)
  3163. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3164. # Clear any stale user-stopped flag from previous print cycles
  3165. _user_stopped_printers.discard(printer_id)
  3166. _kill_switch_notification_tasks.pop(printer_id, None)
  3167. # #1721: drop any leftover pre-captured finish frame from a prior print
  3168. # so a never-consumed cache entry can't bleed into the new print's photo.
  3169. _stage22_finish_frames.pop(printer_id, None)
  3170. # #1867: same for the in-print frame bank — a queued print must not reuse
  3171. # the previous job's banked frame.
  3172. _inprint_frame_bank.pop(printer_id, None)
  3173. _inprint_frame_bank_ts.pop(printer_id, None)
  3174. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3175. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3176. # print's flag instead of inheriting it.
  3177. print_dispatch_context.adopt(printer_id)
  3178. # Cancel any active bed cooldown waiter for this printer
  3179. if _bed_cool_waiters.pop(printer_id, None):
  3180. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3181. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3182. from backend.app.api.routes.printers import clear_cover_cache
  3183. clear_cover_cache(printer_id)
  3184. await ws_manager.send_print_start(printer_id, data)
  3185. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3186. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3187. # MQTT relay - publish print start
  3188. try:
  3189. printer_info = printer_manager.get_printer(printer_id)
  3190. if printer_info:
  3191. await mqtt_relay.on_print_start(
  3192. printer_id,
  3193. printer_info.name,
  3194. printer_info.serial_number,
  3195. data.get("filename", ""),
  3196. data.get("subtask_name", ""),
  3197. )
  3198. except Exception:
  3199. pass # Don't fail print start callback if MQTT fails
  3200. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3201. # and mapping, and the seeded tray-change log.
  3202. #
  3203. # Unconditional, for both inventory backends. This only *captures* — the
  3204. # writing is still split, with the internal tracker skipped at completion
  3205. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3206. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3207. # tray-change log, and that log is the only record of which spool fed
  3208. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3209. # it on one side only would leave Spoolman users with the mid-print
  3210. # restart bug this fixes for everyone else.
  3211. try:
  3212. async with async_session() as db:
  3213. from backend.app.api.routes.settings import get_setting
  3214. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3215. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3216. await usage_on_print_start(
  3217. printer_id,
  3218. data,
  3219. printer_manager,
  3220. db=db,
  3221. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3222. )
  3223. except Exception as e:
  3224. logger.warning("Usage tracker on_print_start failed: %s", e)
  3225. # Track if notification was sent (to avoid sending twice)
  3226. notification_sent = False
  3227. # Smart plug automation: turn on plug when print starts
  3228. try:
  3229. async with async_session() as db:
  3230. await smart_plug_manager.on_print_start(printer_id, db)
  3231. except Exception as e:
  3232. logger.warning("Smart plug on_print_start failed: %s", e)
  3233. async with async_session() as db:
  3234. from backend.app.models.printer import Printer
  3235. from backend.app.services.bambu_ftp import list_files_async
  3236. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3237. printer = result.scalar_one_or_none()
  3238. # Plate detection check - pause if objects detected on build plate
  3239. logger.info(
  3240. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3241. )
  3242. if printer and printer.plate_detection_enabled:
  3243. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3244. # Release the pooled DB connection before the plate-detection camera
  3245. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3246. # printer SELECT has run so far — nothing to persist — so this commit
  3247. # is a data-noop that ends the read transaction and returns the
  3248. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3249. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3250. # archive lookups below re-acquire a fresh connection on next execute.
  3251. await db.commit()
  3252. try:
  3253. from backend.app.services.plate_detection import check_plate_empty
  3254. # Build ROI tuple from printer settings if available
  3255. roi = None
  3256. if all(
  3257. [
  3258. printer.plate_detection_roi_x is not None,
  3259. printer.plate_detection_roi_y is not None,
  3260. printer.plate_detection_roi_w is not None,
  3261. printer.plate_detection_roi_h is not None,
  3262. ]
  3263. ):
  3264. roi = (
  3265. printer.plate_detection_roi_x,
  3266. printer.plate_detection_roi_y,
  3267. printer.plate_detection_roi_w,
  3268. printer.plate_detection_roi_h,
  3269. )
  3270. # Auto-turn on chamber light if it's off for better detection
  3271. light_was_off = False
  3272. client = printer_manager.get_client(printer_id)
  3273. if client and client.state:
  3274. light_was_off = not client.state.chamber_light
  3275. if light_was_off:
  3276. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3277. client.set_chamber_light(True)
  3278. # Wait for light to physically turn on and camera to adjust exposure
  3279. await asyncio.sleep(2.5)
  3280. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3281. plate_result = await check_plate_empty(
  3282. printer_id=printer_id,
  3283. ip_address=printer.ip_address,
  3284. access_code=printer.access_code,
  3285. model=printer.model,
  3286. include_debug_image=False,
  3287. external_camera_url=printer.external_camera_url,
  3288. external_camera_type=printer.external_camera_type,
  3289. use_external=printer.external_camera_enabled,
  3290. roi=roi,
  3291. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3292. )
  3293. # Restore chamber light to original state
  3294. if light_was_off and client:
  3295. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3296. client.set_chamber_light(False)
  3297. if not plate_result.needs_calibration and not plate_result.is_empty:
  3298. # Objects detected - pause the print!
  3299. logger.warning(
  3300. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3301. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3302. )
  3303. client = printer_manager.get_client(printer_id)
  3304. if client:
  3305. client.pause_print()
  3306. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3307. # Send notification about plate not empty
  3308. await ws_manager.broadcast(
  3309. {
  3310. "type": "plate_not_empty",
  3311. "printer_id": printer_id,
  3312. "printer_name": printer.name,
  3313. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3314. }
  3315. )
  3316. # Also send push notification
  3317. try:
  3318. await notification_service.on_plate_not_empty(
  3319. printer_id=printer_id,
  3320. printer_name=printer.name,
  3321. db=db,
  3322. difference_percent=plate_result.difference_percent,
  3323. )
  3324. except Exception as notif_err:
  3325. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3326. else:
  3327. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3328. except Exception as plate_err:
  3329. # Don't block print on plate detection errors
  3330. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3331. if not printer:
  3332. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3333. if not notification_sent:
  3334. await _send_print_start_notification(printer_id, data, logger=logger)
  3335. return
  3336. if not printer.auto_archive:
  3337. # auto-archive disabled — check if there's an expected print (dispatched
  3338. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3339. # If so, fall through to the expected-print handling below so the archive
  3340. # is tracked in _active_prints and usage tracking works at completion.
  3341. _fn = data.get("filename", "")
  3342. _sn = data.get("subtask_name", "")
  3343. _check_keys: list[tuple[int, str]] = []
  3344. if _sn:
  3345. _check_keys += [
  3346. (printer_id, _sn),
  3347. (printer_id, f"{_sn}.3mf"),
  3348. (printer_id, f"{_sn}.gcode.3mf"),
  3349. ]
  3350. if _fn:
  3351. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3352. _check_keys.append((printer_id, _base_fn))
  3353. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3354. _check_keys += [
  3355. (printer_id, _no_archive_base),
  3356. (printer_id, f"{_no_archive_base}.3mf"),
  3357. ]
  3358. _has_expected = any(k in _expected_prints for k in _check_keys)
  3359. if not _has_expected:
  3360. # No expected print — truly external print (started from slicer/touchscreen)
  3361. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3362. if not notification_sent:
  3363. _no_archive_creator: int | None = None
  3364. for _key in _check_keys:
  3365. _expected_prints.pop(_key, None)
  3366. _expected_print_registered_at.pop(_key, None)
  3367. popped_creator = _expected_print_creators.pop(_key, None)
  3368. if _no_archive_creator is None:
  3369. _no_archive_creator = popped_creator
  3370. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3371. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3372. return
  3373. else:
  3374. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3375. # Get the filename and subtask_name
  3376. filename = data.get("filename", "")
  3377. subtask_name = data.get("subtask_name", "")
  3378. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3379. # present, it lets us match an archive across a backend restart (#972):
  3380. # same id → same print → resume the existing row instead of cancelling
  3381. # it and recreating from scratch (which loses started_at). Treat "0"
  3382. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3383. raw_mqtt = data.get("raw_data") or {}
  3384. subtask_id = raw_mqtt.get("subtask_id")
  3385. if subtask_id is not None:
  3386. subtask_id = str(subtask_id).strip()
  3387. if subtask_id in ("", "0"):
  3388. subtask_id = None
  3389. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3390. # Skip the printer's own jobs — a calibration run is not a user's print.
  3391. # See is_internal_printer_job for what counts and why both fields are
  3392. # tested; the pressure-advance line reports as a subtask name with no
  3393. # /usr/ path, which the old prefix-only test here missed entirely.
  3394. #
  3395. # No notification either. The event describes the printer calibrating
  3396. # itself, so "Print started" is as wrong as the archive was, and the
  3397. # matching completion is suppressed in on_print_complete for the same
  3398. # reason.
  3399. if is_internal_printer_job(filename, subtask_name):
  3400. logger.info(
  3401. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3402. filename,
  3403. subtask_name,
  3404. )
  3405. return
  3406. if not filename and not subtask_name:
  3407. # Send notification without archive data (no filename)
  3408. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3409. if not notification_sent:
  3410. await _send_print_start_notification(printer_id, data, logger=logger)
  3411. return
  3412. # Check if this is an expected print from reprint/scheduled
  3413. # Build list of possible keys to check
  3414. expected_keys = []
  3415. if subtask_name:
  3416. expected_keys.append((printer_id, subtask_name))
  3417. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3418. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3419. if filename:
  3420. fname = filename.split("/")[-1] if "/" in filename else filename
  3421. expected_keys.append((printer_id, fname))
  3422. # Strip extensions to match
  3423. base = fname.replace(".gcode", "").replace(".3mf", "")
  3424. expected_keys.append((printer_id, base))
  3425. expected_keys.append((printer_id, f"{base}.3mf"))
  3426. expected_archive_id = None
  3427. for key in expected_keys:
  3428. expected_archive_id = _expected_prints.pop(key, None)
  3429. _expected_print_registered_at.pop(key, None)
  3430. if expected_archive_id:
  3431. # Clean up other possible keys for this print
  3432. for other_key in expected_keys:
  3433. _expected_prints.pop(other_key, None)
  3434. _expected_print_registered_at.pop(other_key, None)
  3435. break
  3436. if expected_archive_id:
  3437. # This is a reprint/scheduled print - use existing archive, don't create new one
  3438. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3439. from backend.app.models.archive import PrintArchive
  3440. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3441. archive = result.scalar_one_or_none()
  3442. if archive:
  3443. # Update archive status to printing
  3444. archive.status = "printing"
  3445. archive.started_at = datetime.now(timezone.utc)
  3446. # The previous run's answer is still on this row and the
  3447. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3448. # so without a reset the second run inherits the first run's
  3449. # verdict: no prompt at all, and a green "good" badge on a run
  3450. # nobody ever judged.
  3451. if archive.confirm_requested:
  3452. archive.user_verdict = None
  3453. archive.user_verdict_source = None
  3454. archive.user_verdict_at = None
  3455. archive.confirm_token = None
  3456. archive.confirm_token_used_at = None
  3457. # Reprint of an archive reuses the source row. Without resetting
  3458. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3459. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3460. # extracts the *original* print's last frame, which then ships in
  3461. # the completion notification (#1707). Clear the path so the
  3462. # scanner runs fresh; also unlink the old video file so reprints
  3463. # don't accumulate orphans in the archive directory. Photos list
  3464. # is left alone — accumulating one finish photo per run is fine.
  3465. # The print-start baseline (#2704) is stale for the same reason:
  3466. # it describes the printer before the previous run. The capture
  3467. # below overwrites it, but clear it here too so an early failure
  3468. # can't leave the scan diffing against the wrong snapshot.
  3469. archive.timelapse_baseline = None
  3470. stale_timelapse_relpath = archive.timelapse_path
  3471. if stale_timelapse_relpath:
  3472. archive.timelapse_path = None
  3473. try:
  3474. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3475. if stale_path.is_file():
  3476. stale_path.unlink()
  3477. logger.info(
  3478. "Deleted stale timelapse %s on reprint of archive %s",
  3479. stale_timelapse_relpath,
  3480. expected_archive_id,
  3481. )
  3482. except OSError as e:
  3483. logger.warning(
  3484. "Failed to delete stale timelapse %s on reprint: %s",
  3485. stale_timelapse_relpath,
  3486. e,
  3487. )
  3488. # Persist a restart-stable id so a later restart resumes this
  3489. # archive by subtask_id instead of name-matching + duplicating
  3490. # it (#1485). The printer often hasn't echoed subtask_id back
  3491. # this soon after dispatch, so fall back to the id Bambuddy
  3492. # minted when it sent the print command. Scoped to this
  3493. # expected-print branch on purpose: an expected match means
  3494. # Bambuddy dispatched this exact print in this process, so the
  3495. # client's last-dispatch id genuinely belongs to it — using it
  3496. # for an externally-started print could mis-tag the archive.
  3497. effective_subtask_id = subtask_id
  3498. if not effective_subtask_id:
  3499. _client = printer_manager.get_client(printer_id)
  3500. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3501. if _dispatched:
  3502. effective_subtask_id = str(_dispatched).strip() or None
  3503. # Update on first-set OR on reprint (the queue dispatcher mints
  3504. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3505. # the rewrite for reprints leaves the archive holding the FIRST
  3506. # run's id; if MQTT then reconnects mid-print, the reconciler
  3507. # (#1542) compares the stale stored id against the printer's
  3508. # live id, sees a mismatch, and synthesises a bogus PRINT
  3509. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3510. # in #1807. Inequality check preserves the noop-on-stable-push
  3511. # behaviour the earlier `not archive.subtask_id` guard provided.
  3512. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3513. archive.subtask_id = effective_subtask_id
  3514. # #1403 follow-up: VP-queue archives are created with
  3515. # printer_id=None at queue-add time (we don't know which
  3516. # printer will run the job yet). When the print actually
  3517. # starts on a specific printer the expected-archive lookup
  3518. # used to skip this assignment, leaving printer_id=None
  3519. # forever — which then disables the "Scan for timelapse"
  3520. # button in ArchivesPage (gated on !archive.printer_id).
  3521. if archive.printer_id != printer_id:
  3522. archive.printer_id = printer_id
  3523. await db.commit()
  3524. # Track as active print
  3525. _active_prints[(printer_id, archive.filename)] = archive.id
  3526. if subtask_name:
  3527. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3528. # Start timelapse session if external camera is enabled (#1353).
  3529. # Queue / VP-dispatched prints land here in the expected-archive
  3530. # branch and used to skip start_session entirely — frames were
  3531. # never captured and the post-print stitch silently returned None.
  3532. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3533. # Inject ams_mapping into usage tracker session — the session was created
  3534. # before expected-print promotion, so it may have ams_mapping=None when
  3535. # the MQTT request topic subscription failed (common on P1S/A1).
  3536. _stored_map = _print_ams_mappings.get(expected_archive_id)
  3537. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  3538. if _stored_map or _stored_plate_id is not None:
  3539. try:
  3540. from backend.app.services.usage_tracker import _active_sessions
  3541. _ut_session = _active_sessions.get(printer_id)
  3542. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  3543. _ut_session.ams_mapping = _stored_map
  3544. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  3545. # plate_id injection covers direct-Print of plate N of a multi-plate
  3546. # 3MF — queue prints already capture it via the on_print_start queue
  3547. # lookup, but direct-Print never goes through the queue (#1697).
  3548. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  3549. _ut_session.plate_id = _stored_plate_id
  3550. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  3551. except Exception:
  3552. pass
  3553. # Set up energy tracking (#941: persist start on archive row)
  3554. await _record_energy_start(archive, printer_id, db, context="expected-print")
  3555. await ws_manager.send_archive_updated(
  3556. {
  3557. "id": archive.id,
  3558. "status": "printing",
  3559. }
  3560. )
  3561. # Send notification with archive data (reprint/scheduled)
  3562. if not notification_sent:
  3563. # Use archive's created_by_id; fall back to the creator registered via
  3564. # register_expected_print (handles library-file-based queue items where
  3565. # the freshly-created archive has no created_by_id yet).
  3566. # Pop ALL matching keys so no stale entries remain in the dict.
  3567. fallback_creator = None
  3568. for key in expected_keys:
  3569. popped = _expected_print_creators.pop(key, None)
  3570. if fallback_creator is None:
  3571. fallback_creator = popped
  3572. archive_data = {
  3573. "print_time_seconds": archive.print_time_seconds,
  3574. "created_by_id": archive.created_by_id or fallback_creator,
  3575. }
  3576. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3577. # Extract printable objects from the archived 3MF file
  3578. _load_objects_from_archive(archive, printer_id, logger)
  3579. # Store Spoolman tracking data for per-filament usage reporting
  3580. try:
  3581. await _store_spoolman_print_data(
  3582. printer_id,
  3583. archive.id,
  3584. archive.file_path,
  3585. db,
  3586. printer_manager,
  3587. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3588. plate_id=_get_start_plate_id(archive.id),
  3589. )
  3590. except Exception as e:
  3591. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3592. # Capture timelapse file baseline for snapshot-diff on completion
  3593. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  3594. # hit this branch — without the baseline the completion-time scan
  3595. # falls into its "take baseline now" fallback, which snapshots
  3596. # AFTER the new MP4 already exists and never matches a diff
  3597. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  3598. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3599. return # Skip creating a new archive
  3600. # Check if there's already a "printing" archive for this printer/file
  3601. # This prevents duplicates when backend restarts during an active print
  3602. from backend.app.models.archive import PrintArchive
  3603. existing_archive: PrintArchive | None = None
  3604. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  3605. # across a backend restart for the same print, so this is the most
  3606. # reliable way to reattach. We also accept a previously stale-cancelled
  3607. # archive here so users upgrading mid-print get revived when the row
  3608. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  3609. if subtask_id:
  3610. by_id = await db.execute(
  3611. select(PrintArchive)
  3612. .where(PrintArchive.printer_id == printer_id)
  3613. .where(PrintArchive.subtask_id == subtask_id)
  3614. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  3615. .order_by(PrintArchive.created_at.desc())
  3616. .limit(1)
  3617. )
  3618. candidate = by_id.scalar_one_or_none()
  3619. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3620. existing_archive = candidate
  3621. # Fallback match: name-based lookup. Kept as-is for prints whose
  3622. # subtask_id is missing ("0" / local / non-cloud prints).
  3623. if existing_archive is None:
  3624. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3625. existing = await db.execute(
  3626. select(PrintArchive)
  3627. .where(PrintArchive.printer_id == printer_id)
  3628. .where(PrintArchive.status == "printing")
  3629. .where(
  3630. or_(
  3631. PrintArchive.print_name == check_name,
  3632. PrintArchive.filename.in_(
  3633. [
  3634. f"{check_name}.3mf",
  3635. f"{check_name}.gcode.3mf",
  3636. ]
  3637. ),
  3638. )
  3639. )
  3640. .order_by(PrintArchive.created_at.desc())
  3641. .limit(1)
  3642. )
  3643. existing_archive = existing.scalar_one_or_none()
  3644. if existing_archive:
  3645. # subtask_id match → always resume, regardless of age. Same print,
  3646. # just a backend restart. Revive if it was previously stale-cancelled.
  3647. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  3648. if subtask_match:
  3649. if existing_archive.status == "cancelled":
  3650. logger.warning(
  3651. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  3652. existing_archive.id,
  3653. subtask_id,
  3654. )
  3655. existing_archive.status = "printing"
  3656. existing_archive.failure_reason = None
  3657. await db.commit()
  3658. else:
  3659. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  3660. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3661. if existing_archive.energy_start_kwh is None:
  3662. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  3663. if not notification_sent:
  3664. archive_data = {
  3665. "print_time_seconds": existing_archive.print_time_seconds,
  3666. "created_by_id": existing_archive.created_by_id,
  3667. }
  3668. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3669. _load_objects_from_archive(existing_archive, printer_id, logger)
  3670. return
  3671. # Name-match only (no subtask_id to anchor on): decide resume vs.
  3672. # stale from the printer's *current* progress, not wall-clock age.
  3673. # A genuinely long print used to trip a blind 4h cutoff and have its
  3674. # live archive cancelled + duplicated on every backend restart
  3675. # (#1485). If the printer reports real progress, this name-matched
  3676. # 'printing' archive IS that ongoing print — resume it whatever its
  3677. # age. Only treat it as a stale leftover when the printer clearly
  3678. # shows a different, freshly-started print: near-0% progress on an
  3679. # archive far too old to still be at 0%. Unknown progress (printer
  3680. # not connected) never cancels — resuming is the safe default.
  3681. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  3682. live_status = printer_manager.get_status(printer_id)
  3683. live_progress = getattr(live_status, "progress", None) if live_status else None
  3684. looks_stale = (
  3685. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  3686. )
  3687. if looks_stale:
  3688. logger.warning(
  3689. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  3690. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  3691. )
  3692. existing_archive.status = "cancelled"
  3693. # Canonical key, not a sentence (issue #2974). "No status update
  3694. # received" is what both stale paths actually observed; which of
  3695. # the two it was is already carried by ``status`` -- cancelled
  3696. # here, the reconciled outcome at the reconnect site -- so one
  3697. # key loses no information and gives the Statistics breakdown a
  3698. # single bucket instead of two untranslatable prose strings.
  3699. existing_archive.failure_reason = "noStatusUpdate"
  3700. await db.commit()
  3701. # Fall through to create new archive (don't return)
  3702. else:
  3703. logger.info(
  3704. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  3705. )
  3706. # Track this as the active print
  3707. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3708. # Attach subtask_id retroactively so future restarts can resume.
  3709. # Compare for inequality (not "is empty") to also pick up reprint
  3710. # dispatches that mint a fresh id — see #1807 for the bogus
  3711. # "Print Stopped" the strict-empty guard caused on reconnect.
  3712. if subtask_id and existing_archive.subtask_id != subtask_id:
  3713. existing_archive.subtask_id = subtask_id
  3714. await db.commit()
  3715. # Also set up energy tracking if not already tracked (#941: persisted column)
  3716. if existing_archive.energy_start_kwh is None:
  3717. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  3718. # Send notification with archive data (existing archive)
  3719. if not notification_sent:
  3720. archive_data = {
  3721. "print_time_seconds": existing_archive.print_time_seconds,
  3722. "created_by_id": existing_archive.created_by_id,
  3723. }
  3724. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3725. # Extract printable objects from the archived 3MF file
  3726. _load_objects_from_archive(existing_archive, printer_id, logger)
  3727. return
  3728. # Build list of possible 3MF filenames to try
  3729. possible_names = []
  3730. # Bambu printers typically store files as "Name.gcode.3mf"
  3731. # The subtask_name is usually the best source for the filename
  3732. if subtask_name:
  3733. # Try common Bambu naming patterns
  3734. possible_names.append(f"{subtask_name}.gcode.3mf")
  3735. possible_names.append(f"{subtask_name}.3mf")
  3736. # Try original filename with .3mf extension
  3737. if filename:
  3738. # Extract just the filename part, not the full path
  3739. fname = filename.split("/")[-1] if "/" in filename else filename
  3740. if fname.endswith(".3mf"):
  3741. possible_names.append(fname)
  3742. elif fname.endswith(".gcode"):
  3743. base = fname.rsplit(".", 1)[0]
  3744. possible_names.append(f"{base}.gcode.3mf")
  3745. possible_names.append(f"{base}.3mf")
  3746. else:
  3747. possible_names.append(f"{fname}.gcode.3mf")
  3748. possible_names.append(f"{fname}.3mf")
  3749. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3750. space_variants = []
  3751. for name in possible_names:
  3752. if " " in name:
  3753. space_variants.append(name.replace(" ", "_"))
  3754. possible_names.extend(space_variants)
  3755. # Remove duplicates while preserving order
  3756. seen = set()
  3757. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  3758. logger.info("Trying filenames: %s", possible_names)
  3759. # Release the pooled DB connection before the 3MF FTP download. Reaching
  3760. # here means none of the expected-/existing-archive write branches ran
  3761. # (they all return earlier) — only SELECTs have executed on this path, so
  3762. # this commit persists nothing; it ends the read transaction so the
  3763. # connection returns to the pool during the download. That download tries
  3764. # up to five remote paths per candidate filename with retry/backoff and
  3765. # can run for minutes under FTP contention; holding the session across it
  3766. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  3767. # work runs during the download — the new-archive writes below re-acquire
  3768. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  3769. await db.commit()
  3770. # Try to find and download the 3MF file
  3771. temp_path = None
  3772. downloaded_filename = None
  3773. # Cache check: cover endpoint may have already pulled this 3MF during
  3774. # the print (frontend opens the card and shows the thumbnail) — reuse
  3775. # that file instead of re-downloading 36MB over the same FTP link that
  3776. # just served it (#972). The cache keys on a normalized filename so
  3777. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  3778. for try_filename in possible_names:
  3779. if not try_filename.endswith(".3mf"):
  3780. continue
  3781. cached = get_cached_3mf(printer_id, try_filename)
  3782. if cached:
  3783. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  3784. temp_path = cached
  3785. downloaded_filename = try_filename
  3786. break
  3787. # Does this printer keep the sliced file somewhere FTPS can reach? On
  3788. # H2-series and P2S the answer is routinely no — the file stays on
  3789. # internal eMMC and port 990 only ever serves external storage — and
  3790. # then the whole sweep below (six filenames x five directories x four
  3791. # retries, then the directory walk) is ~110 connections that cannot
  3792. # succeed. Skip it and say why (#2780).
  3793. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  3794. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  3795. # running rather than because the file is somewhere unreachable. The
  3796. # distinction is the whole of #2957: one is permanent, the other clears
  3797. # in minutes with the file still sitting on the printer.
  3798. blocked_by_ftps_cooloff = False
  3799. # Set when a probe reached the printer and still came back without the
  3800. # file -- a timeout mid-transfer, a refused connection, anything that is
  3801. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  3802. # caught by name below, so a file that genuinely is not on the card
  3803. # leaves this False and schedules nothing. Anything else means the
  3804. # transfer, not the file, is what failed, and that does not last (#3063).
  3805. ftp_transfer_failed = False
  3806. # The print's name, for a fallback archive whose `subtask_name` the
  3807. # plate guard below had to disown. Display only, and deliberately kept
  3808. # apart from `subtask_name`: that variable is what every file lookup
  3809. # here is built from, and once a name has been shown to fetch another
  3810. # plate's 3MF it must not key `_active_prints` either, or the cover
  3811. # endpoint hands the same contradicted file to
  3812. # `_recover_fallback_archive` and fills the row in with it (#3126).
  3813. display_name_after_plate_reject: str | None = None
  3814. # Get FTP retry settings
  3815. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3816. # ...but "the printer put it on eMMC" is where it went, not whether we
  3817. # can read it. An H2D with a card in mirrors the job to /cache and
  3818. # serves it happily, and skipping on the URL alone cost that reporter
  3819. # every archive for two days (#2856). So ask the printer instead of
  3820. # guessing: the dispatch named the exact file, which is one connection
  3821. # walking five paths rather than the sweep's ~110. Only when the probe
  3822. # comes back empty does the verdict's reason stand.
  3823. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  3824. if ftps_handshake_blocked(printer.ip_address):
  3825. # Deliberately NOT recorded as a cool-off give-up. This branch
  3826. # only runs on an unreachable verdict, and that verdict is the
  3827. # honest, permanent reason the archive is empty — the probe was
  3828. # a long shot on top of it. Blaming the cool-off here would
  3829. # schedule a retry for a file sitting on internal eMMC, which is
  3830. # the sweep #2780 removed (#2957).
  3831. logger.debug(
  3832. "Not probing for %s on printer %s: its file service is not answering over TLS",
  3833. storage.probe_filename,
  3834. printer_id,
  3835. )
  3836. else:
  3837. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  3838. probe_path.parent.mkdir(parents=True, exist_ok=True)
  3839. try:
  3840. probe_hit = await download_file_try_paths_async(
  3841. printer.ip_address,
  3842. printer.access_code,
  3843. ftp_probe_paths(storage.probe_filename),
  3844. probe_path,
  3845. socket_timeout=ftp_timeout,
  3846. printer_model=printer.model,
  3847. )
  3848. except Exception as e:
  3849. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  3850. probe_hit = False
  3851. if probe_hit:
  3852. downloaded_filename = storage.probe_filename
  3853. temp_path = probe_path
  3854. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  3855. # Naming the path, not just the file: a printer that keeps
  3856. # uploads around for weeks can serve a same-named copy of an
  3857. # earlier slice, and without the directory in the log that
  3858. # mismatch is invisible rather than merely rare (#1820).
  3859. logger.info(
  3860. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  3861. downloaded_filename,
  3862. probe_hit,
  3863. printer_id,
  3864. storage.reason,
  3865. )
  3866. if not storage.reachable and not downloaded_filename:
  3867. # Same opening words whether or not a probe ran, because that is
  3868. # the phrase support asks people to grep for — only the tail says
  3869. # which of the two happened.
  3870. logger.info(
  3871. "Skipping the 3MF lookup for printer %s: %s — %s",
  3872. printer_id,
  3873. storage.reason,
  3874. "no copy of it on external storage either"
  3875. if storage.probe_filename
  3876. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  3877. )
  3878. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  3879. if not try_filename.endswith(".3mf"):
  3880. continue
  3881. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  3882. # printers, so try it first — deferring it to last cost #972's reporter
  3883. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  3884. # landing on the path that actually had the file.
  3885. remote_paths = [
  3886. f"/{try_filename}",
  3887. f"/cache/{try_filename}",
  3888. f"/model/{try_filename}",
  3889. f"/data/{try_filename}",
  3890. f"/data/Metadata/{try_filename}",
  3891. ]
  3892. temp_path = app_settings.archive_dir / "temp" / try_filename
  3893. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3894. for remote_path in remote_paths:
  3895. if ftps_handshake_blocked(printer.ip_address):
  3896. # The printer's FTPS service is not completing a TLS
  3897. # handshake, so it has no path we could reach — walking the
  3898. # remaining candidates only re-runs the same failure
  3899. # (#2780). Fall through to the no-3MF archive now.
  3900. #
  3901. # Remember *why*, though. This is the one give-up that is
  3902. # temporary: the cool-off clears in minutes and the file was
  3903. # on the printer the whole time. The fallback archive is
  3904. # stamped with it so a retry can be scheduled, and so the
  3905. # Archives banner stops blaming storage (#2957).
  3906. blocked_by_ftps_cooloff = True
  3907. logger.warning(
  3908. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  3909. printer_id,
  3910. )
  3911. break
  3912. logger.debug("Trying FTP download: %s", remote_path)
  3913. try:
  3914. if ftp_retry_enabled:
  3915. downloaded = await with_ftp_retry(
  3916. download_file_async,
  3917. printer.ip_address,
  3918. printer.access_code,
  3919. remote_path,
  3920. temp_path,
  3921. timeout=ftp_timeout,
  3922. socket_timeout=ftp_timeout,
  3923. printer_model=printer.model,
  3924. max_retries=ftp_retry_count,
  3925. retry_delay=ftp_retry_delay,
  3926. operation_name=f"Download 3MF from {remote_path}",
  3927. cooloff_ip=printer.ip_address,
  3928. non_retry_exceptions=(FileNotOnPrinterError,),
  3929. )
  3930. else:
  3931. downloaded = await download_file_async(
  3932. printer.ip_address,
  3933. printer.access_code,
  3934. remote_path,
  3935. temp_path,
  3936. timeout=ftp_timeout,
  3937. socket_timeout=ftp_timeout,
  3938. printer_model=printer.model,
  3939. )
  3940. if downloaded:
  3941. downloaded_filename = try_filename
  3942. logger.info("Downloaded: %s", remote_path)
  3943. # Populate shared cache so the cover endpoint (if it
  3944. # runs next) doesn't refetch the same 36MB over FTP.
  3945. cache_3mf_download(printer_id, try_filename, temp_path)
  3946. break
  3947. # with_ftp_retry returns None once it has spent its budget,
  3948. # and download_file_async returns False on a timeout, so an
  3949. # exhausted transfer arrives here rather than as an
  3950. # exception (#3063).
  3951. ftp_transfer_failed = True
  3952. except FileNotOnPrinterError:
  3953. # 550 — file isn't at this path. Advance to next candidate
  3954. # without burning the retry budget.
  3955. logger.debug("3MF not at %s (550), trying next path", remote_path)
  3956. except Exception as e:
  3957. ftp_transfer_failed = True
  3958. logger.debug("FTP download failed for %s: %s", remote_path, e)
  3959. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  3960. break
  3961. # If still not found, try listing directories to find matching file
  3962. # Different printer models use different directory structures. Skipped
  3963. # when the printer's FTPS handshake is failing — the directory walk is
  3964. # five more connections that cannot get further than the download did.
  3965. if (
  3966. not downloaded_filename
  3967. and storage.reachable
  3968. and (filename or subtask_name)
  3969. and not ftps_handshake_blocked(printer.ip_address)
  3970. ):
  3971. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  3972. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  3973. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  3974. for search_dir in search_dirs:
  3975. if downloaded_filename:
  3976. break
  3977. try:
  3978. dir_files = await list_files_async(
  3979. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  3980. )
  3981. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  3982. if threemf_files:
  3983. logger.info(
  3984. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  3985. )
  3986. for f in dir_files:
  3987. if f.get("is_directory"):
  3988. continue
  3989. fname = f.get("name", "")
  3990. # Normalize both for comparison (spaces and underscores are equivalent)
  3991. fname_normalized = fname.lower().replace(" ", "_")
  3992. search_normalized = search_term.replace(" ", "_")
  3993. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  3994. logger.info("Found matching file in %s: %s", search_dir, fname)
  3995. temp_path = app_settings.archive_dir / "temp" / fname
  3996. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3997. remote_full_path = posixpath.join(search_dir, fname)
  3998. if ftp_retry_enabled:
  3999. downloaded = await with_ftp_retry(
  4000. download_file_async,
  4001. printer.ip_address,
  4002. printer.access_code,
  4003. remote_full_path,
  4004. temp_path,
  4005. timeout=ftp_timeout,
  4006. socket_timeout=ftp_timeout,
  4007. printer_model=printer.model,
  4008. max_retries=ftp_retry_count,
  4009. retry_delay=ftp_retry_delay,
  4010. operation_name=f"Download 3MF from {remote_full_path}",
  4011. cooloff_ip=printer.ip_address,
  4012. )
  4013. else:
  4014. downloaded = await download_file_async(
  4015. printer.ip_address,
  4016. printer.access_code,
  4017. remote_full_path,
  4018. temp_path,
  4019. timeout=ftp_timeout,
  4020. socket_timeout=ftp_timeout,
  4021. printer_model=printer.model,
  4022. )
  4023. if downloaded:
  4024. downloaded_filename = fname
  4025. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4026. cache_3mf_download(printer_id, fname, temp_path)
  4027. break
  4028. # The listing named the file, so it is on the card;
  4029. # only the transfer failed (#3063).
  4030. ftp_transfer_failed = True
  4031. except Exception as e:
  4032. logger.debug("Failed to list %s: %s", search_dir, e)
  4033. # Validate the downloaded 3MF actually matches the plate that's running
  4034. # (#1204): subtask_name lags across consecutive plates of the same model,
  4035. # so the first FTP candidate (built from subtask_name) can land on the
  4036. # previous plate's still-resident upload. Cross-check the slice_info
  4037. # plate index against the plate parsed from gcode_file (always fresh —
  4038. # it's the field whose change triggered this callback).
  4039. if downloaded_filename and temp_path:
  4040. expected_plate = parse_plate_id(filename)
  4041. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4042. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4043. logger.warning(
  4044. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4045. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4046. downloaded_filename,
  4047. actual_plate,
  4048. expected_plate,
  4049. subtask_name,
  4050. )
  4051. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4052. retry_succeeded = False
  4053. if corrected_subtask and corrected_subtask != subtask_name:
  4054. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4055. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4056. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4057. for remote_path in (
  4058. f"/{try_filename}",
  4059. f"/cache/{try_filename}",
  4060. f"/model/{try_filename}",
  4061. f"/data/{try_filename}",
  4062. f"/data/Metadata/{try_filename}",
  4063. ):
  4064. try:
  4065. if ftp_retry_enabled:
  4066. downloaded = await with_ftp_retry(
  4067. download_file_async,
  4068. printer.ip_address,
  4069. printer.access_code,
  4070. remote_path,
  4071. retry_temp_path,
  4072. timeout=ftp_timeout,
  4073. socket_timeout=ftp_timeout,
  4074. printer_model=printer.model,
  4075. max_retries=ftp_retry_count,
  4076. retry_delay=ftp_retry_delay,
  4077. operation_name=f"Re-download 3MF from {remote_path}",
  4078. cooloff_ip=printer.ip_address,
  4079. non_retry_exceptions=(FileNotOnPrinterError,),
  4080. )
  4081. else:
  4082. downloaded = await download_file_async(
  4083. printer.ip_address,
  4084. printer.access_code,
  4085. remote_path,
  4086. retry_temp_path,
  4087. timeout=ftp_timeout,
  4088. socket_timeout=ftp_timeout,
  4089. printer_model=printer.model,
  4090. )
  4091. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4092. logger.info(
  4093. "[CALLBACK] Re-download succeeded with corrected name %s "
  4094. "(plate %s) — replacing wrong file",
  4095. try_filename,
  4096. expected_plate,
  4097. )
  4098. try:
  4099. temp_path.unlink(missing_ok=True)
  4100. except OSError:
  4101. pass
  4102. temp_path = retry_temp_path
  4103. downloaded_filename = try_filename
  4104. subtask_name = corrected_subtask
  4105. cache_3mf_download(printer_id, try_filename, temp_path)
  4106. retry_succeeded = True
  4107. break
  4108. elif downloaded:
  4109. # Wrong plate again — discard and keep trying
  4110. try:
  4111. retry_temp_path.unlink(missing_ok=True)
  4112. except OSError:
  4113. pass
  4114. except FileNotOnPrinterError:
  4115. continue
  4116. except Exception as e:
  4117. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4118. if retry_succeeded:
  4119. break
  4120. # If the retry didn't find a matching file, drop the wrong 3MF
  4121. # so the no-3MF fallback below creates an archive whose name
  4122. # at least reflects the right plate.
  4123. if not retry_succeeded:
  4124. logger.warning(
  4125. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4126. expected_plate,
  4127. )
  4128. try:
  4129. temp_path.unlink(missing_ok=True)
  4130. except OSError:
  4131. pass
  4132. temp_path = None
  4133. downloaded_filename = None
  4134. # Whatever the sweep's transport did earlier, it is not why
  4135. # this archive ends up empty: a 3MF downloaded fine, it was
  4136. # just the wrong plate. Retrying would re-fetch that same
  4137. # contradicted file under the same stale names and hand it
  4138. # to _recover_fallback_archive, which checks that a
  4139. # candidate is a readable 3MF but not which plate it is --
  4140. # so the row would be filled in with another plate's
  4141. # filament and cost, the exact swap #2957 removed (#3063).
  4142. ftp_transfer_failed = False
  4143. # Disown the name for *lookups*: it has just been shown to
  4144. # fetch another plate's 3MF, and it keys `_active_prints`
  4145. # below, where the cover endpoint's own download of that
  4146. # same name would find this archive and fill it in with the
  4147. # file we are discarding here.
  4148. #
  4149. # Keep it for the *title*, which is a separate question.
  4150. # ``swap_plate_suffix`` returns None both for a name that
  4151. # carries no "- Plate N" / "_plate_N" suffix and for no
  4152. # name at all, and those are not the same situation: a name
  4153. # without a suffix holds no stale plate number to be wrong
  4154. # about. Blanking both uses at once dropped the project
  4155. # name too, and the row fell through to the gcode_file path
  4156. # titled "plate_1" though the real name was in hand.
  4157. # #1204's own premise is consecutive plates *of the same
  4158. # model*, so the project part is right either way (#3126).
  4159. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4160. subtask_name = corrected_subtask or ""
  4161. if not downloaded_filename or not temp_path:
  4162. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4163. # Create a fallback archive without 3MF data so the print is still tracked
  4164. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4165. try:
  4166. from backend.app.models.archive import PrintArchive
  4167. # Why the card is empty. The two temporary causes outrank the
  4168. # storage verdict because they say the sweep never got a fair
  4169. # answer: a cool-off skipped it at the transport, and a failed
  4170. # transfer reached the printer but never finished. Either way
  4171. # the file is still on the card, so reporting where the printer
  4172. # files its jobs would describe a setting that is not the
  4173. # problem (#2957, #3063).
  4174. if blocked_by_ftps_cooloff:
  4175. no_3mf_reason = REASON_FTPS_COOLOFF
  4176. elif storage.reachable and ftp_transfer_failed:
  4177. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4178. else:
  4179. no_3mf_reason = storage.reason
  4180. # Derive print name from subtask_name or filename. The
  4181. # plate guard's disowned name comes second: it is a real name
  4182. # for a real print, and only the gcode_file path is left
  4183. # otherwise -- which titles the row "plate_1" (#3126).
  4184. print_name = subtask_name or display_name_after_plate_reject or filename
  4185. if print_name:
  4186. # Clean up the name (remove extensions, path parts)
  4187. print_name = print_name.split("/")[-1]
  4188. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4189. else:
  4190. print_name = "Unknown Print"
  4191. # Recover estimated print time from MQTT (best-effort for notifications)
  4192. fallback_print_time = None
  4193. mqtt_remaining = data.get("remaining_time")
  4194. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4195. fallback_print_time = int(mqtt_remaining)
  4196. if fallback_print_time is None:
  4197. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4198. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4199. fallback_print_time = int(mc_remaining * 60)
  4200. # Best-effort filament metadata from MQTT — see
  4201. # _extract_filament_data_from_mqtt. Without this the fallback
  4202. # archive's filament fields stayed NULL even though the AMS
  4203. # state at print start was sitting right there in `data`.
  4204. # The slicer's ams_mapping (when present) narrows the result
  4205. # to slots actually used by the print (#1533).
  4206. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4207. # Create minimal archive entry
  4208. fallback_archive = PrintArchive(
  4209. printer_id=printer_id,
  4210. filename=filename or f"{print_name}.3mf",
  4211. file_path="", # Empty - no 3MF file available
  4212. file_size=0,
  4213. print_name=print_name,
  4214. print_time_seconds=fallback_print_time,
  4215. status="printing",
  4216. started_at=datetime.now(timezone.utc),
  4217. subtask_id=subtask_id,
  4218. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4219. filament_type=mqtt_filament_meta.get("filament_type"),
  4220. filament_color=mqtt_filament_meta.get("filament_color"),
  4221. extra_data={
  4222. "no_3mf_available": True,
  4223. # Why the card is empty, when we know -- see above. The
  4224. # banner reads this to stop telling H2/P2 owners to
  4225. # switch on a setting that is already on and would not
  4226. # have helped (#2780).
  4227. "no_3mf_reason": no_3mf_reason,
  4228. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4229. "_print_data": data,
  4230. },
  4231. )
  4232. db.add(fallback_archive)
  4233. await db.commit()
  4234. await db.refresh(fallback_archive)
  4235. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4236. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4237. # Track as active print
  4238. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4239. if filename:
  4240. _active_prints[(printer_id, filename)] = fallback_archive.id
  4241. if subtask_name:
  4242. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4243. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4244. # Record starting energy if smart plug available (#941: persisted column)
  4245. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4246. # Send WebSocket notification
  4247. await ws_manager.send_archive_created(
  4248. {
  4249. "id": fallback_archive.id,
  4250. "printer_id": fallback_archive.printer_id,
  4251. "filename": fallback_archive.filename,
  4252. "print_name": fallback_archive.print_name,
  4253. "status": fallback_archive.status,
  4254. }
  4255. )
  4256. # MQTT relay - publish archive created
  4257. try:
  4258. await mqtt_relay.on_archive_created(
  4259. archive_id=fallback_archive.id,
  4260. print_name=fallback_archive.print_name,
  4261. printer_name=printer.name,
  4262. status=fallback_archive.status,
  4263. )
  4264. except Exception:
  4265. pass # Don't fail if MQTT fails
  4266. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4267. try:
  4268. await _store_spoolman_print_data(
  4269. printer_id,
  4270. fallback_archive.id,
  4271. fallback_archive.file_path,
  4272. db,
  4273. printer_manager,
  4274. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4275. plate_id=_get_start_plate_id(fallback_archive.id),
  4276. )
  4277. except Exception as e:
  4278. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4279. # Both temporary give-ups are worth coming back for, and for
  4280. # the same reason: the file is on the printer and the last look
  4281. # failed at the transport rather than finding nothing. One waits
  4282. # out the handshake block (#2957), the other waits for the
  4283. # printer to stop being busy (#3063). Deliberately not scheduled
  4284. # for a storage verdict: a file on internal eMMC will not appear
  4285. # at any FTPS path however long we wait, and retrying it is
  4286. # exactly the sweep #2780 removed.
  4287. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4288. # `possible_names`, not the raw MQTT strings: it is the exact
  4289. # list this flow just tried, already stripped of any path
  4290. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4291. # some firmware) and deduped.
  4292. _schedule_fallback_3mf_retry(
  4293. printer_id=printer_id,
  4294. archive_id=fallback_archive.id,
  4295. filenames=list(possible_names),
  4296. reason=no_3mf_reason,
  4297. )
  4298. # Send notification without archive data (file not found)
  4299. if not notification_sent:
  4300. await _send_print_start_notification(printer_id, data, logger=logger)
  4301. # The same baseline the other two on_print_start branches take
  4302. # (#2704), and last for the same reason they are: it lists the
  4303. # printer's timelapse directory, so a slow card must not delay
  4304. # the _active_prints registration, the energy reading, the
  4305. # archive-created event or the start notification above it.
  4306. #
  4307. # This branch never took one, so every no-3MF archive reached
  4308. # completion with no baseline in memory and none on the row, and
  4309. # the completion scan fell into its "snapshot now" fallback --
  4310. # which runs after the printer has written the video, so the new
  4311. # file landed inside the baseline and no diff ever matched
  4312. # (#2957 follow-up).
  4313. #
  4314. # Skipped when the FTPS cool-off is what produced this fallback:
  4315. # the listing needs the same connection that just failed, so it
  4316. # could only record that the card was unreadable. The scan
  4317. # handles that case by refusing to choose between candidates.
  4318. if not blocked_by_ftps_cooloff:
  4319. await _capture_timelapse_baseline_at_start(
  4320. printer, printer_id, logger, archive_id=fallback_archive.id
  4321. )
  4322. return
  4323. except Exception as e:
  4324. logger.error("Failed to create fallback archive: %s", e)
  4325. # Send notification without archive data (file not found)
  4326. if not notification_sent:
  4327. await _send_print_start_notification(printer_id, data, logger=logger)
  4328. return
  4329. try:
  4330. # Archive the file with status "printing"
  4331. service = ArchiveService(db)
  4332. archive = await service.archive_print(
  4333. printer_id=printer_id,
  4334. source_file=temp_path,
  4335. print_data={**data, "status": "printing"},
  4336. subtask_id=subtask_id,
  4337. )
  4338. if archive:
  4339. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4340. # Set on the row rather than passed to archive_print, which also
  4341. # serves the queue dispatcher — there the queue item decides.
  4342. # Guarded because this branch has no ``except``: an unhandled
  4343. # write error would take the _active_prints registration, the
  4344. # start notification, the energy reading and the timelapse
  4345. # baseline below it with it, and a missing prompt is by far the
  4346. # cheaper failure.
  4347. try:
  4348. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4349. archive.confirm_requested = True
  4350. await db.commit()
  4351. except Exception as e:
  4352. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive.id, e)
  4353. try:
  4354. await db.rollback()
  4355. except Exception:
  4356. pass
  4357. # Track this active print (use both original filename and downloaded filename)
  4358. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4359. if filename and filename != downloaded_filename:
  4360. _active_prints[(printer_id, filename)] = archive.id
  4361. if subtask_name:
  4362. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4363. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4364. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4365. # Record starting energy from smart plug if available (#941: persisted column)
  4366. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4367. await ws_manager.send_archive_created(
  4368. {
  4369. "id": archive.id,
  4370. "printer_id": archive.printer_id,
  4371. "filename": archive.filename,
  4372. "print_name": archive.print_name,
  4373. "status": archive.status,
  4374. }
  4375. )
  4376. # MQTT relay - publish archive created
  4377. try:
  4378. await mqtt_relay.on_archive_created(
  4379. archive_id=archive.id,
  4380. print_name=archive.print_name,
  4381. printer_name=printer.name,
  4382. status=archive.status,
  4383. )
  4384. except Exception:
  4385. pass # Don't fail if MQTT fails
  4386. # Send notification with archive data (new archive created)
  4387. if not notification_sent:
  4388. archive_data = {
  4389. "print_time_seconds": archive.print_time_seconds,
  4390. "created_by_id": archive.created_by_id,
  4391. }
  4392. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4393. # Extract printable objects for skip object functionality
  4394. try:
  4395. from backend.app.services.archive import extract_printable_objects_from_3mf
  4396. client = printer_manager.get_client(printer_id)
  4397. if client:
  4398. with open(temp_path, "rb") as f:
  4399. threemf_data = f.read()
  4400. # Extract with positions for UI overlay, scoped to the
  4401. # plate that is printing — an all-plates 3MF carries
  4402. # every plate's objects (#2522).
  4403. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4404. threemf_data,
  4405. plate_number=resolve_plate_id(client.state),
  4406. include_positions=True,
  4407. )
  4408. if printable_objects:
  4409. # Store objects in printer state
  4410. client.state.printable_objects = printable_objects
  4411. client.state.printable_objects_bbox_all = bbox_all
  4412. client.state.skipped_objects = [] # Reset skipped objects for new print
  4413. logger.info(
  4414. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4415. )
  4416. except Exception as e:
  4417. logger.debug("Failed to extract printable objects: %s", e)
  4418. # Store Spoolman tracking data for per-filament usage reporting
  4419. try:
  4420. await _store_spoolman_print_data(
  4421. printer_id,
  4422. archive.id,
  4423. archive.file_path,
  4424. db,
  4425. printer_manager,
  4426. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4427. plate_id=_get_start_plate_id(archive.id),
  4428. )
  4429. except Exception as e:
  4430. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4431. # Capture timelapse file baseline for snapshot-diff on completion
  4432. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4433. finally:
  4434. # Keep temp_path around until print completes so the cover endpoint
  4435. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4436. # the file. If the cache entry was evicted early (file vanished),
  4437. # clean up any stragglers here to avoid leaking disk on retries.
  4438. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4439. if temp_path and temp_path.exists() and cached_now != temp_path:
  4440. temp_path.unlink()
  4441. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4442. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4443. # tests can shrink them without waiting out real delays.
  4444. #
  4445. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4446. # looking. Across 247 support bundles the attempt that found the video was #1
  4447. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4448. # decaying one, which is the signature of a budget that expires while files are
  4449. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4450. # prints make big videos and the printer writes them after the print ends, so
  4451. # the poll now runs for minutes and costs one FTP LIST per round.
  4452. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4453. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4454. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4455. def _timelapse_scan_max_attempts() -> int:
  4456. """Round cap for the poll, derived from the wall-clock budget.
  4457. The deadline alone is not a sufficient bound: it assumes each round really
  4458. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4459. and an FTP list that fails immediately would otherwise spin against the
  4460. printer at full speed for the whole window. Whichever bound is reached
  4461. first ends the poll.
  4462. """
  4463. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4464. # A zero interval makes the wall-clock budget meaningless; fall back to
  4465. # the round count the production interval would have given.
  4466. return 32
  4467. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4468. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4469. """Video filenames already attached to some other archive of this printer.
  4470. Used to disambiguate when more than one file is new since the baseline —
  4471. which happens when a previous print's video landed after this print's
  4472. baseline was taken. Ordering the candidates would be the obvious fix and is
  4473. the wrong one: it can only be done on mtime or on the filename timestamp,
  4474. both of which come from the printer's own clock, and a LAN-only printer
  4475. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4476. ``attach_timelapse`` saves the video into the archive directory under the
  4477. printer's original filename, and the later MP4 conversion keeps the stem,
  4478. so the stem of ``timelapse_path`` recovers what was claimed.
  4479. """
  4480. from backend.app.models.archive import PrintArchive
  4481. rows = await db.execute(
  4482. select(PrintArchive.timelapse_path).where(
  4483. PrintArchive.printer_id == printer_id,
  4484. PrintArchive.id != exclude_archive_id,
  4485. PrintArchive.timelapse_path.is_not(None),
  4486. )
  4487. )
  4488. return {Path(p).stem for p in rows.scalars().all() if p}
  4489. def _timelapse_listing_is_trustworthy(printer) -> bool:
  4490. """Whether an *empty* timelapse listing for *printer* can be believed.
  4491. ``list_files_async`` answers ``[]`` when its connect fails rather than
  4492. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  4493. from one holding no videos. Everywhere that only wants to know "is there a
  4494. video yet" the difference does not matter — both mean "not yet, retry".
  4495. It matters where an empty listing is recorded as a *baseline*. Recording
  4496. "the card held nothing" for a card that was never read means every video on
  4497. it counts as new once the cool-off expires, and the completion scan then
  4498. attaches a stale video to this print and deletes it from the printer
  4499. (#2957 follow-up). Those two callers ask this first.
  4500. """
  4501. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  4502. ip_address = getattr(printer, "ip_address", None)
  4503. if not ip_address:
  4504. return True
  4505. return not ftps_handshake_blocked(ip_address)
  4506. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  4507. """List video files from printer's timelapse directory.
  4508. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  4509. Returns (video_files, found_path) where video_files is a list of file dicts
  4510. and found_path is the directory where they were found, or ([], None).
  4511. An empty return does not distinguish "no videos" from "could not read the
  4512. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  4513. baseline callers consult before believing one.
  4514. """
  4515. from backend.app.services.bambu_ftp import list_files_async
  4516. logger = logging.getLogger(__name__)
  4517. # No card in the slot means no /timelapse to walk — four connections that
  4518. # can only fail, on a path whose failures are swallowed and so would go on
  4519. # costing time silently forever (#2780).
  4520. #
  4521. # ``getattr`` rather than ``printer.id``: every dereference below happens
  4522. # inside the loop's own try/except, so a caller that passed something
  4523. # unexpected used to get an empty listing rather than an exception. Keep
  4524. # that, instead of making this gate the first thing that can raise here.
  4525. printer_id = getattr(printer, "id", None)
  4526. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  4527. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  4528. return [], None
  4529. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  4530. try:
  4531. found_files = await list_files_async(
  4532. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  4533. )
  4534. if found_files:
  4535. video_files = [
  4536. f
  4537. for f in found_files
  4538. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  4539. ]
  4540. if video_files:
  4541. return video_files, timelapse_path
  4542. except Exception as e:
  4543. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  4544. continue
  4545. return [], None
  4546. async def _capture_timelapse_baseline_at_start(
  4547. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  4548. ) -> None:
  4549. """Snapshot the printer's timelapse directory at print start so the
  4550. completion-time scan can pick the new file by set-difference.
  4551. Must be called from every on_print_start path that proceeds to a real
  4552. print — both the new-archive branch and the expected-archive branch (which
  4553. queue / VP-dispatched prints take). Without a baseline,
  4554. _scan_for_timelapse_with_retries falls into its "take baseline now"
  4555. fallback that runs AFTER the new MP4 has already landed on the SD card,
  4556. so the new file ends up in the "baseline" set and no diff ever matches.
  4557. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  4558. unreliable — the snapshot-diff approach sidesteps that entirely.
  4559. When ``archive_id`` is known the baseline is also written to the archive
  4560. row, so it survives a restart and the manual "Scan for Timelapse" button
  4561. can run the same diff instead of falling back to clock-based matching
  4562. (#2704). Only baselines taken at print start are persisted — one taken at
  4563. completion already contains the new video and would poison a later scan.
  4564. """
  4565. names: set[str] | None = None
  4566. try:
  4567. if not _timelapse_listing_is_trustworthy(printer):
  4568. # Recorded anyway, deliberately. An empty baseline taken off a card
  4569. # we could not read is not authoritative, but it is still the right
  4570. # *default*: Bambuddy deletes each video from the printer once it is
  4571. # attached, so the usual card holds exactly one video at completion
  4572. # and an empty baseline resolves it correctly. Persisting NULL
  4573. # instead would send completion to take its own snapshot, by which
  4574. # point this print's video is on the card and would be swallowed by
  4575. # it. The ambiguity is handled where it actually bites — see
  4576. # ``require_unambiguous`` in the scan (#2957 follow-up).
  4577. logger.warning(
  4578. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  4579. "handshake cool-off, so the card could not be read — treating it as empty",
  4580. printer_id,
  4581. )
  4582. baseline_files, _ = await _list_timelapse_videos(printer)
  4583. names = {f.get("name", "") for f in baseline_files}
  4584. _timelapse_baselines[printer_id] = names
  4585. logger.info(
  4586. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  4587. len(names),
  4588. printer_id,
  4589. )
  4590. except Exception as e:
  4591. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  4592. if archive_id is None:
  4593. return
  4594. try:
  4595. async with async_session() as db:
  4596. from backend.app.models.archive import PrintArchive
  4597. archive = await db.get(PrintArchive, archive_id)
  4598. if archive is not None:
  4599. # Written even when the listing failed, and then as NULL. A
  4600. # reprint reuses the archive row, so leaving the previous run's
  4601. # baseline in place would have the scan diff this print against
  4602. # the state of the printer before the *last* one — and a stale
  4603. # baseline reads as authoritative, where NULL correctly falls
  4604. # back to a fresh snapshot.
  4605. archive.timelapse_baseline = sorted(names) if names is not None else None
  4606. await db.commit()
  4607. except Exception as e:
  4608. # In-memory baseline still covers the normal completion path.
  4609. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  4610. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  4611. """Poll the printer for this print's timelapse and attach it.
  4612. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  4613. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  4614. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  4615. (#2704). Comparing the current listing against the set of filenames that
  4616. existed when the print started needs no clock at all, because the printer
  4617. writes the video only once the print has ended.
  4618. Baseline precedence: the caller's in-memory set, then the one persisted on
  4619. the archive at print start, then a snapshot taken now. The last of those is
  4620. a poor substitute — by completion the new video may already be on the card,
  4621. in which case it lands in the "baseline" and no diff can ever match — but it
  4622. is all that is available for a print that began before Bambuddy started.
  4623. On success the video is deleted from the printer, which keeps ``/timelapse``
  4624. down to the unclaimed files and makes the next diff unambiguous.
  4625. """
  4626. logger = logging.getLogger(__name__)
  4627. # Cleared when the baseline had to be taken off a card we could not read, so
  4628. # the attach step refuses to choose between several candidates (#2957).
  4629. baseline_trusted = True
  4630. # --- Phase 1: establish the baseline -------------------------------------
  4631. try:
  4632. async with async_session() as db:
  4633. from backend.app.models.printer import Printer
  4634. service = ArchiveService(db)
  4635. archive = await service.get_archive(archive_id)
  4636. if not archive:
  4637. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  4638. return
  4639. if archive.timelapse_path:
  4640. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  4641. return
  4642. if not archive.printer_id:
  4643. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  4644. return
  4645. if baseline_names is not None:
  4646. logger.info(
  4647. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  4648. len(baseline_names),
  4649. archive_id,
  4650. )
  4651. elif archive.timelapse_baseline is not None:
  4652. # Persisted at print start — survives a restart mid-print.
  4653. baseline_names = set(archive.timelapse_baseline)
  4654. logger.info(
  4655. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  4656. len(baseline_names),
  4657. archive_id,
  4658. )
  4659. else:
  4660. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4661. printer = result.scalar_one_or_none()
  4662. if not printer:
  4663. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  4664. return
  4665. if not _timelapse_listing_is_trustworthy(printer):
  4666. # The card is unreadable at the one moment a baseline has to
  4667. # be taken, so the empty listing below means "we never
  4668. # looked", not "these are all new". Carry on with it anyway
  4669. # — the usual card holds exactly one video, which resolves
  4670. # correctly — but stop the poll from *choosing* between
  4671. # several, which is how a stale video got attached to this
  4672. # print and then deleted off the printer (#2957 follow-up).
  4673. baseline_trusted = False
  4674. logger.warning(
  4675. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  4676. "handshake cool-off. A single new video still resolves; several will not be "
  4677. "guessed between — use Scan for Timelapse to pick one by hand",
  4678. archive_id,
  4679. archive.printer_id,
  4680. )
  4681. baseline_files, _ = await _list_timelapse_videos(printer)
  4682. baseline_names = {f.get("name", "") for f in baseline_files}
  4683. logger.info(
  4684. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  4685. len(baseline_names),
  4686. archive_id,
  4687. )
  4688. except Exception as e:
  4689. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  4690. return
  4691. # --- Phase 2: poll for a file that was not there when the print began -----
  4692. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  4693. max_attempts = _timelapse_scan_max_attempts()
  4694. seen_names: set[str] = set()
  4695. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  4696. attempt = 0
  4697. while True:
  4698. await asyncio.sleep(delay)
  4699. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  4700. attempt += 1
  4701. try:
  4702. from backend.app.models.printer import Printer
  4703. # Read phase: fetch archive + printer in a short session and release
  4704. # the pooled connection BEFORE the FTP list/download below. Holding it
  4705. # across the FTP round-trips left one connection idle-in-transaction per
  4706. # in-flight scan (issue #2572).
  4707. async with async_session() as db:
  4708. service = ArchiveService(db)
  4709. archive = await service.get_archive(archive_id)
  4710. if not archive:
  4711. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  4712. return
  4713. if archive.timelapse_path:
  4714. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  4715. return
  4716. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4717. printer = result.scalar_one_or_none()
  4718. if not printer:
  4719. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  4720. return
  4721. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  4722. # I/O phase (no DB connection held): FTP list + download.
  4723. video_files, found_path = await _list_timelapse_videos(printer)
  4724. # The poll can run for dozens of rounds, so only narrate a round
  4725. # that saw something change. Repeating the whole listing every 30 s
  4726. # would bury the one interesting line in the support bundle.
  4727. names_now = {f.get("name", "") for f in video_files}
  4728. changed = attempt == 1 or names_now != seen_names
  4729. seen_names = names_now
  4730. speak = logger.info if changed else logger.debug
  4731. if video_files:
  4732. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  4733. if changed:
  4734. for f in video_files[:5]:
  4735. logger.info("[TIMELAPSE] - %s", f.get("name"))
  4736. attached = await _attach_first_unclaimed_timelapse(
  4737. archive_id,
  4738. printer,
  4739. video_files,
  4740. baseline_names,
  4741. claimed,
  4742. attempt,
  4743. logger,
  4744. quiet=not changed,
  4745. require_unambiguous=not baseline_trusted,
  4746. )
  4747. if attached:
  4748. return
  4749. else:
  4750. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  4751. except Exception as e:
  4752. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  4753. if attempt >= max_attempts or time.monotonic() >= deadline:
  4754. break
  4755. # No name-match fallback: it compared the print name against the filename,
  4756. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  4757. # bundles it fired 159 times and matched zero times, so all it added was a
  4758. # misleading log line before giving up.
  4759. logger.warning(
  4760. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  4761. archive_id,
  4762. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  4763. )
  4764. async def _attach_first_unclaimed_timelapse(
  4765. archive_id: int,
  4766. printer,
  4767. video_files: list[dict],
  4768. baseline_names: set[str],
  4769. claimed: set[str],
  4770. attempt: int,
  4771. logger: logging.Logger,
  4772. *,
  4773. quiet: bool = False,
  4774. require_unambiguous: bool = False,
  4775. ) -> bool:
  4776. """Download and attach the one video that belongs to this print.
  4777. A candidate is any file absent from the print-start baseline. More than one
  4778. can qualify when a previous print's video landed late, after this print's
  4779. baseline was taken — those are filtered out by name, because they are
  4780. already attached to another archive. Sorting the candidates instead would
  4781. mean sorting on mtime or on the filename timestamp, both of which come from
  4782. the printer's unsynced clock.
  4783. Returns True once a video is attached. The printer's copy is deleted only
  4784. after the attach succeeds on bytes whose length matched the listing.
  4785. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  4786. already seen this exact listing — the poll runs for many rounds and only the
  4787. rounds where something changed are worth an INFO line.
  4788. """
  4789. from backend.app.services.bambu_ftp import (
  4790. delete_archived_timelapse,
  4791. download_file_bytes_async,
  4792. remote_file_settled,
  4793. )
  4794. speak = logger.debug if quiet else logger.info
  4795. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  4796. if not new_files:
  4797. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  4798. return False
  4799. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  4800. if not candidates:
  4801. speak(
  4802. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  4803. attempt,
  4804. len(new_files),
  4805. )
  4806. return False
  4807. if len(candidates) > 1:
  4808. if require_unambiguous:
  4809. # The baseline is not evidence -- it was taken off a card that could
  4810. # not be read -- so "new since the baseline" does not narrow these
  4811. # down at all. Taking the first would attach an arbitrary video to
  4812. # this print and then delete it from the printer.
  4813. logger.warning(
  4814. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  4815. "leaving all of them on the printer for manual selection",
  4816. attempt,
  4817. len(candidates),
  4818. ", ".join(str(f.get("name")) for f in candidates),
  4819. )
  4820. return False
  4821. logger.warning(
  4822. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  4823. "the rest stay on the printer for manual selection",
  4824. attempt,
  4825. len(candidates),
  4826. ", ".join(str(f.get("name")) for f in candidates),
  4827. )
  4828. target = candidates[0]
  4829. file_name = target.get("name")
  4830. remote_path = target.get("path") or f"/timelapse/{file_name}"
  4831. logger.info(
  4832. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  4833. attempt,
  4834. file_name,
  4835. archive_id,
  4836. )
  4837. # The listing always carries a size (`list_files` skips entries it can't
  4838. # parse), but read it explicitly: the delete below is destructive and must
  4839. # depend on a size we actually had, not on one we hoped was there.
  4840. expected_size = target.get("size")
  4841. timelapse_data = await download_file_bytes_async(
  4842. printer.ip_address,
  4843. printer.access_code,
  4844. remote_path,
  4845. printer_model=printer.model,
  4846. expected_size=expected_size,
  4847. )
  4848. if not timelapse_data:
  4849. # Short or failed transfer. The printer keeps its copy, so the next
  4850. # round can try again — which is exactly why the delete below is
  4851. # gated on a verified download.
  4852. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  4853. return False
  4854. # The length check above proves we got what the listing said, not that the
  4855. # printer had finished writing. A video still being written can be listed
  4856. # short, served short, and pass — so confirm it has stopped growing before
  4857. # committing to it and deleting the original (#2704).
  4858. if not await remote_file_settled(
  4859. printer.ip_address,
  4860. printer.access_code,
  4861. remote_path,
  4862. len(timelapse_data),
  4863. printer_model=printer.model,
  4864. ):
  4865. return False
  4866. # Write phase: attach in a fresh short-lived session.
  4867. async with async_session() as db:
  4868. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  4869. if not success:
  4870. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  4871. return False
  4872. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  4873. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  4874. await delete_archived_timelapse(
  4875. printer.ip_address,
  4876. printer.access_code,
  4877. remote_path,
  4878. verified=expected_size is not None,
  4879. printer_model=printer.model,
  4880. printer_name=printer.name,
  4881. )
  4882. return True
  4883. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  4884. # module-level so tests can monkeypatch them down to ~0 without timing out.
  4885. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  4886. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  4887. # How long the *background* upgrade keeps waiting after the notification has
  4888. # already gone out (#2704 follow-up). The short bound above exists so a slow
  4889. # printer can't hold up the print-complete notification; this one exists so the
  4890. # archive still ends up with the better frame afterwards.
  4891. #
  4892. # Measured across 261 attaches in the support bundles, the video lands a median
  4893. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  4894. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  4895. # was 546s. Every other model was inside 26s. The long budget is therefore
  4896. # almost entirely for P1-series users; on everything else the short wait already
  4897. # wins and this task never runs.
  4898. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  4899. async def _capture_finish_photo_from_timelapse(
  4900. archive_id: int,
  4901. archive_dir: Path,
  4902. timeout: float | None = None,
  4903. rotation: int = 0,
  4904. ) -> tuple[str | None, bool]:
  4905. """Wait for the per-print timelapse to land on the archive and extract its
  4906. last frame as the finish photo (#1397).
  4907. Bambu firmware stops timelapse recording after the toolhead parks but
  4908. before the bed-drop end-gcode runs, so the last frame frames the finished
  4909. print correctly. A live camera grab at gcode_state=FINISH captures the
  4910. bed already lowered.
  4911. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  4912. ``archive.timelapse_path`` when the file lands. This function polls for
  4913. that field.
  4914. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  4915. the wait ran out with no video on the archive yet — i.e. the video may
  4916. still be coming and a later attempt could succeed. It is False when the
  4917. video landed (whether or not extraction worked), because in that case
  4918. waiting longer changes nothing. The caller uses that to decide between
  4919. falling back permanently and scheduling a background upgrade.
  4920. ``rotation`` is the printer's camera_rotation, applied to the extracted
  4921. still (#2708) so this source agrees with every other finish-photo source.
  4922. The archived video itself is the printer's own file and is left alone —
  4923. rotating it would mean re-encoding it.
  4924. """
  4925. import uuid
  4926. from backend.app.models.archive import PrintArchive
  4927. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  4928. logger = logging.getLogger(__name__)
  4929. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  4930. deadline = asyncio.get_event_loop().time() + budget
  4931. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  4932. while True:
  4933. async with async_session() as db:
  4934. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4935. archive = result.scalar_one_or_none()
  4936. timelapse_relpath = archive.timelapse_path if archive else None
  4937. if timelapse_relpath:
  4938. video_path = app_settings.base_dir / timelapse_relpath
  4939. if video_path.exists() and video_path.stat().st_size > 0:
  4940. photos_dir = archive_dir / "photos"
  4941. photos_dir.mkdir(parents=True, exist_ok=True)
  4942. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4943. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4944. output_path = photos_dir / filename
  4945. if await extract_video_last_frame(video_path, output_path):
  4946. await apply_camera_rotation_to_file(output_path, rotation, logger)
  4947. logger.info(
  4948. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  4949. video_path.name,
  4950. archive_id,
  4951. )
  4952. return filename, False
  4953. logger.warning(
  4954. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  4955. video_path.name,
  4956. archive_id,
  4957. )
  4958. return None, False
  4959. if asyncio.get_event_loop().time() >= deadline:
  4960. logger.info(
  4961. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  4962. archive_id,
  4963. budget,
  4964. )
  4965. return None, True
  4966. await asyncio.sleep(poll_interval)
  4967. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  4968. """Add the timelapse's last frame to an archive after the fact (#2704).
  4969. The print-complete notification waits only ~60s for the video, because
  4970. holding a notification for minutes is worse than sending it with a live
  4971. camera grab. On a P1-series printer the video often lands well after that,
  4972. so the archive used to be stuck with the live grab — which is taken at
  4973. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  4974. the worse photo of the two.
  4975. This keeps waiting in the background and, when the video arrives, extracts
  4976. the frame and puts it *first* in the archive's photo list, so opening the
  4977. gallery shows it. The live grab is deliberately kept: the notification that
  4978. already went out links to that exact file, and deleting it would leave a
  4979. broken image in Discord or Telegram.
  4980. """
  4981. logger = logging.getLogger(__name__)
  4982. filename, _ = await _capture_finish_photo_from_timelapse(
  4983. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  4984. )
  4985. if not filename:
  4986. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  4987. return
  4988. try:
  4989. async with async_session() as db:
  4990. from backend.app.models.archive import PrintArchive
  4991. archive = await db.get(PrintArchive, archive_id)
  4992. if archive is None:
  4993. return
  4994. photos = list(archive.photos or [])
  4995. if filename in photos:
  4996. return
  4997. # Front of the list: PhotoGalleryModal opens at index 0.
  4998. archive.photos = [filename, *photos]
  4999. await db.commit()
  5000. except Exception as e:
  5001. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5002. return
  5003. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5004. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5005. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5006. """Put the filament-attribution context back after a restart mid-print.
  5007. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5008. both die with the process. The print keeps running, so at completion the
  5009. tracker would fall back to whatever the printer reports *now* — and AMS
  5010. filament backup makes "now" the substitute tray, charging the whole print
  5011. to the spool that only finished it.
  5012. The persisted row is only trusted when its print name still matches what
  5013. the printer says it is running: a row left behind by a completion we never
  5014. saw must not attach itself to the next print.
  5015. """
  5016. try:
  5017. from backend.app.api.routes.settings import get_setting
  5018. from backend.app.services.usage_tracker import (
  5019. clear_persisted_session,
  5020. get_persisted_print_name,
  5021. restore_session,
  5022. )
  5023. persisted_name = await get_persisted_print_name(db, printer_id)
  5024. current_name = (state.subtask_name or "").strip()
  5025. if persisted_name and current_name and persisted_name.strip() != current_name:
  5026. logger.info(
  5027. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5028. printer_id,
  5029. persisted_name,
  5030. current_name,
  5031. )
  5032. await clear_persisted_session(db, printer_id)
  5033. # Fall through to seeding: the print on the printer is real, it just
  5034. # isn't the one the row described.
  5035. persisted_log = None
  5036. else:
  5037. # Spoolman users get the tray-change log back but no in-memory
  5038. # session — see ``on_print_start`` on why that dict is load-bearing
  5039. # for the remain%-sync guard.
  5040. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5041. persisted_log = await restore_session(
  5042. db,
  5043. printer_id,
  5044. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5045. )
  5046. if persisted_log:
  5047. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5048. # Anything this process already observed goes after the persisted
  5049. # history — the log is ordered by layer, and a fresh process can
  5050. # only have seen changes from later in the print.
  5051. for entry in state.tray_change_log or []:
  5052. if tuple(entry) not in restored:
  5053. restored.append(tuple(entry))
  5054. state.tray_change_log = restored
  5055. tray_now = state.tray_now
  5056. if 0 <= tray_now <= 254:
  5057. if not state.tray_change_log:
  5058. # No persisted history — a print that started before this build,
  5059. # or before the row existed. Seed with the tray feeding right
  5060. # now so the remainder of the print is at least attributable to
  5061. # the right spool.
  5062. state.tray_change_log = [(tray_now, state.layer_num)]
  5063. logger.info(
  5064. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5065. printer_id,
  5066. tray_now,
  5067. state.layer_num,
  5068. )
  5069. # The tray handler updates ``last_loaded_tray`` on every push
  5070. # regardless of whether it logged a change, so re-align it to avoid
  5071. # a duplicate entry on the next push. Only ever with a real tray:
  5072. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5073. # 255" fallback, and writing 255 into it would defeat that.
  5074. state.last_loaded_tray = tray_now
  5075. except Exception:
  5076. # Never let attribution recovery cost the caller its timelapse
  5077. # baseline — that capture has to happen before the printer uploads
  5078. # the in-flight MP4 and there is no second chance at it.
  5079. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5080. async def on_print_running_observed(printer_id: int, data: dict):
  5081. """Restart-recovery for a print that started before Bambuddy came up.
  5082. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5083. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5084. creation). This hook restores the persisted archive into ``_active_prints``
  5085. and captures the timelapse baseline that normally hangs off print start.
  5086. Fires once per session, in lieu of on_print_start when restart-recovery
  5087. kicks in. The printer doesn't upload the timelapse until after PRINT
  5088. COMPLETE, so a baseline captured any time during the print is still
  5089. pre-upload.
  5090. """
  5091. logger = logging.getLogger(__name__)
  5092. async with async_session() as db:
  5093. from backend.app.models.printer import Printer
  5094. state = printer_manager.get_status(printer_id)
  5095. if state is not None:
  5096. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5097. if authorization is True:
  5098. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5099. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5100. await _restore_printable_objects(printer_id, state, db, logger)
  5101. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5102. printer = result.scalar_one_or_none()
  5103. if not printer:
  5104. logger.warning(
  5105. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5106. printer_id,
  5107. )
  5108. return
  5109. # Avoid double-capture: ownership reconciliation above must still run when
  5110. # a baseline already exists, but the camera work itself is one-shot.
  5111. if printer_id in _timelapse_baselines:
  5112. logger.debug(
  5113. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5114. printer_id,
  5115. )
  5116. return
  5117. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5118. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5119. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5120. against the printer's current MQTT state.
  5121. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5122. COMPLETE events, typically a print finishing during an MQTT disconnect
  5123. window followed by a smart-plug power cycle):
  5124. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5125. provably not running anymore — only branch that should fire under
  5126. normal disconnect-then-reconnect timing.
  5127. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5128. firmware mints a fresh ``subtask_id`` for each print, including the
  5129. ghost replay it runs after a power cycle from a leftover SD file —
  5130. so a mismatch unambiguously means the in-DB archive is no longer
  5131. the print on the printer.
  5132. 3. Printer is running but ``subtask_name`` is empty. The printer
  5133. doesn't know what it's running; the archive's reference to it is
  5134. already broken.
  5135. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5136. with matching subtask_id+subtask_name is left alone. The cost of a false
  5137. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5138. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5139. clears on synthesis, so the real completion creates a fresh row instead
  5140. of overwriting the synthesised one (#1679). The cost of a false negative
  5141. is the ghost-print loop in #1542.
  5142. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5143. MQTT has connected but the first ``push_status`` response hasn't been
  5144. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5145. The reconcile caller in ``on_printer_status_change`` is already gated
  5146. on a real ``state.state``, so in normal operation this branch is
  5147. unreachable; it's kept as belt-and-braces for future callers and for
  5148. the narrow window where a partial state update could arrive
  5149. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5150. ``not stale`` on degenerate input is strictly conservative: a real
  5151. stale archive will still be caught by the next push_status arriving
  5152. with terminal state.
  5153. """
  5154. current_state = (state.state or "").upper()
  5155. if current_state in ("", "UNKNOWN"):
  5156. # No real push_status yet — PrinterState defaults are not evidence.
  5157. return False, ""
  5158. if current_state in ("IDLE", "FINISH", "FAILED"):
  5159. return True, f"printer state {current_state}"
  5160. # Below here the printer is in a running / pre-running state (RUNNING /
  5161. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5162. current_subtask_id = (state.subtask_id or "").strip()
  5163. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5164. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5165. current_subtask_name = (state.subtask_name or "").strip()
  5166. if not current_subtask_name:
  5167. return True, "printer subtask_name empty"
  5168. return False, ""
  5169. async def prime_kprofile_table(printer_id: int) -> int:
  5170. """Read the printer's calibration table once per connection.
  5171. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5172. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5173. report ``cali_idx`` and nothing else -- that number can only come from
  5174. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5175. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5176. backup, or the printer answering a query BambuStudio made on the report
  5177. topic we share. A Bambuddy that nobody visited showed a card with no K
  5178. values at all.
  5179. Only the diameters actually fitted are asked for, which is one request on a
  5180. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5181. what the backup does, and it is both wasteful and the thing that used to
  5182. blank the table.
  5183. Returns the number of nozzles whose table was read.
  5184. """
  5185. client = printer_manager.get_client(printer_id)
  5186. state = printer_manager.get_status(printer_id)
  5187. if client is None or state is None or not state.connected:
  5188. return 0
  5189. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5190. # ask once, and both entries are empty until the first push_status lands.
  5191. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5192. if not diameters:
  5193. logging.getLogger(__name__).debug(
  5194. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5195. printer_id,
  5196. )
  5197. return 0
  5198. primed = 0
  5199. for diameter in diameters:
  5200. try:
  5201. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5202. except Exception as exc: # noqa: BLE001
  5203. # A printer that won't answer costs the card its K values, nothing
  5204. # more — never the connection this runs on the back of.
  5205. logging.getLogger(__name__).warning(
  5206. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5207. )
  5208. continue
  5209. primed += 1
  5210. logging.getLogger(__name__).info(
  5211. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5212. )
  5213. return primed
  5214. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5215. """Synthesise ``on_print_complete`` for archives whose print can't be
  5216. running on the printer anymore.
  5217. Called once per MQTT (re)connection (from on_printer_status_change when
  5218. the connected edge flips False → True) and at Bambuddy startup (from
  5219. the FastAPI lifespan). Without this, a print that completes during a
  5220. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5221. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5222. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5223. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5224. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5225. closes the loop by faking the missed PRINT COMPLETE — the existing
  5226. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5227. and notifications.
  5228. Synthesised ``status="aborted"`` is the conservative label: we have no
  5229. proof the print finished successfully (and no progress evidence to
  5230. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5231. fires later, overwrites the status with the correct value.
  5232. Returns the number of archives reconciled.
  5233. """
  5234. state = printer_manager.get_status(printer_id)
  5235. if not state:
  5236. return 0
  5237. # Don't reconcile while disconnected — we'd be making a decision against
  5238. # stale cached state. The connected → reconcile edge handles this.
  5239. if not state.connected:
  5240. return 0
  5241. from backend.app.models.archive import PrintArchive
  5242. reconciled = 0
  5243. async with async_session() as db:
  5244. result = await db.execute(
  5245. select(PrintArchive).where(
  5246. PrintArchive.printer_id == printer_id,
  5247. PrintArchive.status == "printing",
  5248. )
  5249. )
  5250. active = list(result.scalars().all())
  5251. if not active:
  5252. return 0
  5253. logger = logging.getLogger(__name__)
  5254. for archive in active:
  5255. is_stale, reason = _is_active_archive_stale(archive, state)
  5256. if not is_stale:
  5257. continue
  5258. logger.info(
  5259. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5260. printer_id,
  5261. archive.id,
  5262. archive.filename,
  5263. reason,
  5264. )
  5265. # Synthesised payload: minimal fields the on_print_complete chain
  5266. # needs. `_reconciled` marker lets downstream code distinguish this
  5267. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5268. # metrics / debug logging). raw_data is the live printer state so
  5269. # the usage tracker can compare end-of-print remain% against the
  5270. # captured start values.
  5271. try:
  5272. await on_print_complete(
  5273. printer_id,
  5274. {
  5275. "status": "aborted",
  5276. "filename": archive.filename,
  5277. "subtask_name": archive.print_name or "",
  5278. "subtask_id": archive.subtask_id or "",
  5279. "raw_data": state.raw_data or {},
  5280. "_reconciled": True,
  5281. },
  5282. )
  5283. reconciled += 1
  5284. except Exception as e:
  5285. # Catch-all: a reconciliation failure must not block the
  5286. # printer's normal status flow. The archive stays in
  5287. # ``status="printing"`` and the next reconnect retries.
  5288. logger.warning(
  5289. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5290. archive.id,
  5291. e,
  5292. )
  5293. return reconciled
  5294. # #2547: clearance left between the nozzle and the top of the print when the
  5295. # plate is commanded back into camera framing. The nozzle is parked away from
  5296. # the part by then, so this is belt-and-braces against a max_z_height that
  5297. # under-reports (e.g. a slicer that excludes a final Z hop).
  5298. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5299. # How far below the restored position to drop the plate again afterwards, so
  5300. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5301. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5302. # on machines with less headroom.
  5303. _PLATE_PARK_DROP_MM = 100.0
  5304. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5305. # this axis, so it is a proven-safe speed for the full travel.
  5306. _PLATE_RESTORE_FEEDRATE = 600
  5307. # Time allowed for the plate to reach the restored position before the camera
  5308. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5309. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5310. # How long `_background_finish_photo` waits for this producer. Must cover the
  5311. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5312. # notification path's own photo wait so a slow producer degrades to a
  5313. # photo-less notification rather than a missed one.
  5314. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5315. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  5316. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5317. This number becomes the target of a real Z move, so every step here refuses
  5318. rather than guesses. A height belonging to some *other* print is the one
  5319. failure that could drive the nozzle into the model: 20 mm carried onto a
  5320. 200 mm print would command the plate up through the part.
  5321. Two independent things therefore have to agree before a height is returned:
  5322. 1. **Identity.** The archive is matched by the finished print's own
  5323. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  5324. resolve to "Cube v2". Matching on "most recent archive for this printer"
  5325. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  5326. binding concurrently with us, and a print Bambuddy failed to archive
  5327. would silently resolve to its predecessor.
  5328. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5329. match the layer count the printer itself reported over MQTT for the print
  5330. that just ended. These come from genuinely different sources, so a
  5331. mismatch means the row is not this print, whatever its name says.
  5332. ``completed`` is accepted alongside ``printing`` only because
  5333. ``on_print_complete`` may already have flipped the status by the time we
  5334. run; the identity check above is what actually selects the row.
  5335. """
  5336. subtask_name = (data.get("subtask_name") or "").strip()
  5337. if not subtask_name:
  5338. # Nothing to identify the print by — refuse rather than fall back to
  5339. # "whatever ran last on this printer".
  5340. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5341. return None
  5342. try:
  5343. from backend.app.models.archive import PrintArchive
  5344. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5345. async with async_session() as db:
  5346. result = await db.execute(
  5347. select(PrintArchive)
  5348. .where(
  5349. PrintArchive.printer_id == printer_id,
  5350. PrintArchive.status.in_(("printing", "completed")),
  5351. PrintArchive.deleted_at.is_(None),
  5352. or_(
  5353. PrintArchive.print_name == subtask_name,
  5354. PrintArchive.filename == subtask_name,
  5355. PrintArchive.filename == f"{subtask_name}.3mf",
  5356. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  5357. ),
  5358. )
  5359. .order_by(PrintArchive.id.desc())
  5360. .limit(1)
  5361. )
  5362. archive = result.scalar_one_or_none()
  5363. if archive is None or not archive.file_path:
  5364. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  5365. return None
  5366. client = printer_manager.get_client(printer_id)
  5367. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  5368. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  5369. logger.warning(
  5370. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  5371. "— refusing to move the plate on a height that may not be this print's",
  5372. printer_id,
  5373. archive.id,
  5374. archive.total_layers,
  5375. reported_layers,
  5376. )
  5377. return None
  5378. path = Path(archive.file_path)
  5379. if not path.is_absolute():
  5380. path = Path(app_settings.data_dir) / path
  5381. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  5382. except Exception as e:
  5383. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  5384. return None
  5385. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  5386. """Raise the plate back into camera framing before the finish photo (#2547).
  5387. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  5388. the time ``gcode_state`` reaches FINISH the finished print sits far below
  5389. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  5390. This commands an absolute ``G1 Z`` back to just above the last printed
  5391. layer.
  5392. Absolute, not relative, is the whole safety argument. ``max_z_height +
  5393. clearance`` is a height the toolhead was physically at seconds earlier, so
  5394. it is inside the travel limits by construction and leaves the nozzle above
  5395. the part. It is also unambiguous across model families: Z is the
  5396. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  5397. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  5398. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  5399. (#2579).
  5400. Returns True if the move was sent and waited out, False if it was skipped.
  5401. """
  5402. client = printer_manager.get_client(printer_id)
  5403. if client is None:
  5404. return False
  5405. # Re-read state immediately before commanding motion. If the queue has
  5406. # already started the next print, the printer is no longer ours to move.
  5407. state = getattr(client, "state", None)
  5408. if state is None or state.state != "FINISH":
  5409. logger.info(
  5410. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  5411. printer_id,
  5412. getattr(state, "state", "unknown"),
  5413. )
  5414. return False
  5415. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  5416. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  5417. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  5418. return False
  5419. logger.info(
  5420. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  5421. printer_id,
  5422. target_z,
  5423. max_z_height,
  5424. _PLATE_RESTORE_CLEARANCE_MM,
  5425. _PLATE_RESTORE_SETTLE_SECONDS,
  5426. )
  5427. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  5428. return True
  5429. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  5430. """Drop the plate again after the finish photo (#2547).
  5431. Without this the user walks up to a finished print sitting just under the
  5432. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  5433. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  5434. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  5435. print homes anyway.
  5436. """
  5437. client = printer_manager.get_client(printer_id)
  5438. state = getattr(client, "state", None) if client else None
  5439. if client is None or state is None or state.state != "FINISH":
  5440. return
  5441. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  5442. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  5443. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  5444. """True if a queue item is about to take this printer (#2547).
  5445. The scheduler dispatches the next job the moment a print completes, and a
  5446. plate move interleaved with a print start is not a race worth having. The
  5447. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  5448. this window; this closes the head of it.
  5449. """
  5450. try:
  5451. from backend.app.models.print_queue import PrintQueueItem
  5452. async with async_session() as db:
  5453. result = await db.execute(
  5454. select(PrintQueueItem.id)
  5455. .where(
  5456. PrintQueueItem.printer_id == printer_id,
  5457. PrintQueueItem.status.in_(("pending", "printing")),
  5458. )
  5459. .limit(1)
  5460. )
  5461. return result.scalar_one_or_none() is not None
  5462. except Exception as e:
  5463. # Fail closed: if we can't tell, don't move the plate.
  5464. logging.getLogger(__name__).debug(
  5465. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  5466. )
  5467. return True
  5468. async def on_finish_photo_moment(printer_id: int, data: dict):
  5469. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  5470. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  5471. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  5472. fallback for prints that skip stage 22 (cancel, external-spool-only,
  5473. HMS halt, firmware variants). Grabs one frame via the same
  5474. external-camera / RTSP path the post-completion fallback uses, stores
  5475. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  5476. ``_background_finish_photo`` consume the cached bytes when it runs.
  5477. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  5478. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  5479. set to Smooth (#1721). No force-on now means the user's explicit
  5480. timelapse=off in the slicer send dialog is respected.
  5481. """
  5482. logger = logging.getLogger(__name__)
  5483. trigger = data.get("trigger", "unknown")
  5484. timelapse_was_active = bool(data.get("timelapse_was_active"))
  5485. logger.info(
  5486. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  5487. printer_id,
  5488. trigger,
  5489. timelapse_was_active,
  5490. )
  5491. # If a timelapse is actively recording, skip the pre-capture — the
  5492. # post-completion path will extract the last frame from the recorded
  5493. # video, which still provides the best framing (toolhead parked,
  5494. # before bed drop) without the per-layer parking side effects.
  5495. if timelapse_was_active:
  5496. logger.info(
  5497. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  5498. printer_id,
  5499. )
  5500. return
  5501. # #1790: register the producer-done event BEFORE the first await so the
  5502. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  5503. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  5504. # The `finally` below guarantees `set()` runs on every exit, including
  5505. # early returns and exceptions, so the consumer's bounded wait can't hang.
  5506. producer_done = asyncio.Event()
  5507. _stage22_finish_in_flight[printer_id] = producer_done
  5508. # #2547: set once the plate has actually been raised, and read by the
  5509. # `finally` below. Declared out here so a failure anywhere after the move —
  5510. # a camera timeout, a DB error — still lowers the plate again.
  5511. restore_max_z: float | None = None
  5512. try:
  5513. async with async_session() as db:
  5514. from backend.app.api.routes.settings import get_setting
  5515. from backend.app.models.printer import Printer
  5516. capture_setting = await get_setting(db, "capture_finish_photo")
  5517. if capture_setting is not None and capture_setting.lower() != "true":
  5518. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  5519. return
  5520. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  5521. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  5522. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5523. printer = result.scalar_one_or_none()
  5524. if printer is None:
  5525. logger.warning(
  5526. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  5527. printer_id,
  5528. )
  5529. return
  5530. frame_bytes: bytes | None = None
  5531. # #2708: the banked frame arrives already rotated — it comes from
  5532. # `_capture_snapshot_for_notification`, which rotates before returning.
  5533. # Every other source below is a raw grab. Tracking which lets us store
  5534. # exactly one rotation in `_stage22_finish_frames` either way.
  5535. frame_already_rotated = False
  5536. # On the FINISH-state path the End G-code has already run, and two very
  5537. # different situations arrive here needing opposite answers.
  5538. #
  5539. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  5540. # snippet may have ejected the plate — the scene in front of the camera
  5541. # is no longer the finished print, and no amount of moving the plate
  5542. # brings it back. Use the banked in-print frame instead.
  5543. #
  5544. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  5545. # than the camera frames well, and the toolhead is parked out of the
  5546. # way. That is the *best* moment available on firmware that never emits
  5547. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  5548. # back. Preferring the bank here unconditionally, as this code used to,
  5549. # is what shipped a mid-print photo with the toolhead over the part.
  5550. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  5551. banked = _inprint_frame_bank.get(printer_id)
  5552. if banked:
  5553. frame_bytes = banked
  5554. frame_already_rotated = True
  5555. logger.info(
  5556. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  5557. "frame (%d bytes) instead of a post-swap live grab",
  5558. len(banked),
  5559. )
  5560. else:
  5561. logger.warning(
  5562. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  5563. "in-print bank is empty — falling back to a live grab, which may show a "
  5564. "swapped or empty plate",
  5565. printer_id,
  5566. )
  5567. # `restore_max_z` is set only once the plate is actually up, because the
  5568. # `finally` reads it to decide whether it owes a move back down.
  5569. #
  5570. # Never on a print whose End G-code Bambuddy injected, even when the bank
  5571. # came up empty above: that machine may have just ejected its plate, and
  5572. # driving Z into whatever a swap mechanism is doing is not a risk worth
  5573. # taking for a photo of a bed we already know may be bare.
  5574. if (
  5575. frame_bytes is None
  5576. and trigger == "finish_state"
  5577. and restore_plate_enabled
  5578. and not print_dispatch_context.end_gcode_injected(printer_id)
  5579. ):
  5580. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  5581. if wants_restore is None:
  5582. logger.info(
  5583. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  5584. printer_id,
  5585. )
  5586. elif await _plate_restore_is_blocked_by_queue(printer_id):
  5587. logger.info(
  5588. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  5589. printer_id,
  5590. )
  5591. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  5592. restore_max_z = wants_restore
  5593. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  5594. from backend.app.api.routes.camera import live_frame_for_capture
  5595. from backend.app.services.external_camera import capture_frame
  5596. # #2707: this used to collide with the live view and fail, which is
  5597. # how finish-photo notifications went out with no image attached.
  5598. # Leaving frame_bytes None keeps the rest of the fallback chain.
  5599. defer, buffered = live_frame_for_capture(printer_id)
  5600. if defer:
  5601. frame_bytes = buffered
  5602. else:
  5603. frame_bytes = await capture_frame(
  5604. printer.external_camera_url,
  5605. printer.external_camera_type or "mjpeg",
  5606. snapshot_url=printer.external_camera_snapshot_url,
  5607. )
  5608. if frame_bytes:
  5609. logger.info(
  5610. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  5611. len(frame_bytes),
  5612. )
  5613. elif frame_bytes is None:
  5614. from backend.app.api.routes.camera import get_buffered_frame
  5615. buffered = get_buffered_frame(printer_id)
  5616. if buffered:
  5617. frame_bytes = buffered
  5618. logger.info(
  5619. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  5620. len(frame_bytes),
  5621. )
  5622. else:
  5623. from backend.app.services.camera import capture_camera_frame_bytes
  5624. frame_bytes = await capture_camera_frame_bytes(
  5625. ip_address=printer.ip_address,
  5626. access_code=printer.access_code,
  5627. model=printer.model,
  5628. timeout=15,
  5629. )
  5630. if frame_bytes:
  5631. logger.info(
  5632. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  5633. len(frame_bytes),
  5634. )
  5635. if frame_bytes:
  5636. if not frame_already_rotated:
  5637. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  5638. _stage22_finish_frames[printer_id] = frame_bytes
  5639. else:
  5640. logger.warning(
  5641. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  5642. printer_id,
  5643. )
  5644. except Exception as e:
  5645. logger.warning(
  5646. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  5647. printer_id,
  5648. e,
  5649. )
  5650. finally:
  5651. # #2547: we raised the plate, so we own lowering it — including when the
  5652. # capture above failed or threw partway through.
  5653. if restore_max_z is not None:
  5654. try:
  5655. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  5656. except Exception as e:
  5657. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  5658. # #1790: always unblock the consumer's bounded wait — whether we stored
  5659. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  5660. # dict entry by the consumer doesn't affect signalling.
  5661. producer_done.set()
  5662. def _subtask_name_from_filename(filename: str) -> str:
  5663. """Recover the subtask name a print command would have carried for *filename*.
  5664. The dispatcher derives the printer-facing subtask name from the archive's
  5665. file name, so stripping the extensions back off gives the value MQTT echoes
  5666. on completion. Only the two extensions Bambuddy actually stores are removed,
  5667. and in the order they nest (``.gcode.3mf``), so a model whose own name
  5668. contains a dot -- ``My.Model.3mf`` -- keeps it.
  5669. """
  5670. name = PurePosixPath(filename).name
  5671. for suffix in (".3mf", ".gcode"):
  5672. if name.lower().endswith(suffix):
  5673. name = name[: -len(suffix)]
  5674. return name
  5675. # How the printer marks a subtask name it had to cut short. Observed on real
  5676. # hardware at ~100 characters, but the cut-off is not a fixed character count
  5677. # (a name with multibyte characters came back at 98), so match the marker
  5678. # rather than a length.
  5679. _SUBTASK_TRUNCATION_MARKER = "..."
  5680. def _normalise_subtask_name(name: str) -> str:
  5681. """Canonical form for comparing a dispatched name against MQTT's echo.
  5682. The printer does not echo the name back verbatim: it substitutes
  5683. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  5684. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  5685. The 3MF lookup in this module has always known that -- it builds
  5686. space-to-underscore variants of every candidate filename, and its
  5687. directory search normalises both sides before comparing. This exists so
  5688. the completion check reads the same rule from the same place instead of
  5689. growing its own, which is exactly how it came to disagree (#2829).
  5690. """
  5691. return name.strip().replace(" ", "_").casefold()
  5692. def _subtask_names_match(expected: str, observed: str) -> bool:
  5693. """Whether two subtask names describe the same print.
  5694. Beyond the space/underscore substitution, the printer truncates long names
  5695. and marks the cut with ``...``. A truncated echo has to count as a match or
  5696. every print with a long name strands its queue item the same way.
  5697. """
  5698. expected_n = _normalise_subtask_name(expected)
  5699. observed_n = _normalise_subtask_name(observed)
  5700. if expected_n == observed_n:
  5701. return True
  5702. # Either side can be the truncated one: the printer truncates what it
  5703. # echoes, and an archive whose own filename was recorded from a previous
  5704. # truncated echo carries the marker too.
  5705. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  5706. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  5707. return True
  5708. return False
  5709. async def _queue_item_dispatched_name(db, item) -> str:
  5710. """The subtask name *item* was dispatched under, or "" when unknowable.
  5711. A row with no archive, or an archive with no file name, is unverifiable
  5712. rather than wrong; every caller answers that with its permissive branch.
  5713. """
  5714. if item.archive_id is None:
  5715. return ""
  5716. from backend.app.models.archive import PrintArchive
  5717. archive = await db.get(PrintArchive, item.archive_id)
  5718. if archive is None or not archive.filename:
  5719. return ""
  5720. return _subtask_name_from_filename(archive.filename)
  5721. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  5722. """Whether this completion event is plausibly about *item*'s print.
  5723. The caller finds its queue row by printer and ``status='printing'`` alone,
  5724. which is all a completion event gives it -- there is no run identifier in
  5725. the MQTT payload to match on. That makes the lookup indiscriminate: any
  5726. completion delivered for this printer closes whichever row happens to be
  5727. printing, however unrelated. Comparing the subtask name against the archive
  5728. the row was dispatched with costs one primary-key load and rules that out.
  5729. Deliberately permissive: it answers False only on a positive disagreement
  5730. between two names we actually have. A row with no archive, an archive with
  5731. no file name, or an event with no subtask name is unverifiable rather than
  5732. wrong, and refusing those would strand the item in ``printing`` and wedge
  5733. the printer's queue -- a worse failure than the one being prevented.
  5734. """
  5735. observed = (data.get("subtask_name") or "").strip()
  5736. if not observed or item.archive_id is None:
  5737. return True
  5738. from backend.app.models.archive import PrintArchive
  5739. archive = await db.get(PrintArchive, item.archive_id)
  5740. if archive is None or not archive.filename:
  5741. return True
  5742. expected = _subtask_name_from_filename(archive.filename)
  5743. if not expected or _subtask_names_match(expected, observed):
  5744. return True
  5745. logging.getLogger(__name__).warning(
  5746. "Ignoring print completion for queue item %s: it was dispatched as %r "
  5747. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  5748. "printing rather than closing a run this event is not about.",
  5749. item.id,
  5750. expected,
  5751. archive.id,
  5752. archive.filename,
  5753. observed,
  5754. )
  5755. return False
  5756. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  5757. """Spend the 3MF download cache on a still-empty fallback archive.
  5758. ``on_print_complete`` drops the cache as its first act, which deletes the
  5759. file. If the cover endpoint (or anything else) pulled the 3MF while the
  5760. print ran and the archive never got one, this is the last moment those bytes
  5761. exist (#2957).
  5762. """
  5763. logger = logging.getLogger(__name__)
  5764. names = [
  5765. n
  5766. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  5767. if n
  5768. ]
  5769. for name in names:
  5770. try:
  5771. cached = get_cached_3mf(printer_id, name)
  5772. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  5773. return
  5774. except Exception as e:
  5775. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  5776. async def on_print_complete(printer_id: int, data: dict):
  5777. """Handle print completion - update the archive status."""
  5778. import time
  5779. logger = logging.getLogger(__name__)
  5780. start_time = time.time()
  5781. def log_timing(section: str):
  5782. elapsed = time.time() - start_time
  5783. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  5784. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  5785. # A kill-switch stop sends its provider notification immediately. Keep the
  5786. # task so the later notification path can await it and avoid a duplicate;
  5787. # if that immediate attempt failed, the regular completion path retries.
  5788. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  5789. # Last chance before the bytes go: if this print's archive is still an empty
  5790. # fallback and something downloaded the 3MF while it ran, fill the archive in
  5791. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  5792. # below deletes the file (#2957).
  5793. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  5794. # A pending cool-off retry has nothing left to recover for — the cache is
  5795. # about to be dropped and the print is over.
  5796. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  5797. if retry_task and not retry_task.done():
  5798. retry_task.cancel()
  5799. # Drop the 3MF download cache for this printer (#972). The print is over,
  5800. # nothing else legitimately needs the bytes; keeping them would only risk
  5801. # handing a stale file to the next print if it reuses the same name.
  5802. clear_3mf_cache(printer_id)
  5803. try:
  5804. ws_data = {
  5805. "status": data.get("status"),
  5806. "filename": data.get("filename"),
  5807. "subtask_name": data.get("subtask_name"),
  5808. "timelapse_was_active": data.get("timelapse_was_active"),
  5809. }
  5810. await ws_manager.send_print_complete(printer_id, ws_data)
  5811. log_timing("WebSocket send_print_complete")
  5812. except Exception as e:
  5813. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  5814. # Capture user info before clearing (needed for print log entry)
  5815. _print_user_info = printer_manager.get_current_print_user(printer_id)
  5816. # Clear current print user tracking (Issue #206)
  5817. printer_manager.clear_current_print_user(printer_id)
  5818. # If the user explicitly stopped this print from the queue UI the printer will
  5819. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  5820. # correct "print stopped" notification/email is sent instead of a failure alert.
  5821. _raw_status = data.get("status", "completed")
  5822. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  5823. logger.info(
  5824. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  5825. _raw_status,
  5826. printer_id,
  5827. )
  5828. data = {**data, "status": "cancelled"}
  5829. _user_stopped_printers.discard(printer_id)
  5830. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  5831. # may have left material on the bed: a user can cancel ten hours into a
  5832. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  5833. # touchscreen-stop reports `aborted` rather than `cancelled` because
  5834. # `_user_stopped_printers` is only populated when the user stops via the
  5835. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  5836. # which auto-dispatched the next queued print onto a fouled bed two seconds
  5837. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  5838. # Auto Off power cycles and Bambuddy restarts.
  5839. _final_status = data.get("status", "completed")
  5840. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  5841. printer_manager.set_awaiting_plate_clear(printer_id, True)
  5842. # MQTT relay - publish print complete
  5843. try:
  5844. printer_info = printer_manager.get_printer(printer_id)
  5845. if printer_info:
  5846. await mqtt_relay.on_print_complete(
  5847. printer_id,
  5848. printer_info.name,
  5849. printer_info.serial_number,
  5850. data.get("filename", ""),
  5851. data.get("subtask_name", ""),
  5852. data.get("status", "completed"),
  5853. )
  5854. except Exception:
  5855. pass # Don't fail print complete callback if MQTT fails
  5856. filename = data.get("filename", "")
  5857. subtask_name = data.get("subtask_name", "")
  5858. if not filename and not subtask_name:
  5859. logger.warning("Print complete without filename or subtask_name")
  5860. return
  5861. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  5862. # Build list of possible keys to try (matching how they were registered in on_print_start)
  5863. possible_keys = []
  5864. # Try subtask_name variations first (most reliable for matching)
  5865. if subtask_name:
  5866. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5867. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5868. possible_keys.append((printer_id, subtask_name))
  5869. # Try filename variations
  5870. if filename:
  5871. # Extract just the filename if it's a path
  5872. fname = filename.split("/")[-1] if "/" in filename else filename
  5873. if fname.endswith(".3mf"):
  5874. possible_keys.append((printer_id, fname))
  5875. elif fname.endswith(".gcode"):
  5876. base_name = fname.rsplit(".", 1)[0]
  5877. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5878. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5879. possible_keys.append((printer_id, fname))
  5880. else:
  5881. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5882. possible_keys.append((printer_id, f"{fname}.3mf"))
  5883. possible_keys.append((printer_id, fname))
  5884. # Also try full path versions
  5885. if filename.endswith(".3mf"):
  5886. possible_keys.append((printer_id, filename))
  5887. elif filename.endswith(".gcode"):
  5888. base_name = filename.rsplit(".", 1)[0]
  5889. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5890. possible_keys.append((printer_id, filename))
  5891. else:
  5892. possible_keys.append((printer_id, f"{filename}.3mf"))
  5893. possible_keys.append((printer_id, filename))
  5894. # Find the archive for this print
  5895. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  5896. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  5897. archive_id = None
  5898. for key in possible_keys:
  5899. archive_id = _active_prints.pop(key, None)
  5900. if archive_id:
  5901. logger.info("Found archive %s with key %s", archive_id, key)
  5902. # Also clean up any other keys pointing to this archive
  5903. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  5904. for k in keys_to_remove:
  5905. _active_prints.pop(k, None)
  5906. break
  5907. if not archive_id:
  5908. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  5909. async with async_session() as db:
  5910. from backend.app.models.archive import PrintArchive
  5911. # Try matching by subtask_name (stored as print_name) first
  5912. if subtask_name:
  5913. result = await db.execute(
  5914. select(PrintArchive)
  5915. .where(PrintArchive.printer_id == printer_id)
  5916. .where(PrintArchive.status == "printing")
  5917. .where(
  5918. or_(
  5919. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  5920. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  5921. )
  5922. )
  5923. .order_by(PrintArchive.created_at.desc())
  5924. .limit(1)
  5925. )
  5926. archive = result.scalar_one_or_none()
  5927. if archive:
  5928. archive_id = archive.id
  5929. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  5930. # Also try by filename
  5931. if not archive_id and filename:
  5932. result = await db.execute(
  5933. select(PrintArchive)
  5934. .where(PrintArchive.printer_id == printer_id)
  5935. .where(PrintArchive.filename == filename)
  5936. .where(PrintArchive.status == "printing")
  5937. .order_by(PrintArchive.created_at.desc())
  5938. .limit(1)
  5939. )
  5940. archive = result.scalar_one_or_none()
  5941. if archive:
  5942. archive_id = archive.id
  5943. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  5944. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  5945. # auto-start files found in root on power cycle, causing ghost prints.
  5946. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  5947. try:
  5948. if subtask_name:
  5949. archive_filename: str | None = None
  5950. async with async_session() as db:
  5951. from backend.app.models.archive import PrintArchive
  5952. from backend.app.models.printer import Printer
  5953. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5954. printer = result.scalar_one_or_none()
  5955. if archive_id:
  5956. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  5957. archive_filename = archive_row.scalar_one_or_none()
  5958. if printer:
  5959. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  5960. from backend.app.utils.filename import derive_remote_filename
  5961. # Primary candidate: the exact path the dispatcher uploaded to
  5962. # (derived from archive.filename via the same rule as upload).
  5963. # Without it, a library row that ended up with a doubled
  5964. # .gcode.3mf (#1542) leaves the real file behind because the
  5965. # subtask_name + ext fallbacks below don't match what's on the
  5966. # SD card. Fallbacks remain for archive-less prints (subtask
  5967. # never resolved to an archive) and for older naming variants.
  5968. candidate_paths: list[str] = []
  5969. if archive_filename:
  5970. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  5971. for ext in (".3mf", ".gcode"):
  5972. fallback = f"/{subtask_name}{ext}"
  5973. if fallback not in candidate_paths:
  5974. candidate_paths.append(fallback)
  5975. # Three outcomes track across all candidates so the final log
  5976. # line reflects what actually happened. The A1 in #1721 always
  5977. # ends here with ``any_not_found=True`` and the others False
  5978. # — its firmware auto-cleans the SD card before our cleanup
  5979. # runs, every candidate FTP-DELE returns 550, and the old
  5980. # code burned 3 retries × 2 s × 3 candidates per print
  5981. # logging a misleading "may linger" WARNING on a successful
  5982. # print.
  5983. any_deleted = False
  5984. any_real_failure = False
  5985. any_not_found = False
  5986. for remote_path in candidate_paths:
  5987. # Retry only the FAILED case — 550 NOT_FOUND will never
  5988. # recover by waiting, so a "file isn't here" answer
  5989. # advances immediately to the next candidate without
  5990. # consuming the retry budget.
  5991. for attempt in range(1, 4):
  5992. try:
  5993. delete_result = await delete_file_async(
  5994. printer.ip_address,
  5995. printer.access_code,
  5996. remote_path,
  5997. printer_model=printer.model,
  5998. )
  5999. except Exception as e:
  6000. delete_result = DeleteResult.FAILED
  6001. logger.warning(
  6002. "SD card cleanup attempt %d/3 raised for %s: %s",
  6003. attempt,
  6004. remote_path,
  6005. e,
  6006. )
  6007. if delete_result == DeleteResult.DELETED:
  6008. any_deleted = True
  6009. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6010. break
  6011. if delete_result == DeleteResult.NOT_FOUND:
  6012. any_not_found = True
  6013. break # 550 will not recover; try next candidate
  6014. # FAILED: real error — retry with backoff, then give up
  6015. if attempt < 3:
  6016. await asyncio.sleep(2)
  6017. else:
  6018. any_real_failure = True
  6019. logger.warning(
  6020. "SD card cleanup failed after 3 attempts for %s "
  6021. "(network/auth/transient error — file may linger on SD card)",
  6022. remote_path,
  6023. )
  6024. if not any_deleted and not any_real_failure and any_not_found:
  6025. # Every candidate said "not here." Either the printer
  6026. # firmware swept the SD card itself (common on A1) or the
  6027. # dispatcher's upload path doesn't match our candidate
  6028. # rule. Either way: nothing to clean up, no warning.
  6029. logger.debug(
  6030. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6031. "(printer likely self-cleaned)",
  6032. printer.name,
  6033. )
  6034. except Exception as e:
  6035. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6036. log_timing("SD card cleanup")
  6037. # Update queue item status early — must run before the archive_id early-return
  6038. # so queue items don't get stuck in "printing" when archive lookup fails.
  6039. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6040. queue_item_id = None
  6041. billing_run_id: str | None = None
  6042. billing_user_id: int | None = None
  6043. billing_cost_center_id: int | None = None
  6044. billing_plate_id: int | None = None
  6045. queue_status = None
  6046. queue_auto_off = False
  6047. try:
  6048. from backend.app.core.database import run_with_retry
  6049. from backend.app.models.print_queue import PrintQueueItem
  6050. async def _update_queue_status(db):
  6051. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6052. nonlocal queue_item_id, queue_status, queue_auto_off
  6053. result = await db.execute(
  6054. select(PrintQueueItem)
  6055. .where(PrintQueueItem.printer_id == printer_id)
  6056. .where(PrintQueueItem.status == "printing")
  6057. )
  6058. printing_items = list(result.scalars().all())
  6059. if len(printing_items) > 1:
  6060. logger.warning(
  6061. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6062. printer_id,
  6063. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6064. )
  6065. item = printing_items[0] if printing_items else None
  6066. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6067. return
  6068. if item:
  6069. queue_status = data.get("status", "completed")
  6070. # MQTT sends "aborted" for cancelled prints; normalise to
  6071. # "cancelled" so it matches the queue schema Literal.
  6072. if queue_status == "aborted":
  6073. queue_status = "cancelled"
  6074. item.status = queue_status
  6075. item.completed_at = datetime.now(timezone.utc)
  6076. if queue_status == "failed" and not item.error_message:
  6077. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6078. # Bump usage counters on the source library file so admins can
  6079. # sort by "last printed" and (eventually) auto-purge stale
  6080. # files — #1008.
  6081. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6082. await db.commit()
  6083. queue_item_id = item.id
  6084. billing_run_id = item.billing_run_id
  6085. billing_user_id = item.created_by_id
  6086. billing_cost_center_id = item.cost_center_id
  6087. billing_plate_id = item.plate_id
  6088. queue_auto_off = item.auto_off_after
  6089. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6090. await run_with_retry(_update_queue_status, label="queue status update")
  6091. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6092. # their own sessions and have their own error handling — no retry needed.
  6093. if queue_item_id is not None:
  6094. # Batch orders (#342): this run may have been the last one an order
  6095. # owed. Re-evaluate here rather than lazily on read, so a finished
  6096. # order reports itself complete without someone opening the page.
  6097. try:
  6098. from backend.app.services.print_batch import refresh_batch_status_for_item
  6099. async with async_session() as db:
  6100. await refresh_batch_status_for_item(db, queue_item_id)
  6101. await db.commit()
  6102. except Exception as e:
  6103. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6104. # MQTT relay - publish queue job completed
  6105. try:
  6106. printer_info = printer_manager.get_printer(printer_id)
  6107. await mqtt_relay.on_queue_job_completed(
  6108. job_id=queue_item_id,
  6109. filename=filename or subtask_name,
  6110. printer_id=printer_id,
  6111. printer_name=printer_info.name if printer_info else "Unknown",
  6112. status=queue_status,
  6113. )
  6114. except Exception:
  6115. pass # Don't fail if MQTT fails
  6116. # Check if queue is now empty and send notification
  6117. try:
  6118. from sqlalchemy import func as sa_func
  6119. async with async_session() as db:
  6120. count_result = await db.execute(
  6121. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6122. )
  6123. pending_count = count_result.scalar() or 0
  6124. if pending_count == 0:
  6125. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6126. completed_result = await db.execute(
  6127. select(sa_func.count(PrintQueueItem.id)).where(
  6128. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6129. PrintQueueItem.completed_at >= today_start,
  6130. )
  6131. )
  6132. completed_count = completed_result.scalar() or 1
  6133. await notification_service.on_queue_completed(
  6134. completed_count=completed_count,
  6135. db=db,
  6136. )
  6137. except Exception:
  6138. pass # Don't fail if notification fails
  6139. # Handle auto_off_after - power off printer if the queue item opted
  6140. # in. Delegates to the smart-plug manager so the off honours each
  6141. # plug's configured strategy (time delay or temperature threshold),
  6142. # is cancelled if the printer starts printing again, and never cuts
  6143. # power on a loaded print (#1890). Previously an inline block here
  6144. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6145. # timeout regardless of print state — cutting a touchscreen reprint.
  6146. if queue_auto_off:
  6147. try:
  6148. async with async_session() as db:
  6149. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6150. except Exception as e:
  6151. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6152. except Exception as e:
  6153. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6154. log_timing("Queue item update")
  6155. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6156. # Must run before archive_id early-return so it fires for all prints (including
  6157. # prints started from BambuStudio/touchscreen that have no archive).
  6158. if data.get("status") == "completed":
  6159. try:
  6160. from backend.app.api.routes.settings import get_setting
  6161. async with async_session() as db:
  6162. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6163. threshold = float(threshold_str) if threshold_str else 35.0
  6164. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6165. async with async_session() as db:
  6166. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6167. if providers:
  6168. _bed_cool_waiters[printer_id] = {
  6169. "threshold": threshold,
  6170. "filename": filename or subtask_name or "",
  6171. "registered_at": time.time(),
  6172. }
  6173. logger.info(
  6174. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6175. printer_id,
  6176. threshold,
  6177. )
  6178. else:
  6179. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6180. except Exception as e:
  6181. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6182. # Capture the slicer estimate before usage tracking runs. The tracker may
  6183. # update archive.cost with this run's measured cost; billing partial runs
  6184. # against that already-partial value would discount the charge twice.
  6185. billing_planned_grams: float | None = None
  6186. billing_base_cost: float | None = None
  6187. if archive_id:
  6188. try:
  6189. async with async_session() as db:
  6190. from backend.app.models.archive import PrintArchive
  6191. billing_archive = await db.get(PrintArchive, archive_id)
  6192. if billing_archive:
  6193. billing_path = (
  6194. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6195. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6196. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6197. billing_archive,
  6198. billing_path,
  6199. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6200. )
  6201. except Exception as e:
  6202. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6203. # --- Track filament consumption (must run before archive_id early-return so usage
  6204. # is recorded even when auto-archive is disabled) ---
  6205. usage_results: list[dict] = []
  6206. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6207. stored_ams_mapping = data.get("ams_mapping")
  6208. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6209. if not stored_ams_mapping and archive_id:
  6210. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6211. # Always drain the plate_id register on completion — the session already
  6212. # consumed it at print-start injection; leaving it would leak into the next
  6213. # print on the same archive_id (rare but possible with reprints) (#1697).
  6214. # Capture the popped value so the completion notification can scope the
  6215. # archive-level (summed-across-plates per #1593) filament + time totals
  6216. # down to the single plate that was actually printed (#1785).
  6217. notify_plate_id: int | None = None
  6218. if archive_id:
  6219. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6220. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6221. try:
  6222. async with async_session() as db:
  6223. from backend.app.api.routes.settings import get_setting
  6224. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6225. if not _spoolman_on or _spoolman_on.lower() != "true":
  6226. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6227. async with async_session() as db:
  6228. usage_results = await usage_on_print_complete(
  6229. printer_id,
  6230. data,
  6231. printer_manager,
  6232. db,
  6233. archive_id=archive_id,
  6234. ams_mapping=stored_ams_mapping,
  6235. )
  6236. if usage_results:
  6237. await ws_manager.broadcast(
  6238. {
  6239. "type": "spool_usage_logged",
  6240. "printer_id": printer_id,
  6241. "usage": usage_results,
  6242. }
  6243. )
  6244. log_timing("Usage tracker")
  6245. except Exception as e:
  6246. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6247. # Drop the print-start context unconditionally — the Spoolman branch above
  6248. # skips the internal tracker entirely, so nothing else would clear what
  6249. # print start captured, and a row surviving its print would be restored
  6250. # onto the next one after a restart.
  6251. try:
  6252. from backend.app.services.usage_tracker import discard_session
  6253. async with async_session() as db:
  6254. await discard_session(db, printer_id)
  6255. except Exception as e:
  6256. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6257. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6258. if archive_id:
  6259. if data.get("status") == "completed":
  6260. try:
  6261. await _report_spoolman_usage(printer_id, archive_id)
  6262. log_timing("Spoolman usage report")
  6263. except Exception as e:
  6264. logger.warning("Spoolman usage reporting failed: %s", e)
  6265. else:
  6266. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6267. try:
  6268. async with async_session() as db:
  6269. await _cleanup_spoolman_tracking(
  6270. printer_id,
  6271. archive_id,
  6272. db,
  6273. last_layer_num=data.get("last_layer_num"),
  6274. last_progress=data.get("last_progress"),
  6275. )
  6276. except Exception as e:
  6277. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6278. log_timing("Filament usage tracking")
  6279. if not archive_id:
  6280. # The printer's own calibration run has no archive by design, so this
  6281. # arrives here every time one finishes. Returning before the no-archive
  6282. # notification is not just noise control: that path attributes an
  6283. # unmatched completion to any queue item this printer finished in the
  6284. # last five minutes, which for a calibration that runs alongside a real
  6285. # print means emailing its owner that their print is done, twice and
  6286. # early. Everything above this point has already run — the plate-clear
  6287. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6288. # notification is skipped.
  6289. if is_internal_printer_job(filename, subtask_name):
  6290. logger.info(
  6291. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6292. filename,
  6293. subtask_name,
  6294. )
  6295. return
  6296. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6297. # Still send print-complete/failed/stopped notifications even without an archive.
  6298. # Try to enrich with queue/library-file data so user-specific emails work too.
  6299. async def _notify_no_archive():
  6300. try:
  6301. async with async_session() as db:
  6302. from backend.app.models.library import LibraryFile
  6303. from backend.app.models.print_queue import PrintQueueItem
  6304. from backend.app.models.printer import Printer
  6305. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6306. printer_obj = result.scalar_one_or_none()
  6307. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  6308. # Try to find the most-recent queue item for this printer so we can
  6309. # recover created_by_id and estimated print time.
  6310. # NOTE: By the time this task runs the queue item status has already
  6311. # been updated to a terminal state (completed/failed/cancelled), so
  6312. # we look for recently-completed items (within the last 5 minutes).
  6313. no_archive_data: dict | None = None
  6314. try:
  6315. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  6316. q_result = await db.execute(
  6317. select(PrintQueueItem)
  6318. .where(PrintQueueItem.printer_id == printer_id)
  6319. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  6320. .where(PrintQueueItem.completed_at >= cutoff)
  6321. .order_by(PrintQueueItem.completed_at.desc())
  6322. .limit(1)
  6323. )
  6324. queue_item = q_result.scalar_one_or_none()
  6325. if queue_item:
  6326. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6327. # Pull estimated time from library file when available
  6328. if queue_item.library_file_id:
  6329. lib_result = await db.execute(
  6330. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6331. )
  6332. lib_file = lib_result.scalar_one_or_none()
  6333. if lib_file and lib_file.print_time_seconds:
  6334. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6335. except Exception as lookup_err:
  6336. logger.debug(
  6337. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6338. )
  6339. # Enrich with usage tracker results (captured in enclosing scope)
  6340. if usage_results:
  6341. if no_archive_data is None:
  6342. no_archive_data = {}
  6343. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6344. if total_from_usage > 0:
  6345. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6346. no_archive_data["usage_results"] = usage_results
  6347. # Try MQTT remaining_time for print duration when no queue/library data
  6348. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  6349. mqtt_remaining = data.get("remaining_time")
  6350. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  6351. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  6352. ps = data.get("status", "completed")
  6353. logger.info(
  6354. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  6355. )
  6356. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6357. await notification_service.on_print_complete(
  6358. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  6359. )
  6360. else:
  6361. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6362. # Send user-specific email if we have a created_by_id
  6363. if no_archive_data and no_archive_data.get("created_by_id"):
  6364. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6365. await _dispatch_user_print_email(
  6366. ps,
  6367. no_archive_data["created_by_id"],
  6368. p_name,
  6369. raw_filename,
  6370. db,
  6371. )
  6372. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  6373. except Exception as e:
  6374. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  6375. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  6376. return
  6377. log_timing("Archive lookup")
  6378. # Update archive status
  6379. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  6380. try:
  6381. async with async_session() as db:
  6382. service = ArchiveService(db)
  6383. status = data.get("status", "completed")
  6384. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  6385. if hms_errors:
  6386. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  6387. failure_reason = derive_failure_reason(status, hms_errors)
  6388. if data.get("_reconciled"):
  6389. # A reconciled completion closes out a stale archive at
  6390. # reconnect — it is not a user action, so don't mislabel it
  6391. # "userCancelled". It shares the stale-cleanup path's key
  6392. # (issue #2974) and records that the real end time is unknown,
  6393. # which is also why its logged duration is 0 (#2592).
  6394. failure_reason = "noStatusUpdate"
  6395. if failure_reason:
  6396. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  6397. elif status == "failed" and hms_errors:
  6398. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  6399. await service.update_archive_status(
  6400. archive_id,
  6401. status=status,
  6402. completed_at=(
  6403. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  6404. ),
  6405. failure_reason=failure_reason,
  6406. )
  6407. logger.info(
  6408. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  6409. )
  6410. await ws_manager.send_archive_updated(
  6411. {
  6412. "id": archive_id,
  6413. "status": status,
  6414. }
  6415. )
  6416. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  6417. # MQTT relay - publish archive updated
  6418. try:
  6419. await mqtt_relay.on_archive_updated(
  6420. archive_id=archive_id,
  6421. print_name=filename or subtask_name,
  6422. status=status,
  6423. )
  6424. except Exception:
  6425. pass # Don't fail if MQTT fails
  6426. except Exception as e:
  6427. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  6428. # Continue with other operations even if archive update fails
  6429. log_timing("Archive status update")
  6430. # Apply finance wallet charge or release reservations once. For all partial
  6431. # terminal states (failed, aborted at the printer display, or cancelled via
  6432. # Bambuddy) use this run's measured spool delta, falling back to the last
  6433. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  6434. # estimate and therefore cannot represent an interrupted run.
  6435. try:
  6436. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  6437. async with async_session() as db:
  6438. from backend.app.models.archive import PrintArchive
  6439. from backend.app.services.finance_billing import apply_print_charge_for_archive
  6440. archive = await db.get(PrintArchive, archive_id)
  6441. if archive and billing_run_id is None:
  6442. billing_run_id = getattr(archive, "billing_run_id", None)
  6443. if archive and archive.created_by_id is None and _print_user_info:
  6444. archive.created_by_id = _print_user_info.get("user_id")
  6445. await db.flush()
  6446. run_status = data.get("status", "completed")
  6447. last_progress = data.get("last_progress")
  6448. if last_progress is None:
  6449. last_progress = data.get("progress")
  6450. actual_run_grams = _compute_run_filament_grams(
  6451. run_status,
  6452. billing_planned_grams,
  6453. last_progress,
  6454. usage_results,
  6455. )
  6456. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  6457. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  6458. charged = await apply_print_charge_for_archive(
  6459. db,
  6460. archive_id,
  6461. charged_user_id=billing_user_id,
  6462. cost_center_id=(
  6463. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  6464. ),
  6465. print_queue_id=queue_item_id,
  6466. print_run_id=billing_run_id,
  6467. base_cost_override=billing_base_cost,
  6468. filament_usage=filament_usage,
  6469. )
  6470. await db.commit()
  6471. if charged:
  6472. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  6473. except Exception as e:
  6474. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  6475. printer_info = printer_manager.get_printer(printer_id)
  6476. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  6477. billing_filename = filename or subtask_name or "Unknown"
  6478. billing_error = str(e)
  6479. try:
  6480. await ws_manager.broadcast(
  6481. {
  6482. "type": "billing_charge_failed",
  6483. "printer_id": printer_id,
  6484. "printer_name": billing_printer_name,
  6485. "filename": billing_filename,
  6486. "archive_id": archive_id,
  6487. }
  6488. )
  6489. except Exception as notification_error:
  6490. logger.error(
  6491. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  6492. archive_id,
  6493. notification_error,
  6494. )
  6495. async def _notify_billing_charge_failed() -> None:
  6496. try:
  6497. async with async_session() as notification_db:
  6498. await notification_service.on_billing_charge_failed(
  6499. printer_id,
  6500. billing_printer_name,
  6501. billing_filename,
  6502. archive_id,
  6503. billing_error,
  6504. notification_db,
  6505. )
  6506. except Exception as provider_error:
  6507. logger.error(
  6508. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  6509. archive_id,
  6510. provider_error,
  6511. exc_info=True,
  6512. )
  6513. spawn_background_task(
  6514. _notify_billing_charge_failed(),
  6515. name=f"billing-charge-failed-{archive_id}",
  6516. )
  6517. log_timing("Finance charge update")
  6518. # Write independent print log entry (separate table, never touches archives)
  6519. try:
  6520. async with async_session() as db:
  6521. from backend.app.models.archive import PrintArchive
  6522. from backend.app.services.print_log import write_log_entry
  6523. archive = await db.get(PrintArchive, archive_id)
  6524. if archive:
  6525. # Back-fill created_by_id on reprint (#730): reprint reuses the
  6526. # source archive row rather than creating a new one, so an
  6527. # archive that was auto-created from a printer-initiated
  6528. # print (created_by_id=NULL) would otherwise stay unattributed
  6529. # forever. When we have a print-session user AND the archive
  6530. # has no attribution yet, credit the current user. Never
  6531. # overwrite an existing attribution — the original uploader
  6532. # keeps ownership.
  6533. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  6534. if archive.created_by_id is None and _print_user_id is not None:
  6535. archive.created_by_id = _print_user_id
  6536. p_info = printer_manager.get_printer(printer_id)
  6537. # Per-run actuals — written to PrintLogEntry so stats reflect
  6538. # what THIS print actually used, not the source archive's
  6539. # first-run values (#1378). Helper handles the partial-print
  6540. # math (failed / cancelled / stopped get scaled to progress
  6541. # or to tracked spool deltas).
  6542. _run_status = data.get("status", "completed")
  6543. # #2614: scope the per-run estimate to the printed plate. For a
  6544. # multi-plate 3MF dispatched one plate at a time, the archive's
  6545. # filament/cost are the whole-file totals; the PrintLogEntry must
  6546. # reflect only this plate. No effect on single-plate archives (the
  6547. # plate estimate equals the whole-file value) or on the tracker
  6548. # path (measured spool deltas win in _compute_run_filament_grams).
  6549. _est_full_path = (
  6550. app_settings.base_dir / archive.file_path if archive.file_path else None
  6551. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6552. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  6553. _run_grams = _compute_run_filament_grams(
  6554. _run_status,
  6555. _est_grams,
  6556. data.get("last_progress", data.get("progress")),
  6557. usage_results,
  6558. )
  6559. # Per-run cost — prefer usage_results sum. For partial prints
  6560. # we deliberately skip the topup-to-estimate logic in
  6561. # usage_tracker (which assumes the print completed); the raw
  6562. # tracked-spool sum is closer to what THIS run actually cost.
  6563. _run_cost: float | None = None
  6564. if usage_results:
  6565. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  6566. if _run_cost is None and _run_status == "completed":
  6567. _run_cost = _est_cost
  6568. await write_log_entry(
  6569. db,
  6570. archive_id=archive.id,
  6571. # Captured by _update_queue_status above; None for
  6572. # printer-initiated prints with no queue row. Batch
  6573. # cost/energy roll-up joins on it (#342).
  6574. queue_item_id=queue_item_id,
  6575. status=_run_status,
  6576. print_name=archive.print_name,
  6577. printer_name=p_info.name if p_info else None,
  6578. printer_id=printer_id,
  6579. started_at=archive.started_at,
  6580. completed_at=archive.completed_at,
  6581. filament_type=archive.filament_type,
  6582. filament_color=archive.filament_color,
  6583. filament_used_grams=_run_grams,
  6584. cost=_run_cost,
  6585. failure_reason=archive.failure_reason,
  6586. thumbnail_path=archive.thumbnail_path,
  6587. created_by_id=archive.created_by_id,
  6588. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  6589. # Reconciled completions have an unknown real end time —
  6590. # log 0 duration instead of the whole disconnect gap (#2592).
  6591. reconciled=bool(data.get("_reconciled")),
  6592. )
  6593. await db.commit()
  6594. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  6595. except Exception as e:
  6596. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  6597. log_timing("Print log entry")
  6598. # Run slow operations as background tasks to avoid blocking the event loop
  6599. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  6600. async def _background_energy_calculation():
  6601. """Calculate and save energy usage in background.
  6602. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  6603. backend restart no longer loses per-print energy data).
  6604. """
  6605. try:
  6606. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  6607. async with async_session() as db:
  6608. from backend.app.models.archive import PrintArchive
  6609. archive = await db.get(PrintArchive, archive_id)
  6610. if archive is None:
  6611. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  6612. return
  6613. starting_kwh = archive.energy_start_kwh
  6614. if starting_kwh is None:
  6615. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  6616. return
  6617. candidates = await energy_plug_candidates(db, printer_id)
  6618. if not candidates:
  6619. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  6620. return
  6621. # Same ordering as the start reading, so the delta below is
  6622. # against the counter that produced `starting_kwh` (#2859).
  6623. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  6624. if selected is None:
  6625. logger.warning(
  6626. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  6627. printer_id,
  6628. ", ".join(plug.name for plug in candidates),
  6629. )
  6630. return
  6631. plug, energy = selected
  6632. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  6633. energy_used = round(energy["total"] - starting_kwh, 4)
  6634. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  6635. if energy_used < 0:
  6636. logger.warning(
  6637. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  6638. archive_id,
  6639. starting_kwh,
  6640. energy["total"],
  6641. )
  6642. return
  6643. from backend.app.api.routes.settings import get_setting
  6644. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  6645. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  6646. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  6647. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  6648. # reprint doesn't visually clobber the source archive's energy data
  6649. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  6650. from sqlalchemy import func
  6651. from backend.app.models.print_log import PrintLogEntry
  6652. existing_runs = await db.scalar(
  6653. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  6654. )
  6655. if (existing_runs or 0) <= 1:
  6656. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  6657. # we just wrote for THIS print. Either way it's the first run.
  6658. archive.energy_kwh = energy_used
  6659. archive.energy_cost = energy_cost_value
  6660. # Backfill the latest PrintLogEntry for this archive with energy
  6661. # (write_log_entry above ran before this background task completed,
  6662. # so energy fields are still NULL on that row).
  6663. latest_run = await db.execute(
  6664. select(PrintLogEntry)
  6665. .where(PrintLogEntry.archive_id == archive_id)
  6666. .order_by(PrintLogEntry.id.desc())
  6667. .limit(1)
  6668. )
  6669. run_row = latest_run.scalar_one_or_none()
  6670. if run_row is not None:
  6671. run_row.energy_kwh = energy_used
  6672. run_row.energy_cost = energy_cost_value
  6673. await db.commit()
  6674. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  6675. except Exception as e:
  6676. logger.warning("[ENERGY-BG] Failed: %s", e)
  6677. async def _background_finish_photo() -> str | None:
  6678. """Capture finish photo in background. Returns photo filename if captured."""
  6679. # #2547: set once this function has raised the plate itself (the
  6680. # timelapse path, where the moment producer returned without doing it).
  6681. # Declared out here so the `finally` can lower it again no matter where
  6682. # the capture below fails.
  6683. plate_restored_z: float | None = None
  6684. try:
  6685. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  6686. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  6687. # Read phase: settings + printer + archive in a short session, released
  6688. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  6689. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  6690. # tens of seconds; holding this session across it pinned one pooled
  6691. # connection idle-in-transaction per finishing print (issue #2572).
  6692. async with async_session() as db:
  6693. from backend.app.api.routes.settings import get_setting
  6694. from backend.app.models.archive import PrintArchive
  6695. from backend.app.models.printer import Printer
  6696. capture_enabled = await get_setting(db, "capture_finish_photo")
  6697. if capture_enabled is not None and capture_enabled.lower() != "true":
  6698. return None
  6699. if not archive_id:
  6700. return None
  6701. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  6702. archive = (
  6703. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6704. ).scalar_one_or_none()
  6705. if not printer or not archive:
  6706. return None
  6707. import uuid
  6708. from datetime import datetime
  6709. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  6710. if not archive.file_path:
  6711. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  6712. archive_dir = resolve_archive_dir(archive)
  6713. photo_filename = None
  6714. # Prefer the timelapse last-frame source when a timelapse was
  6715. # recording — it captures the moment after the toolhead parks
  6716. # but before the bed drops, which the live-camera grab below
  6717. # would miss (#1397). Skipped for external cameras (those have
  6718. # their own framing and don't see a Bambu timelapse). Only
  6719. # runs when the USER explicitly enabled timelapse for this
  6720. # print — #1721 removed Bambuddy's force-on at dispatch
  6721. # because it caused per-layer nozzle parking on Smooth-mode
  6722. # slicer profiles.
  6723. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  6724. printer.external_camera_enabled and printer.external_camera_url
  6725. )
  6726. timelapse_still_pending = False
  6727. if prefer_timelapse_source:
  6728. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  6729. archive_id=archive_id,
  6730. archive_dir=archive_dir,
  6731. rotation=getattr(printer, "camera_rotation", 0),
  6732. )
  6733. # #1721: replacement framing path — on_finish_photo_moment
  6734. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  6735. # parked, bed not yet dropped) and cached the JPEG bytes in
  6736. # _stage22_finish_frames. Consume them now so the saved photo
  6737. # has the better framing instead of the post-bed-drop angle
  6738. # the live-camera fallback below would give.
  6739. if not photo_filename:
  6740. # #1790: on the FINISH-state fallback path the producer
  6741. # task is dispatched back-to-back with this consumer, so
  6742. # a bare pop would race past with an empty result and
  6743. # the RTSP fallback below would collide with the
  6744. # producer's still-in-flight grab (single-client RTSP
  6745. # on Bambu printers). Wait for the producer to finish
  6746. # or give up before touching the cache.
  6747. #
  6748. # #2547: 20s was enough when the producer only ever grabbed a
  6749. # frame. It now also raises the plate first, which costs the
  6750. # settle window before the grab even starts — so the budget has
  6751. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  6752. # under the notification's own photo wait below.
  6753. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  6754. if in_flight is not None:
  6755. try:
  6756. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  6757. except asyncio.TimeoutError:
  6758. logger.warning(
  6759. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  6760. printer_id,
  6761. )
  6762. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  6763. if cached_frame:
  6764. # Already rotated by the producer (#2708) — rotating again
  6765. # here would undo the fix on the banked-frame path, whose
  6766. # bytes reach the cache having been rotated once already.
  6767. photos_dir = archive_dir / "photos"
  6768. photos_dir.mkdir(parents=True, exist_ok=True)
  6769. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6770. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6771. photo_path = photos_dir / photo_filename
  6772. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  6773. logger.info(
  6774. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  6775. photo_filename,
  6776. len(cached_frame),
  6777. )
  6778. # #2547: the timelapse path reaches the live grab below whenever the
  6779. # video hasn't landed in time — the documented usual outcome on
  6780. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  6781. # returned early for those prints without raising the plate, so
  6782. # without this the photo that actually ships in the notification is
  6783. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  6784. # asked us to fix. The archive still gets the better video frame
  6785. # later; this is about the image the user is sent.
  6786. #
  6787. # Gated on `timelapse_was_active` precisely because that is the
  6788. # condition under which the producer skipped. On every other path it
  6789. # has already raised and lowered the plate, and repeating that here
  6790. # would be a second pointless round trip.
  6791. if (
  6792. not photo_filename
  6793. and data.get("timelapse_was_active")
  6794. and not print_dispatch_context.end_gcode_injected(printer_id)
  6795. ):
  6796. try:
  6797. async with async_session() as db:
  6798. from backend.app.api.routes.settings import get_setting
  6799. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6800. if restore_setting is None or restore_setting.lower() == "true":
  6801. max_z = await _max_z_for_current_print(printer_id, data, logger)
  6802. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  6803. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  6804. plate_restored_z = max_z
  6805. except Exception as e:
  6806. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  6807. # Fallback chain: external camera → buffered live frame →
  6808. # fresh RTSP capture. Only runs if the timelapse path above
  6809. # didn't already produce a photo.
  6810. if not photo_filename:
  6811. if printer.external_camera_enabled and printer.external_camera_url:
  6812. logger.info("[PHOTO-BG] Using external camera")
  6813. from backend.app.api.routes.camera import live_frame_for_capture
  6814. from backend.app.services.external_camera import capture_frame
  6815. # #2707: the second half of the finish-photo failure — the
  6816. # pre-capture and this fallback both collided with the live
  6817. # view. None here continues down the fallback chain.
  6818. defer, buffered = live_frame_for_capture(printer_id)
  6819. if defer:
  6820. frame_data = buffered
  6821. else:
  6822. frame_data = await capture_frame(
  6823. printer.external_camera_url,
  6824. printer.external_camera_type or "mjpeg",
  6825. snapshot_url=printer.external_camera_snapshot_url,
  6826. )
  6827. if frame_data:
  6828. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  6829. photos_dir = archive_dir / "photos"
  6830. photos_dir.mkdir(parents=True, exist_ok=True)
  6831. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6832. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6833. photo_path = photos_dir / photo_filename
  6834. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  6835. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  6836. else:
  6837. # Check if camera stream is active - use buffered frame to avoid freeze
  6838. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  6839. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  6840. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  6841. buffered_frame = get_buffered_frame(printer_id)
  6842. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  6843. # Use frame from active stream
  6844. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  6845. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  6846. photos_dir = archive_dir / "photos"
  6847. photos_dir.mkdir(parents=True, exist_ok=True)
  6848. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6849. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6850. photo_path = photos_dir / photo_filename
  6851. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  6852. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  6853. else:
  6854. # No active stream - capture new frame
  6855. from backend.app.services.camera import capture_finish_photo
  6856. photo_filename = await capture_finish_photo(
  6857. printer_id=printer_id,
  6858. ip_address=printer.ip_address,
  6859. access_code=printer.access_code,
  6860. model=printer.model,
  6861. archive_dir=archive_dir,
  6862. rotation=getattr(printer, "camera_rotation", 0),
  6863. )
  6864. # Write phase: attach the photo in a fresh short-lived session.
  6865. if photo_filename:
  6866. async with async_session() as db:
  6867. from backend.app.models.archive import PrintArchive
  6868. arch = await db.get(PrintArchive, archive_id)
  6869. if arch is not None:
  6870. photos = arch.photos or []
  6871. photos.append(photo_filename)
  6872. arch.photos = photos
  6873. await db.commit()
  6874. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  6875. # The short wait above is bounded so a slow printer can't hold up
  6876. # the print-complete notification, which is what the caller is
  6877. # blocking on. When it ran out with the video still on its way,
  6878. # keep waiting off to the side and add the better frame to the
  6879. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  6880. # users, whose videos routinely take minutes to transfer, never get
  6881. # the pre-bed-drop framing this path exists to provide.
  6882. #
  6883. # Spawned here rather than at the point the wait gave up: both this
  6884. # function and the upgrade do a read-modify-write on `photos`, and
  6885. # the live-camera fallback above can take tens of seconds. Starting
  6886. # the upgrade before that write means the two can interleave and one
  6887. # silently drops the other's entry, leaving a JPEG on disk that the
  6888. # gallery never lists.
  6889. if timelapse_still_pending:
  6890. spawn_background_task(
  6891. _upgrade_finish_photo_from_timelapse(
  6892. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  6893. ),
  6894. name=f"finish-photo-upgrade-{archive_id}",
  6895. )
  6896. return photo_filename
  6897. except Exception as e:
  6898. logger.warning("[PHOTO-BG] Failed: %s", e)
  6899. return None
  6900. finally:
  6901. # #2547: we raised the plate, so we owe the move back down — even if
  6902. # the capture in between threw. Otherwise the user finds the print
  6903. # pinned under the nozzle.
  6904. if plate_restored_z is not None:
  6905. try:
  6906. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  6907. except Exception as e:
  6908. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6909. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  6910. # Photo capture task - result will be used by notifications
  6911. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  6912. log_timing("Background tasks scheduled (energy, photo)")
  6913. # Also run smart plug, notifications, and maintenance as background tasks
  6914. print_status = data.get("status", "completed")
  6915. async def _background_smart_plug():
  6916. """Handle smart plug automation in background."""
  6917. try:
  6918. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  6919. async with async_session() as db:
  6920. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  6921. logger.info("[AUTO-OFF-BG] Completed")
  6922. except Exception as e:
  6923. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  6924. async def _background_notifications(finish_photo_filename: str | None = None):
  6925. """Send print complete notifications in background."""
  6926. try:
  6927. logger.info(
  6928. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  6929. )
  6930. async with async_session() as db:
  6931. from backend.app.models.archive import PrintArchive
  6932. from backend.app.models.printer import Printer
  6933. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6934. printer = result.scalar_one_or_none()
  6935. printer_name = printer.name if printer else f"Printer {printer_id}"
  6936. archive_data = None
  6937. if archive_id:
  6938. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6939. archive = archive_result.scalar_one_or_none()
  6940. if archive:
  6941. # Actual elapsed time from started_at/completed_at when both are
  6942. # populated (every terminal status sets completed_at after #1198).
  6943. # Falls back to None so the notification path can decide whether to
  6944. # render the slicer estimate as a last resort.
  6945. actual_time_seconds = None
  6946. if archive.started_at and archive.completed_at:
  6947. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  6948. if elapsed > 0:
  6949. actual_time_seconds = int(elapsed)
  6950. archive_data = {
  6951. "print_time_seconds": archive.print_time_seconds,
  6952. "actual_time_seconds": actual_time_seconds,
  6953. "actual_filament_grams": archive.filament_used_grams,
  6954. "failure_reason": archive.failure_reason,
  6955. "created_by_id": archive.created_by_id,
  6956. }
  6957. # Scale filament usage for partial prints
  6958. if print_status != "completed" and archive.filament_used_grams:
  6959. progress = data.get("progress") or 0
  6960. scale = _partial_progress_scale(progress)
  6961. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  6962. archive_data["progress"] = progress
  6963. # Pass per-slot data from archive.extra_data
  6964. if archive.extra_data and archive.extra_data.get("filament_slots"):
  6965. slots = archive.extra_data["filament_slots"]
  6966. if print_status != "completed":
  6967. scale = _partial_progress_scale(data.get("progress"))
  6968. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  6969. archive_data["filament_slots"] = slots
  6970. # Scope project-summed totals down to the plate that was
  6971. # actually printed — see _scope_notification_archive_data_to_plate
  6972. # for the why (#1785).
  6973. archive_data = _scope_notification_archive_data_to_plate(
  6974. archive_data,
  6975. archive.file_path,
  6976. notify_plate_id,
  6977. print_status,
  6978. data.get("progress"),
  6979. app_settings.base_dir,
  6980. )
  6981. # Enrich filament_grams from usage_results when archive has no 3MF data
  6982. if not archive_data.get("actual_filament_grams") and usage_results:
  6983. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6984. if total_from_usage > 0:
  6985. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6986. # Pass usage tracker results for AMS slot info in notifications
  6987. if usage_results:
  6988. archive_data["usage_results"] = usage_results
  6989. # Add finish photo URL and image bytes if available
  6990. if finish_photo_filename:
  6991. from backend.app.api.routes.settings import get_setting
  6992. external_url = await get_setting(db, "external_url")
  6993. if external_url:
  6994. external_url = external_url.rstrip("/")
  6995. archive_data["finish_photo_url"] = (
  6996. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6997. )
  6998. else:
  6999. # Fallback to relative URL (won't work for external services)
  7000. archive_data["finish_photo_url"] = (
  7001. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  7002. )
  7003. # Read finish photo bytes for image attachment (e.g. Pushover)
  7004. try:
  7005. from backend.app.utils.archive_paths import find_archive_photo
  7006. photo_path = find_archive_photo(archive, finish_photo_filename)
  7007. if photo_path is not None:
  7008. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  7009. if len(photo_bytes) <= 2_500_000:
  7010. archive_data["image_data"] = photo_bytes
  7011. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  7012. else:
  7013. logger.warning(
  7014. f"[NOTIFY-BG] Finish photo too large for attachment: "
  7015. f"{len(photo_bytes)} bytes"
  7016. )
  7017. except Exception as e:
  7018. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  7019. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7020. await notification_service.on_print_complete(
  7021. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7022. )
  7023. else:
  7024. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7025. # Post-print outcome confirmation (#1898). Runs in this
  7026. # background task so the finish photo fetched above rides
  7027. # along with the prompt.
  7028. if print_status == "completed" and archive_id:
  7029. try:
  7030. await dispatch_outcome_confirmation(
  7031. db, printer_id, printer_name, data, archive_id, archive_data
  7032. )
  7033. except Exception as e:
  7034. logger.error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  7035. # Send user-specific email notification
  7036. if archive_data:
  7037. created_by_id = archive_data.get("created_by_id")
  7038. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7039. await _dispatch_user_print_email(
  7040. print_status,
  7041. created_by_id,
  7042. printer_name,
  7043. raw_filename,
  7044. db,
  7045. )
  7046. logger.info("[NOTIFY-BG] Completed")
  7047. except Exception as e:
  7048. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7049. async def _background_maintenance_check():
  7050. """Check for maintenance due in background."""
  7051. if print_status != "completed":
  7052. return
  7053. try:
  7054. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7055. async with async_session() as db:
  7056. from backend.app.models.printer import Printer
  7057. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7058. printer = result.scalar_one_or_none()
  7059. printer_name = printer.name if printer else f"Printer {printer_id}"
  7060. await ensure_default_types(db)
  7061. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7062. items_needing_attention = [
  7063. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7064. for item in overview.maintenance_items
  7065. if item.enabled and (item.is_due or item.is_warning)
  7066. ]
  7067. if items_needing_attention:
  7068. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7069. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7070. # MQTT relay - publish maintenance alerts
  7071. for item in items_needing_attention:
  7072. try:
  7073. await mqtt_relay.on_maintenance_alert(
  7074. printer_id=printer_id,
  7075. printer_name=printer_name,
  7076. maintenance_type=item["name"],
  7077. current_value=0, # Not easily available here
  7078. threshold=0, # Not easily available here
  7079. )
  7080. except Exception:
  7081. pass # Don't fail if MQTT fails
  7082. else:
  7083. logger.info("[MAINT-BG] Completed (no items need attention)")
  7084. except Exception as e:
  7085. logger.warning("[MAINT-BG] Failed: %s", e)
  7086. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7087. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7088. # Notification task waits for photo capture to complete first (with timeout).
  7089. # When a timelapse was recording, photo sourcing polls the per-print
  7090. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7091. # carries the correct bed-up photo instead of falling through to the
  7092. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7093. #
  7094. # #2547: both budgets now have to cover a plate restore as well.
  7095. #
  7096. # Without timelapse, the wait is on the moment producer, which raises the
  7097. # plate before its grab — so this has to outlast that producer's own budget.
  7098. #
  7099. # With timelapse, the capture polls up to
  7100. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7101. # falls back to a live grab, which is the case that raises the plate. At the
  7102. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7103. # restore would have moved the plate for a photo nobody waited for.
  7104. photo_wait_timeout = (
  7105. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7106. if data.get("timelapse_was_active")
  7107. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7108. )
  7109. async def _photo_then_notify():
  7110. """Wait for photo capture, then send notification with photo URL."""
  7111. finish_photo = None
  7112. try:
  7113. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7114. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7115. except TimeoutError:
  7116. logger.warning(
  7117. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7118. photo_wait_timeout,
  7119. )
  7120. except Exception as e:
  7121. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7122. try:
  7123. await _background_notifications(finish_photo)
  7124. except Exception as e:
  7125. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7126. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7127. # Stitch external camera layer timelapse if session was active
  7128. print_status = data.get("status", "completed")
  7129. async def _background_layer_timelapse():
  7130. """Stitch layer timelapse and attach to archive."""
  7131. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7132. try:
  7133. if print_status == "completed":
  7134. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7135. timelapse_path = await tl_complete(printer_id)
  7136. if timelapse_path and archive_id:
  7137. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7138. async with async_session() as db:
  7139. service = ArchiveService(db)
  7140. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7141. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  7142. # Clean up the temp file
  7143. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7144. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7145. elif timelapse_path:
  7146. # Timelapse created but no archive - just clean up
  7147. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7148. else:
  7149. # Print failed or cancelled - cancel timelapse session
  7150. cancel_session(printer_id)
  7151. logger.info(
  7152. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7153. )
  7154. except Exception as e:
  7155. logger.warning("[LAYER-TL] Failed: %s", e)
  7156. # Try to cancel session on error
  7157. try:
  7158. cancel_session(printer_id)
  7159. except Exception:
  7160. pass # Best-effort timelapse session cancellation on error
  7161. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7162. log_timing("All background tasks scheduled")
  7163. # Auto-scan for timelapse if recording was active during the print
  7164. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7165. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7166. # Schedule timelapse scan as background task with retries
  7167. # The printer needs time to encode the video after print completion
  7168. baseline = _timelapse_baselines.pop(printer_id, None)
  7169. spawn_background_task(
  7170. _scan_for_timelapse_with_retries(archive_id, baseline),
  7171. name=f"scan-timelapse-{archive_id}",
  7172. )
  7173. log_timing("Timelapse scan scheduled")
  7174. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7175. # AMS sensor history recording
  7176. _ams_history_task: asyncio.Task | None = None
  7177. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7178. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7179. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7180. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7181. _ams_alarm_cooldown: dict[str, datetime] = {}
  7182. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7183. # (printer_id, ams_id) already reported as sending the drop index and no
  7184. # percentage. Logged once each so a supported printer that turns out to do this
  7185. # shows up in a support bundle rather than as a user wondering where the
  7186. # humidity reading went -- see the note at the read site below (#3140).
  7187. _ams_index_only_logged: set[tuple[int, int]] = set()
  7188. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7189. """Temperature at which the AMS alarm fires, falling back to the display band.
  7190. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7191. when a notification was sent as well, which is why a room above it made the
  7192. alarm fire once an hour for as long as the weather lasted -- and the only way
  7193. to stop that was to raise the display band and lose the colour that says the
  7194. unit is warm (#2905).
  7195. Unset resolves to the fair threshold, so an install that never sets one is
  7196. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7197. so that arrives here as a string and is handled by the same branch as any
  7198. other unparseable value -- there is no separate sentinel to keep in sync.
  7199. A non-positive value is refused rather than honoured: zero would alarm
  7200. permanently, and it is far more likely to be a cleared field than a
  7201. deliberate choice.
  7202. """
  7203. if raw_alarm_value is None:
  7204. return fair_threshold
  7205. try:
  7206. value = float(raw_alarm_value)
  7207. except (TypeError, ValueError):
  7208. return fair_threshold
  7209. if not math.isfinite(value) or value <= 0:
  7210. return fair_threshold
  7211. return value
  7212. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7213. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7214. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7215. # partway through a cool-down would otherwise resume alarming about heat the
  7216. # user asked for — the same internal-timestamp-row pattern as
  7217. # support.py's debug_logging_enabled_at.
  7218. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7219. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7220. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7221. # matters when it never does.
  7222. AMS_DRYING_GRACE_MINUTES = 120
  7223. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7224. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7225. Anything older than the grace cap would expire on its next visit anyway, so
  7226. discarding it here costs nothing and stops rows for deleted printers from
  7227. accumulating.
  7228. Stamps ahead of now get two defences, because a box whose clock jumps
  7229. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7230. ones are discarded outright, and the rest are clamped to now. Without the
  7231. clamp the cap would measure from a moment that has not happened yet and hold
  7232. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7233. after a clock jump is a far better failure than an alarm silently disabled
  7234. for hours.
  7235. """
  7236. from backend.app.models.settings import Settings
  7237. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7238. setting = result.scalar_one_or_none()
  7239. if not setting or not setting.value:
  7240. return {}
  7241. try:
  7242. raw = json.loads(setting.value)
  7243. except (ValueError, TypeError):
  7244. return {} # Corrupted row → no latch, alarms behave as they did before
  7245. if not isinstance(raw, dict):
  7246. return {}
  7247. now = datetime.now(timezone.utc)
  7248. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7249. latch: dict[str, datetime] = {}
  7250. for key, value in raw.items():
  7251. try:
  7252. stamp = datetime.fromisoformat(str(value))
  7253. except (ValueError, TypeError):
  7254. continue
  7255. if stamp.tzinfo is None:
  7256. stamp = stamp.replace(tzinfo=timezone.utc)
  7257. if not (now - window <= stamp <= now + window):
  7258. continue
  7259. # Nothing may sit in the future: suppression is measured as now minus
  7260. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7261. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7262. latch[str(key)] = min(stamp, now)
  7263. return latch
  7264. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7265. """Persist the latch, writing only when it actually changed.
  7266. Adds the session change but does not commit — the caller's own commit
  7267. carries it, so the latch lands in the same transaction as the sensor rows
  7268. that produced it.
  7269. """
  7270. from backend.app.models.settings import Settings
  7271. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7272. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7273. setting = result.scalar_one_or_none()
  7274. if setting is None:
  7275. # Don't create the row on installs that never dry anything.
  7276. if payload != "{}":
  7277. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7278. elif setting.value != payload:
  7279. setting.value = payload
  7280. def _ams_has_filament(ams_data: dict) -> bool:
  7281. """True if this AMS unit has at least one tray slot holding filament.
  7282. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7283. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7284. still report sensor readings, but those readings are ambient and not
  7285. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7286. humidity/temperature alarms on this check so empty units don't generate
  7287. hourly noise. Sensor history still records regardless so the UI charts
  7288. stay continuous.
  7289. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7290. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7291. """
  7292. bits = ams_data.get("tray_exist_bits")
  7293. if isinstance(bits, str) and bits.strip():
  7294. try:
  7295. return int(bits, 16) > 0
  7296. except ValueError:
  7297. pass
  7298. trays = ams_data.get("tray")
  7299. if isinstance(trays, list):
  7300. return any(
  7301. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  7302. )
  7303. return False
  7304. async def record_ams_history():
  7305. """Background task to record AMS humidity and temperature data."""
  7306. logger = logging.getLogger(__name__)
  7307. # Wait a short time for MQTT connections to establish on startup
  7308. await asyncio.sleep(10)
  7309. while True:
  7310. try:
  7311. from backend.app.models.ams_history import AMSSensorHistory
  7312. from backend.app.models.printer import Printer
  7313. from backend.app.models.settings import Settings
  7314. async with async_session() as db:
  7315. # Get all active printers
  7316. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7317. printers = result.scalars().all()
  7318. # Get alarm thresholds from settings
  7319. humidity_threshold = 60.0 # Default: fair threshold
  7320. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  7321. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  7322. setting = result.scalar_one_or_none()
  7323. if setting:
  7324. try:
  7325. humidity_threshold = float(setting.value)
  7326. except (ValueError, TypeError):
  7327. pass # Keep default threshold if stored value is invalid
  7328. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  7329. setting = result.scalar_one_or_none()
  7330. if setting:
  7331. try:
  7332. temp_fair_threshold = float(setting.value)
  7333. except (ValueError, TypeError):
  7334. pass # Keep default threshold if stored value is invalid
  7335. # The alarm gets its own threshold, seeded from the resolved fair
  7336. # value so an install that has never set one behaves exactly as
  7337. # it did before (#2905). ams_temp_fair decides when the card turns
  7338. # amber; 35 C is a reasonable place to change a colour and not a
  7339. # reasonable place to page someone. A room above it makes the
  7340. # alarm fire once an hour for as long as the weather lasts, and
  7341. # the only way to stop it was to raise the display band and lose
  7342. # the colour that says the unit is warm.
  7343. #
  7344. # An unset value is stored as the literal "None", which the except
  7345. # below swallows the same way it swallows garbage -- so the
  7346. # fallback costs nothing and needs no sentinel of its own.
  7347. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  7348. setting = result.scalar_one_or_none()
  7349. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  7350. temp_fair_threshold, setting.value if setting else None
  7351. )
  7352. # Per-filament humidity threshold overrides (#1605) — resolved
  7353. # per-AMS below from the loaded tray types. Reuses the same
  7354. # resolver as the auto-drying scheduler so behavior stays in
  7355. # lockstep across both consumers.
  7356. from backend.app.services.print_scheduler import PrintScheduler
  7357. per_type_humidity_thresholds: dict[str, int] = {}
  7358. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  7359. setting = result.scalar_one_or_none()
  7360. if setting and setting.value:
  7361. try:
  7362. raw = json.loads(setting.value)
  7363. if isinstance(raw, dict):
  7364. for k, v in raw.items():
  7365. try:
  7366. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  7367. v
  7368. )
  7369. except (TypeError, ValueError):
  7370. continue
  7371. except (ValueError, TypeError):
  7372. pass # Invalid JSON → no overrides, fall through to global threshold
  7373. # Per-AMS drying latch (#1802), loaded once per pass and written
  7374. # back below only if a unit changed it.
  7375. drying_latch = await _load_ams_drying_latch(db)
  7376. drying_latch_before = dict(drying_latch)
  7377. recorded_count = 0
  7378. for printer in printers:
  7379. # Get current state from printer manager
  7380. state = printer_manager.get_status(printer.id)
  7381. if not state or not state.connected or not state.raw_data:
  7382. continue # Skip disconnected printers - don't use stale data
  7383. raw_data = state.raw_data
  7384. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  7385. continue
  7386. # Record data for each AMS unit
  7387. for ams_data in raw_data["ams"]:
  7388. ams_id = int(ams_data.get("id", 0))
  7389. # Percentage only. The 1-5 index is inverted, so
  7390. # charting it as a percentage drew the wettest units as
  7391. # the driest (#3140); a unit that reports no percentage
  7392. # leaves a gap in the chart instead. See
  7393. # utils/ams_humidity.
  7394. humidity = ams_humidity_percent(ams_data)
  7395. # No supported printer is known to send the index
  7396. # alone -- the report came from unsupported firmware,
  7397. # and no install has been seen using the old fallback.
  7398. # "Known" is doing work there, so say so once per unit:
  7399. # the alternative is a silent blank card.
  7400. if humidity is None and ams_data.get("humidity") is not None:
  7401. unit_key = (printer.id, ams_id)
  7402. if unit_key not in _ams_index_only_logged:
  7403. _ams_index_only_logged.add(unit_key)
  7404. logger.info(
  7405. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  7406. "percentage. The index is inverted and is not shown as a percentage "
  7407. "(#3140), so this unit has no humidity reading, chart or alarm. "
  7408. "Please report this with the printer and AMS firmware versions.",
  7409. printer.name,
  7410. ams_id,
  7411. )
  7412. # Get temperature
  7413. temperature = None
  7414. temp_str = ams_data.get("temp")
  7415. if temp_str is not None:
  7416. try:
  7417. temperature = float(temp_str)
  7418. except (ValueError, TypeError):
  7419. pass # Skip unparseable temperature value
  7420. # Skip if no data
  7421. if humidity is None and temperature is None:
  7422. continue
  7423. # Record the data point
  7424. history = AMSSensorHistory(
  7425. printer_id=printer.id,
  7426. ams_id=ams_id,
  7427. humidity=humidity,
  7428. # Both columns hold the same reading now that the
  7429. # index can no longer reach ``humidity``. Writing it
  7430. # through the same value also stops a genuine 0%
  7431. # from being stored as NULL, which the old truthiness
  7432. # test did.
  7433. humidity_raw=humidity,
  7434. temperature=temperature,
  7435. )
  7436. db.add(history)
  7437. recorded_count += 1
  7438. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  7439. is_ams_ht = ams_id >= 128
  7440. if is_ams_ht:
  7441. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  7442. else:
  7443. ams_label = f"AMS-{chr(65 + ams_id)}"
  7444. # Skip alarm dispatch for empty AMS units — humidity /
  7445. # temperature readings are ambient with no filament to
  7446. # protect, and the hourly notification just becomes
  7447. # noise. Sensor history was already recorded above so
  7448. # the UI charts stay continuous (#1619). Per-AMS check
  7449. # so a multi-AMS setup with one loaded + one empty
  7450. # still alarms on the loaded unit.
  7451. if not _ams_has_filament(ams_data):
  7452. continue
  7453. # Resolve per-filament humidity threshold for this AMS
  7454. # unit (#1605). Falls back to the global ams_humidity_fair
  7455. # when no per-type overrides are configured.
  7456. trays = ams_data.get("tray", []) or []
  7457. effective_humidity_threshold = float(
  7458. PrintScheduler.resolve_humidity_threshold(
  7459. trays, per_type_humidity_thresholds, int(humidity_threshold)
  7460. )
  7461. )
  7462. # Check humidity alarm (only if above threshold)
  7463. if humidity is not None and humidity > effective_humidity_threshold:
  7464. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  7465. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7466. now = datetime.now(timezone.utc)
  7467. if (
  7468. last_alarm is None
  7469. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7470. ):
  7471. _ams_alarm_cooldown[cooldown_key] = now
  7472. logger.info(
  7473. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  7474. )
  7475. try:
  7476. # Call different notification method based on AMS type
  7477. if is_ams_ht:
  7478. await notification_service.on_ams_ht_humidity_high(
  7479. printer.id,
  7480. printer.name,
  7481. ams_label,
  7482. humidity,
  7483. effective_humidity_threshold,
  7484. db,
  7485. )
  7486. else:
  7487. await notification_service.on_ams_humidity_high(
  7488. printer.id,
  7489. printer.name,
  7490. ams_label,
  7491. humidity,
  7492. effective_humidity_threshold,
  7493. db,
  7494. )
  7495. except Exception as e:
  7496. logger.warning("Failed to send humidity alarm: %s", e)
  7497. # A drying cycle heats the unit far past ams_temp_fair on
  7498. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  7499. # AMS-HT, against a 35 C default — so the alarm fired
  7500. # once an hour for the whole cycle and kept firing while
  7501. # the unit cooled back down (#1802). Latch on the
  7502. # firmware's own drying state and hold until the reading
  7503. # returns to normal. Humidity is deliberately left alone:
  7504. # it falls during drying, which is the whole point.
  7505. latch_key = f"{printer.id}:{ams_id}"
  7506. # The latch releases at `threshold`, so it takes the alarm
  7507. # number too. Handing it the display band would strand the
  7508. # latch on any unit that settles back above it -- a room
  7509. # where the AMS rests at 37.7 C never returns under a 35 C
  7510. # band, so the latch could only expire on the grace cap
  7511. # rather than releasing when the unit had actually cooled.
  7512. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  7513. drying_active=is_drying_active(ams_data),
  7514. temperature=temperature,
  7515. threshold=temp_alarm_threshold,
  7516. latched_at=drying_latch.get(latch_key),
  7517. now=datetime.now(timezone.utc),
  7518. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  7519. )
  7520. if new_latch is None:
  7521. drying_latch.pop(latch_key, None)
  7522. else:
  7523. drying_latch[latch_key] = new_latch
  7524. # Check temperature alarm (only if above threshold)
  7525. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  7526. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  7527. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7528. now = datetime.now(timezone.utc)
  7529. if (
  7530. last_alarm is None
  7531. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7532. ):
  7533. _ams_alarm_cooldown[cooldown_key] = now
  7534. logger.info(
  7535. f"Sending temperature alarm for {printer.name} {ams_label}: "
  7536. f"{temperature}°C > {temp_alarm_threshold}°C"
  7537. )
  7538. try:
  7539. # Call different notification method based on AMS type
  7540. if is_ams_ht:
  7541. # The reported threshold has to be the one
  7542. # that fired, or the message says "> 35 °C"
  7543. # while firing at 45.
  7544. await notification_service.on_ams_ht_temperature_high(
  7545. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7546. )
  7547. else:
  7548. await notification_service.on_ams_temperature_high(
  7549. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7550. )
  7551. except Exception as e:
  7552. logger.warning("Failed to send temperature alarm: %s", e)
  7553. if drying_latch != drying_latch_before:
  7554. await _save_ams_drying_latch(db, drying_latch)
  7555. await db.commit()
  7556. if recorded_count > 0:
  7557. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  7558. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  7559. global _ams_cleanup_counter
  7560. _ams_cleanup_counter += 1
  7561. if _ams_cleanup_counter >= 288:
  7562. _ams_cleanup_counter = 0
  7563. # Get retention days from settings
  7564. from backend.app.models.settings import Settings
  7565. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  7566. setting = result.scalar_one_or_none()
  7567. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  7568. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7569. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  7570. await db.commit()
  7571. if result.rowcount > 0:
  7572. logger.info(
  7573. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  7574. )
  7575. # Wait until next recording interval
  7576. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  7577. except asyncio.CancelledError:
  7578. break
  7579. except Exception as e:
  7580. logger.warning("AMS history recording failed: %s", e)
  7581. await asyncio.sleep(60) # Wait a bit before retrying
  7582. def start_ams_history_recording():
  7583. """Start the AMS history recording background task."""
  7584. global _ams_history_task
  7585. if _ams_history_task is None:
  7586. _ams_history_task = asyncio.create_task(record_ams_history())
  7587. logging.getLogger(__name__).info("AMS history recording started")
  7588. def stop_ams_history_recording():
  7589. """Stop the AMS history recording background task."""
  7590. global _ams_history_task
  7591. if _ams_history_task:
  7592. _ams_history_task.cancel()
  7593. _ams_history_task = None
  7594. logging.getLogger(__name__).info("AMS history recording stopped")
  7595. # Printer sensor history recording (nozzle / bed / chamber)
  7596. _printer_sensor_history_task: asyncio.Task | None = None
  7597. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  7598. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  7599. _printer_sensor_cleanup_counter = 0
  7600. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  7601. # MQTT parser writes, so we don't need to handle per-model field aliases here
  7602. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  7603. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  7604. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  7605. _SENSOR_TARGET_KEYS = {
  7606. "nozzle": "nozzle_target",
  7607. "nozzle_2": "nozzle_2_target",
  7608. "bed": "bed_target",
  7609. "chamber": "chamber_target",
  7610. }
  7611. async def record_printer_sensor_history():
  7612. """Background task to record nozzle / bed / chamber readings.
  7613. Pulls from `state.temperatures` (already normalised across all printer
  7614. models by the MQTT parser) rather than re-parsing raw_data, so we get
  7615. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  7616. """
  7617. logger = logging.getLogger(__name__)
  7618. await asyncio.sleep(10)
  7619. while True:
  7620. try:
  7621. from backend.app.models.printer import Printer
  7622. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  7623. from backend.app.models.settings import Settings
  7624. async with async_session() as db:
  7625. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7626. printers = result.scalars().all()
  7627. recorded_count = 0
  7628. for printer in printers:
  7629. state = printer_manager.get_status(printer.id)
  7630. if not state or not state.connected:
  7631. continue
  7632. temps = getattr(state, "temperatures", None) or {}
  7633. if not isinstance(temps, dict):
  7634. continue
  7635. for kind in _SENSOR_KINDS:
  7636. if kind not in temps:
  7637. continue
  7638. try:
  7639. value = float(temps[kind])
  7640. except (ValueError, TypeError):
  7641. continue
  7642. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  7643. target_val: float | None = None
  7644. if target_raw is not None:
  7645. try:
  7646. target_val = float(target_raw)
  7647. except (ValueError, TypeError):
  7648. target_val = None
  7649. db.add(
  7650. PrinterSensorHistory(
  7651. printer_id=printer.id,
  7652. sensor_kind=kind,
  7653. value=value,
  7654. target=target_val,
  7655. )
  7656. )
  7657. recorded_count += 1
  7658. await db.commit()
  7659. if recorded_count > 0:
  7660. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  7661. # Periodic cleanup — once every ~24h at this interval.
  7662. global _printer_sensor_cleanup_counter
  7663. _printer_sensor_cleanup_counter += 1
  7664. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  7665. if _printer_sensor_cleanup_counter >= cleanup_every:
  7666. _printer_sensor_cleanup_counter = 0
  7667. result = await db.execute(
  7668. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  7669. )
  7670. setting = result.scalar_one_or_none()
  7671. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  7672. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7673. cleanup = await db.execute(
  7674. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  7675. )
  7676. await db.commit()
  7677. if cleanup.rowcount > 0:
  7678. logger.info(
  7679. "Cleaned up %s old printer sensor history entries (older than %s days)",
  7680. cleanup.rowcount,
  7681. retention_days,
  7682. )
  7683. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  7684. except asyncio.CancelledError:
  7685. break
  7686. except Exception as e:
  7687. logger.warning("Printer sensor history recording failed: %s", e)
  7688. await asyncio.sleep(60)
  7689. def start_printer_sensor_history_recording():
  7690. global _printer_sensor_history_task
  7691. if _printer_sensor_history_task is None:
  7692. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  7693. logging.getLogger(__name__).info("Printer sensor history recording started")
  7694. def stop_printer_sensor_history_recording():
  7695. global _printer_sensor_history_task
  7696. if _printer_sensor_history_task:
  7697. _printer_sensor_history_task.cancel()
  7698. _printer_sensor_history_task = None
  7699. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  7700. # Printer runtime tracking
  7701. _runtime_tracking_task: asyncio.Task | None = None
  7702. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  7703. async def track_printer_runtime():
  7704. """Background task to track printer active runtime (RUNNING state only).
  7705. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  7706. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  7707. which track mechanical wear. Pause time has no motion and no wear, so
  7708. counting it inflates maintenance warnings (#1521).
  7709. """
  7710. logger = logging.getLogger(__name__)
  7711. # Wait for MQTT connections to establish on startup
  7712. await asyncio.sleep(15)
  7713. while True:
  7714. try:
  7715. from backend.app.models.printer import Printer
  7716. # Fetch printer IDs in a short-lived read-only session
  7717. async with async_session() as db:
  7718. result = await db.execute(
  7719. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  7720. Printer.is_active.is_(True)
  7721. )
  7722. )
  7723. printer_rows = result.all()
  7724. now = datetime.now(timezone.utc)
  7725. updated_count = 0
  7726. # Update each printer in its own short session to minimise write-lock
  7727. # hold time and avoid blocking critical commits like queue status
  7728. # updates (#897).
  7729. for pid, pname, runtime_secs, last_update in printer_rows:
  7730. state = printer_manager.get_status(pid)
  7731. if not state:
  7732. logger.debug("[%s] Runtime tracking: no state available", pname)
  7733. continue
  7734. if not state.connected:
  7735. logger.debug("[%s] Runtime tracking: not connected", pname)
  7736. continue
  7737. needs_commit = False
  7738. new_runtime = runtime_secs
  7739. new_last_update = last_update
  7740. if state.state == "RUNNING":
  7741. if last_update:
  7742. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  7743. elapsed = (now - lu).total_seconds()
  7744. if elapsed > 0:
  7745. new_runtime = runtime_secs + int(elapsed)
  7746. updated_count += 1
  7747. needs_commit = True
  7748. logger.debug(
  7749. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  7750. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  7751. )
  7752. else:
  7753. needs_commit = True
  7754. logger.debug("[%s] Runtime tracking: first active detection", pname)
  7755. new_last_update = now
  7756. else:
  7757. if last_update is not None:
  7758. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  7759. new_last_update = None
  7760. needs_commit = True
  7761. if needs_commit:
  7762. try:
  7763. async with async_session() as db:
  7764. result = await db.execute(select(Printer).where(Printer.id == pid))
  7765. printer = result.scalar_one_or_none()
  7766. if printer:
  7767. printer.runtime_seconds = new_runtime
  7768. printer.last_runtime_update = new_last_update
  7769. await db.commit()
  7770. except Exception as e:
  7771. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  7772. if updated_count > 0:
  7773. logger.debug("Updated runtime for %s printer(s)", updated_count)
  7774. except asyncio.CancelledError:
  7775. logger.info("Runtime tracking cancelled")
  7776. break
  7777. except Exception as e:
  7778. logger.warning("Runtime tracking failed: %s", e)
  7779. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  7780. def start_runtime_tracking():
  7781. """Start the printer runtime tracking background task."""
  7782. global _runtime_tracking_task
  7783. if _runtime_tracking_task is None:
  7784. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  7785. logging.getLogger(__name__).info("Printer runtime tracking started")
  7786. def stop_runtime_tracking():
  7787. """Stop the printer runtime tracking background task."""
  7788. global _runtime_tracking_task
  7789. if _runtime_tracking_task:
  7790. _runtime_tracking_task.cancel()
  7791. _runtime_tracking_task = None
  7792. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  7793. # SpoolBuddy device watchdog
  7794. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  7795. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  7796. async def _spoolbuddy_watchdog_loop():
  7797. """Periodic check for SpoolBuddy devices that have gone offline."""
  7798. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  7799. while True:
  7800. try:
  7801. await spoolbuddy_watchdog()
  7802. except asyncio.CancelledError:
  7803. break
  7804. except Exception as e:
  7805. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  7806. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  7807. def start_spoolbuddy_watchdog():
  7808. global _spoolbuddy_watchdog_task
  7809. if _spoolbuddy_watchdog_task is None:
  7810. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  7811. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  7812. def stop_spoolbuddy_watchdog():
  7813. global _spoolbuddy_watchdog_task
  7814. if _spoolbuddy_watchdog_task:
  7815. _spoolbuddy_watchdog_task.cancel()
  7816. _spoolbuddy_watchdog_task = None
  7817. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  7818. # Dead-MQTT-session recovery
  7819. #
  7820. # check_staleness() covers the "connected but silent" half-broken session. It
  7821. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  7822. # is the only thing left watching at that point. When paho stops making
  7823. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  7824. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  7825. # offline with the UI open the whole time, recovered only when something
  7826. # happened to nudge it.
  7827. #
  7828. # This loop is that backstop. It only touches printers that had a working
  7829. # session and lost it, and only when the MQTT port still answers — a printer
  7830. # that is simply switched off is left to paho, since rebuilding a client
  7831. # against an unreachable host achieves nothing and would fill the log every
  7832. # night.
  7833. _connection_watchdog_task: asyncio.Task | None = None
  7834. CONNECTION_WATCHDOG_INTERVAL = 60
  7835. # How long a printer must have been silent before we stop trusting paho.
  7836. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  7837. # so a session that is recovering on its own is never interrupted.
  7838. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  7839. # Per-printer floor between rebuild attempts.
  7840. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  7841. _connection_watchdog_last_attempt: dict[int, float] = {}
  7842. async def _recover_dead_printer_sessions() -> int:
  7843. """Rebuild MQTT clients that have been offline too long to still be trying.
  7844. Returns the number of printers a rebuild was attempted for (for tests and
  7845. for the caller's logging). Never raises: one unreachable printer must not
  7846. stop the sweep for the rest of the farm.
  7847. """
  7848. logger = logging.getLogger(__name__)
  7849. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  7850. now = time.monotonic()
  7851. recovered = 0
  7852. for printer_id, client in list(printer_manager._clients.items()):
  7853. try:
  7854. if client.state.connected:
  7855. _connection_watchdog_last_attempt.pop(printer_id, None)
  7856. continue
  7857. # Time since the last inbound message is the age of the last known
  7858. # good session — no extra bookkeeping needed, and it is the same
  7859. # clock is_stale() reads. 0 means this client has never had one:
  7860. # that is the initial-connect path, where paho retrying is the
  7861. # correct and only behaviour, so leave it be.
  7862. last_msg = client._last_message_time
  7863. if not last_msg:
  7864. continue
  7865. offline_for = time.time() - last_msg
  7866. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  7867. continue
  7868. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  7869. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  7870. continue
  7871. if not await check_port(client.ip_address, PORT_MQTT):
  7872. # Switched off, unplugged, or off the network. Paho's retry is
  7873. # the right handler; say so at debug level and move on.
  7874. logger.debug(
  7875. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  7876. "— leaving the reconnect to paho",
  7877. printer_id,
  7878. offline_for,
  7879. )
  7880. _connection_watchdog_last_attempt[printer_id] = now
  7881. continue
  7882. _connection_watchdog_last_attempt[printer_id] = now
  7883. recovered += 1
  7884. logger.warning(
  7885. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  7886. "rebuilding the client with a fresh session (last connect error: %s)",
  7887. printer_id,
  7888. offline_for,
  7889. PORT_MQTT,
  7890. client.last_connect_error or "none recorded",
  7891. )
  7892. # Async context, so this takes the hard-reset path: fresh client_id,
  7893. # paho's QoS 1 queue dropped. That matters — a project_file left
  7894. # unacked on the dead session would otherwise replay into the new
  7895. # one and trip 0500_4003 on the printer (#1136).
  7896. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  7897. except Exception as e:
  7898. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  7899. return recovered
  7900. async def _connection_watchdog_loop():
  7901. logger = logging.getLogger(__name__)
  7902. # Let the initial connects settle before judging anyone offline.
  7903. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  7904. while True:
  7905. try:
  7906. await _recover_dead_printer_sessions()
  7907. except asyncio.CancelledError:
  7908. break
  7909. except Exception as e:
  7910. logger.warning("Connection watchdog sweep failed: %s", e)
  7911. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  7912. def start_connection_watchdog():
  7913. global _connection_watchdog_task
  7914. if _connection_watchdog_task is None:
  7915. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  7916. logging.getLogger(__name__).info("Printer connection watchdog started")
  7917. def stop_connection_watchdog():
  7918. global _connection_watchdog_task
  7919. if _connection_watchdog_task:
  7920. _connection_watchdog_task.cancel()
  7921. _connection_watchdog_task = None
  7922. _connection_watchdog_last_attempt.clear()
  7923. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  7924. # Camera stream orphan cleanup
  7925. _camera_cleanup_task: asyncio.Task | None = None
  7926. CAMERA_CLEANUP_INTERVAL = 60
  7927. async def _camera_cleanup_loop():
  7928. """Periodically clean up orphaned ffmpeg processes."""
  7929. from backend.app.api.routes.camera import cleanup_orphaned_streams
  7930. while True:
  7931. try:
  7932. await cleanup_orphaned_streams()
  7933. except asyncio.CancelledError:
  7934. break
  7935. except Exception as e:
  7936. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  7937. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  7938. def start_camera_cleanup():
  7939. global _camera_cleanup_task
  7940. if _camera_cleanup_task is None:
  7941. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  7942. logging.getLogger(__name__).info("Camera stream cleanup started")
  7943. def stop_camera_cleanup():
  7944. global _camera_cleanup_task
  7945. if _camera_cleanup_task:
  7946. _camera_cleanup_task.cancel()
  7947. _camera_cleanup_task = None
  7948. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  7949. # ---------------------------------------------------------------------------
  7950. # Expected-print TTL eviction
  7951. # ---------------------------------------------------------------------------
  7952. def _evict_stale_expected_prints() -> None:
  7953. """Remove entries from _expected_prints / _expected_print_creators that are
  7954. older than _EXPECTED_PRINT_TTL_SECONDS.
  7955. This prevents unbounded growth when a print is registered (via
  7956. register_expected_print) but on_print_start never fires — e.g. because the
  7957. printer disconnects, the app restarts, or the print is started directly from
  7958. the printer panel without going through the queue.
  7959. """
  7960. # Use monotonic time so the TTL is unaffected by system clock adjustments
  7961. # (e.g. NTP sync, DST changes).
  7962. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  7963. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  7964. if not stale_keys:
  7965. return
  7966. evicted_archive_ids: set[int] = set()
  7967. for key in stale_keys:
  7968. archive_id = _expected_prints.pop(key, None)
  7969. if archive_id is not None:
  7970. evicted_archive_ids.add(archive_id)
  7971. _expected_print_creators.pop(key, None)
  7972. _expected_print_registered_at.pop(key, None)
  7973. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  7974. # that have no remaining live keys in _expected_prints (all variants
  7975. # were just evicted).
  7976. live_archive_ids = set(_expected_prints.values())
  7977. for archive_id in evicted_archive_ids:
  7978. if archive_id not in live_archive_ids:
  7979. _print_ams_mappings.pop(archive_id, None)
  7980. _print_cost_center_ids.pop(archive_id, None)
  7981. _print_plate_ids.pop(archive_id, None)
  7982. logging.getLogger(__name__).info(
  7983. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  7984. )
  7985. async def _expected_prints_cleanup_loop() -> None:
  7986. """Background task: periodically evict stale expected-print entries."""
  7987. while True:
  7988. try:
  7989. _evict_stale_expected_prints()
  7990. except asyncio.CancelledError:
  7991. raise
  7992. except Exception as e:
  7993. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  7994. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  7995. def start_expected_prints_cleanup() -> None:
  7996. global _expected_prints_cleanup_task
  7997. if _expected_prints_cleanup_task is None:
  7998. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  7999. logging.getLogger(__name__).info("Expected prints cleanup started")
  8000. def stop_expected_prints_cleanup() -> None:
  8001. global _expected_prints_cleanup_task
  8002. if _expected_prints_cleanup_task:
  8003. _expected_prints_cleanup_task.cancel()
  8004. _expected_prints_cleanup_task = None
  8005. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8006. # ---------------------------------------------------------------------------
  8007. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8008. # ---------------------------------------------------------------------------
  8009. _auth_cleanup_task: asyncio.Task | None = None
  8010. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8011. async def _run_auth_cleanup() -> None:
  8012. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8013. from backend.app.core.database import async_session
  8014. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8015. from backend.app.models.user_totp import UserTOTP
  8016. now = datetime.now(timezone.utc)
  8017. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8018. try:
  8019. async with async_session() as db:
  8020. stale_cutoff = now - timedelta(hours=1)
  8021. result = await db.execute(
  8022. select(UserTOTP).where(
  8023. UserTOTP.is_enabled.is_(False),
  8024. UserTOTP.created_at < stale_cutoff,
  8025. )
  8026. )
  8027. stale_records = result.scalars().all()
  8028. if stale_records:
  8029. for rec in stale_records:
  8030. await db.delete(rec)
  8031. await db.commit()
  8032. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8033. except Exception as e:
  8034. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8035. # Remove expired revoked-JTI entries (they are no longer needed once the
  8036. # original token's exp has passed — the token would be rejected by JWT
  8037. # signature verification regardless).
  8038. try:
  8039. async with async_session() as db:
  8040. await db.execute(
  8041. delete(AuthEphemeralToken).where(
  8042. AuthEphemeralToken.token_type == "revoked_jti",
  8043. AuthEphemeralToken.expires_at < now,
  8044. )
  8045. )
  8046. await db.commit()
  8047. except Exception as e:
  8048. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8049. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8050. # Events outside this window can never affect rate-limit decisions — they only
  8051. # consume DB space. Use the same window constant as the rate limiter so the
  8052. # two are always in sync.
  8053. try:
  8054. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8055. async with async_session() as db:
  8056. await db.execute(
  8057. delete(AuthRateLimitEvent).where(
  8058. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8059. )
  8060. )
  8061. await db.commit()
  8062. except Exception as e:
  8063. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8064. async def _auth_cleanup_loop() -> None:
  8065. """Periodic background task: run auth cleanup every hour."""
  8066. while True:
  8067. try:
  8068. await _run_auth_cleanup()
  8069. except asyncio.CancelledError:
  8070. break
  8071. except Exception as e:
  8072. logging.warning("Auth cleanup loop error: %s", e)
  8073. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8074. def start_auth_cleanup() -> None:
  8075. global _auth_cleanup_task
  8076. if _auth_cleanup_task is None:
  8077. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8078. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8079. def stop_auth_cleanup() -> None:
  8080. global _auth_cleanup_task
  8081. if _auth_cleanup_task:
  8082. _auth_cleanup_task.cancel()
  8083. _auth_cleanup_task = None
  8084. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8085. @asynccontextmanager
  8086. async def lifespan(app: FastAPI):
  8087. # Startup
  8088. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8089. # anything else can spawn tasks that might trip it.
  8090. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8091. install_proactor_reset_filter()
  8092. # Before init_db, so the warning is near the top of the log rather than
  8093. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8094. warn_if_running_on_uvloop()
  8095. await init_db()
  8096. # Browser download tokens expire after five minutes. Remove abandoned
  8097. # prepared ZIPs at startup as well as before each new preparation so a
  8098. # quiet appliance cannot retain an unusable bundle indefinitely.
  8099. try:
  8100. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8101. await prune_stale_printer_file_bundles()
  8102. except Exception as exc:
  8103. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8104. # After migrations, so the is_env_managed column exists. Never raises --
  8105. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8106. # startup (see apply_env_oidc_provider).
  8107. from backend.app.core.oidc_env import apply_env_oidc_provider
  8108. async with async_session() as oidc_db:
  8109. await apply_env_oidc_provider(oidc_db)
  8110. # Close out batches that finished before `completed` was a reachable status
  8111. # (#342). Without this the Batches tab opens on every batch created since
  8112. # the feature shipped, all still marked active. Never blocks startup.
  8113. try:
  8114. from backend.app.services.print_batch import backfill_batch_statuses
  8115. async with async_session() as batch_db:
  8116. await backfill_batch_statuses(batch_db)
  8117. except Exception as exc:
  8118. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8119. # Register an app-scoped httpx client for Bambu Cloud services so
  8120. # per-request BambuCloudService instances reuse the same connection pool
  8121. # (important for routes like /cloud/filament-info that chain many
  8122. # get_setting_detail calls). The shared client stores no region/token
  8123. # state, so the per-request ownership pattern that fixed the region-bleed
  8124. # bug is preserved.
  8125. import httpx as _httpx
  8126. from backend.app.services.bambu_cloud import set_shared_http_client
  8127. from backend.app.services.model_providers.makerworld.service import (
  8128. set_shared_http_client as set_shared_makerworld_http_client,
  8129. )
  8130. from backend.app.services.orca_cloud import (
  8131. set_shared_http_client as set_shared_orca_http_client,
  8132. )
  8133. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8134. set_shared_http_client(_shared_cloud_http_client)
  8135. # Reuse the same connection pool for MakerWorld — different host, same
  8136. # keep-alive pool saves a TLS handshake per request.
  8137. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8138. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8139. # each spun up (and never closed) its own client, leaking sockets.
  8140. set_shared_orca_http_client(_shared_cloud_http_client)
  8141. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8142. # This can happen when a print was cancelled mid-print on versions before this fix.
  8143. try:
  8144. async with async_session() as db:
  8145. from backend.app.models.print_queue import PrintQueueItem
  8146. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8147. aborted_items = result.scalars().all()
  8148. if aborted_items:
  8149. for item in aborted_items:
  8150. item.status = "cancelled"
  8151. await db.commit()
  8152. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8153. except Exception as e:
  8154. logging.warning("Failed to fix aborted queue items: %s", e)
  8155. # Restore debug logging state from previous session
  8156. await init_debug_logging()
  8157. # Set up printer manager callbacks
  8158. loop = asyncio.get_event_loop()
  8159. printer_manager.set_event_loop(loop)
  8160. printer_manager.set_status_change_callback(on_printer_status_change)
  8161. printer_manager.set_print_start_callback(on_print_start)
  8162. printer_manager.set_print_complete_callback(on_print_complete)
  8163. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8164. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8165. printer_manager.set_ams_change_callback(on_ams_change)
  8166. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8167. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8168. await printer_manager.load_awaiting_plate_clear_from_db()
  8169. # Layer change callback for external camera timelapse
  8170. async def on_layer_change(printer_id: int, layer_num: int):
  8171. """Capture timelapse frame on layer change + first layer notification."""
  8172. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8173. await tl_layer_change(printer_id, layer_num)
  8174. # #1867: bank a recent in-print frame so the finish-photo path has a
  8175. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8176. # #2547 added `on_print_progress` as a second driver — this one alone
  8177. # stops firing once the final layer begins.
  8178. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8179. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8180. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8181. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8182. # nozzle clean), so a bare layer_num check can fire minutes before the
  8183. # first real extrusion. We require gcode_state == RUNNING and
  8184. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8185. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8186. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8187. # edge fires later; _first_layer_notified stays clear until we actually send
  8188. # so a deferred re-evaluation can win. See issue #1837.
  8189. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8190. client = printer_manager.get_client(printer_id)
  8191. state = client.state if client else None
  8192. if not state or state.state != "RUNNING":
  8193. return
  8194. if state.mc_print_sub_stage not in (None, 0):
  8195. return
  8196. _first_layer_notified[printer_id] = True
  8197. try:
  8198. async with async_session() as db:
  8199. from backend.app.models.printer import Printer
  8200. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8201. printer = result.scalar_one_or_none()
  8202. if not printer:
  8203. return
  8204. printer_name = printer.name
  8205. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8206. total_layers = state.total_layers if state else 0
  8207. image_data = await _capture_snapshot_for_notification(
  8208. printer_id, printer, logging.getLogger(__name__)
  8209. )
  8210. await notification_service.on_first_layer_complete(
  8211. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8212. )
  8213. except Exception as e:
  8214. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8215. printer_manager.set_layer_change_callback(on_layer_change)
  8216. async def on_print_progress(printer_id: int, percent: int):
  8217. """#2547: keep the in-print frame bank fresh through the final layer.
  8218. `on_layer_change` stops the moment the last layer starts, which on the
  8219. H2C capture that closed #2547 left the bank stale for the three minutes
  8220. that layer took. Progress is the only field that keeps advancing there,
  8221. and it freezes before the End G-code runs — so banking on it stays
  8222. inside the print and never sees a swapped plate.
  8223. """
  8224. client = printer_manager.get_client(printer_id)
  8225. state = client.state if client else None
  8226. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8227. printer_manager.set_print_progress_callback(on_print_progress)
  8228. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8229. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8230. waiter = _bed_cool_waiters.get(printer_id)
  8231. if not waiter:
  8232. return
  8233. threshold = waiter["threshold"]
  8234. if bed_temp > threshold:
  8235. return
  8236. # Bed is at or below threshold — fire notification and remove waiter
  8237. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8238. if not waiter_info:
  8239. return # Another callback already handled it
  8240. bed_cool_logger = logging.getLogger(__name__)
  8241. bed_cool_logger.info(
  8242. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8243. bed_temp,
  8244. printer_id,
  8245. threshold,
  8246. )
  8247. try:
  8248. printer_info = printer_manager.get_printer(printer_id)
  8249. p_name = printer_info.name if printer_info else "Unknown"
  8250. async with async_session() as db:
  8251. await notification_service.on_bed_cooled(
  8252. printer_id=printer_id,
  8253. printer_name=p_name,
  8254. bed_temp=bed_temp,
  8255. threshold=threshold,
  8256. filename=waiter_info["filename"],
  8257. db=db,
  8258. )
  8259. except Exception as e:
  8260. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8261. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8262. async def on_drying_complete(printer_id: int, ams_id: int):
  8263. """Smart-plug auto-off-after-drying trigger (#1349).
  8264. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8265. manager walks all plugs linked to this printer and turns off only
  8266. the ones with ``auto_off_after_drying`` enabled, after their
  8267. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8268. dual-AMS dry that ends within the same MQTT push) call this once
  8269. per unit — the manager's ``_cancel_pending_off`` collapses
  8270. repeated scheduling on the same plug to one timer, so duplicate
  8271. fires are safe.
  8272. """
  8273. try:
  8274. async with async_session() as db:
  8275. await smart_plug_manager.on_drying_complete(printer_id, db)
  8276. except Exception as e:
  8277. logging.getLogger(__name__).warning(
  8278. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8279. printer_id,
  8280. ams_id,
  8281. e,
  8282. )
  8283. printer_manager.set_drying_complete_callback(on_drying_complete)
  8284. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  8285. """Surface the read-back result of a spool assignment to the UI (#2582).
  8286. The MQTT client confirms (or fails to confirm) that the tray telemetry
  8287. echoed back the filament id we pushed. We relay that as a websocket
  8288. event so the frontend can toast "loaded" / "assignment didn't take"
  8289. instead of the historic silent fire-and-forget, which made the
  8290. AMS→Studio hand-off feel random to users.
  8291. """
  8292. try:
  8293. from backend.app.services.spool_assignment_notifications import (
  8294. _slot_label_from_global_tray,
  8295. )
  8296. if ams_id == 255:
  8297. global_id = 254 + tray_id
  8298. elif ams_id >= 128:
  8299. global_id = ams_id
  8300. else:
  8301. global_id = ams_id * 4 + tray_id
  8302. slot_label = _slot_label_from_global_tray(global_id)
  8303. printer_info = printer_manager.get_printer(printer_id)
  8304. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8305. await ws_manager.broadcast(
  8306. {
  8307. "type": "spool_assignment_verified",
  8308. "printer_id": printer_id,
  8309. "printer_name": printer_name,
  8310. "ams_id": ams_id,
  8311. "tray_id": tray_id,
  8312. "slot": slot_label,
  8313. "verified": verified,
  8314. # Present on success: False means the filament setting landed
  8315. # but the K-profile (cali_idx) did not — the reporter's exact
  8316. # "loaded but no flow profile" symptom.
  8317. "kprofile_applied": detail.get("kprofile_applied", True),
  8318. # Present on failure: whether any tray telemetry was seen in
  8319. # the window (distinguishes "printer silent" from "printer
  8320. # stored something else").
  8321. "saw_tray": detail.get("saw_tray", False),
  8322. }
  8323. )
  8324. except Exception as e:
  8325. logging.getLogger(__name__).warning(
  8326. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  8327. printer_id,
  8328. ams_id,
  8329. tray_id,
  8330. e,
  8331. )
  8332. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  8333. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  8334. """Persist a mid-print tray change for completion-time attribution.
  8335. AMS filament backup switches trays without telling the slicer, so the
  8336. tray-change log is the only record of which spool fed which layers.
  8337. Keeping it only in memory meant a restart mid-print charged everything
  8338. to the tray that finished the job.
  8339. """
  8340. try:
  8341. from backend.app.services.usage_tracker import record_tray_change
  8342. async with async_session() as db:
  8343. await record_tray_change(db, printer_id, tray_global, layer_num)
  8344. except Exception as e:
  8345. logging.getLogger(__name__).warning(
  8346. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  8347. printer_id,
  8348. tray_global,
  8349. layer_num,
  8350. e,
  8351. )
  8352. printer_manager.set_tray_change_callback(on_tray_change)
  8353. # Initialize MQTT relay from settings
  8354. async with async_session() as db:
  8355. from backend.app.api.routes.settings import get_setting
  8356. mqtt_settings = {
  8357. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  8358. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  8359. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  8360. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  8361. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  8362. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  8363. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  8364. }
  8365. await mqtt_relay.configure(mqtt_settings)
  8366. # Restore MQTT smart plug subscriptions
  8367. if mqtt_settings.get("mqtt_enabled"):
  8368. from backend.app.models.smart_plug import SmartPlug
  8369. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  8370. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  8371. mqtt_plugs = result.scalars().all()
  8372. restored = 0
  8373. for plug in mqtt_plugs:
  8374. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  8375. restored += 1
  8376. if restored:
  8377. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  8378. # Connect to all active printers
  8379. async with async_session() as db:
  8380. await init_printer_connections(db)
  8381. # Auto-connect to Spoolman if enabled
  8382. async with async_session() as db:
  8383. from backend.app.api.routes.settings import get_setting
  8384. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  8385. spoolman_url = await get_setting(db, "spoolman_url")
  8386. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  8387. try:
  8388. client = await init_spoolman_client(spoolman_url)
  8389. if await client.health_check():
  8390. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  8391. # Ensure the 'tag' extra field exists for RFID/UUID storage
  8392. field_ok = await client.ensure_tag_extra_field()
  8393. if not field_ok:
  8394. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  8395. # Register the BambuStudio slicer-preset fields used by the
  8396. # spool-edit / assign flow. Spoolman rejects PATCHes with
  8397. # unknown extra keys, so these must exist before any update
  8398. # that touches them.
  8399. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  8400. if not await client.ensure_extra_field(field_name):
  8401. logging.warning(
  8402. "Spoolman extra field %r registration failed — "
  8403. "spool slicer-preset edits will return 502",
  8404. field_name,
  8405. )
  8406. else:
  8407. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  8408. except Exception as e:
  8409. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  8410. # Start the print scheduler
  8411. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  8412. # Start the smart plug scheduler for time-based on/off
  8413. smart_plug_manager.start_scheduler()
  8414. # Start the Home Assistant sensor poller (#1148)
  8415. ha_sensor_manager.start()
  8416. location_ha_sensor_manager.start()
  8417. # Resume any pending auto-offs that were interrupted by restart
  8418. await smart_plug_manager.resume_pending_auto_offs()
  8419. # Start the notification digest scheduler
  8420. notification_service.start_digest_scheduler()
  8421. # Start the GitHub backup scheduler
  8422. await github_backup_service.start_scheduler()
  8423. # Start the local backup scheduler
  8424. await local_backup_service.start_scheduler()
  8425. await obico_detection_service.start()
  8426. # Start the library trash sweeper (#1008)
  8427. await library_trash_service.start_scheduler()
  8428. # Start the archive auto-purge sweeper (#1008 follow-up)
  8429. await archive_purge_service.start_scheduler()
  8430. # Start AMS history recording
  8431. start_ams_history_recording()
  8432. # Start printer sensor (nozzle / bed / chamber) history recording
  8433. start_printer_sensor_history_recording()
  8434. # Start printer runtime tracking
  8435. start_runtime_tracking()
  8436. # Start SpoolBuddy device watchdog
  8437. start_spoolbuddy_watchdog()
  8438. # Start camera stream orphan cleanup
  8439. start_camera_cleanup()
  8440. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  8441. start_connection_watchdog()
  8442. # One-shot sweep for timelapse session directories orphaned by a crash
  8443. # or restart that happened mid-print (in-memory session tracking can't
  8444. # survive that, and nothing else reaps the leftover frames/output file)
  8445. try:
  8446. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  8447. removed = cleanup_orphaned_timelapse_sessions()
  8448. if removed:
  8449. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  8450. except Exception as e:
  8451. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  8452. # Start expected-print TTL eviction (prevents memory leak when prints are
  8453. # registered but on_print_start never fires)
  8454. start_expected_prints_cleanup()
  8455. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  8456. start_auth_cleanup()
  8457. from backend.app.services.printer_media import start_printer_download_cleanup
  8458. start_printer_download_cleanup()
  8459. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  8460. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  8461. from backend.app.services.loop_watchdog import start_loop_watchdog
  8462. start_loop_watchdog()
  8463. # Initialize virtual printer manager and sync from DB
  8464. from backend.app.services.virtual_printer import virtual_printer_manager
  8465. virtual_printer_manager.set_session_factory(async_session)
  8466. virtual_printer_manager.set_printer_manager(printer_manager)
  8467. try:
  8468. await virtual_printer_manager.sync_from_db()
  8469. logging.info("Virtual printer manager synced from database")
  8470. except Exception as e:
  8471. logging.warning("Failed to sync virtual printers: %s", e)
  8472. yield
  8473. # Shutdown
  8474. print_scheduler.stop()
  8475. smart_plug_manager.stop_scheduler()
  8476. ha_sensor_manager.stop()
  8477. location_ha_sensor_manager.stop()
  8478. notification_service.stop_digest_scheduler()
  8479. github_backup_service.stop_scheduler()
  8480. local_backup_service.stop_scheduler()
  8481. library_trash_service.stop_scheduler()
  8482. archive_purge_service.stop_scheduler()
  8483. obico_detection_service.stop()
  8484. stop_ams_history_recording()
  8485. stop_printer_sensor_history_recording()
  8486. stop_runtime_tracking()
  8487. stop_spoolbuddy_watchdog()
  8488. stop_camera_cleanup()
  8489. stop_connection_watchdog()
  8490. from backend.app.services.loop_watchdog import stop_loop_watchdog
  8491. stop_loop_watchdog()
  8492. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  8493. # cleanly rather than waiting on a queue that nothing will ever fill.
  8494. try:
  8495. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  8496. await shutdown_all_broadcasters()
  8497. except Exception as e:
  8498. logging.warning("Failed to shut down camera broadcasters: %s", e)
  8499. stop_expected_prints_cleanup()
  8500. stop_auth_cleanup()
  8501. from backend.app.services.printer_media import stop_printer_download_cleanup
  8502. await stop_printer_download_cleanup()
  8503. printer_manager.disconnect_all()
  8504. await close_spoolman_client()
  8505. # Stop all virtual printer services
  8506. await virtual_printer_manager.stop_all()
  8507. await mqtt_smart_plug_service.disconnect(timeout=2)
  8508. await mqtt_relay.disconnect(timeout=2)
  8509. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  8510. set_shared_http_client(None)
  8511. set_shared_makerworld_http_client(None)
  8512. set_shared_orca_http_client(None)
  8513. await _shared_cloud_http_client.aclose()
  8514. # Checkpoint WAL (SQLite only) and close all database connections
  8515. from backend.app.core.db_dialect import is_sqlite
  8516. if is_sqlite():
  8517. try:
  8518. async with engine.begin() as conn:
  8519. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  8520. logging.info("WAL checkpoint completed")
  8521. except Exception as e:
  8522. logging.warning("WAL checkpoint failed: %s", e)
  8523. await engine.dispose()
  8524. app = FastAPI(
  8525. title=app_settings.app_name,
  8526. description="Archive and manage Bambu Lab 3MF files",
  8527. version=APP_VERSION,
  8528. lifespan=lifespan,
  8529. )
  8530. # =============================================================================
  8531. # Authentication Middleware - Secures ALL API routes by default
  8532. # =============================================================================
  8533. # Public routes that don't require authentication even when auth is enabled
  8534. PUBLIC_API_ROUTES = {
  8535. # Auth routes needed before/during login
  8536. "/api/v1/auth/status",
  8537. "/api/v1/auth/login",
  8538. "/api/v1/auth/setup", # Needed for initial setup and recovery
  8539. # Advanced auth status needed for login page
  8540. "/api/v1/auth/advanced-auth/status",
  8541. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  8542. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  8543. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  8544. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  8545. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  8546. # OIDC routes that must be reachable without a JWT
  8547. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  8548. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  8549. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  8550. # Connected apps: the app's server swaps a code for the user's identity,
  8551. # authenticated by its client secret rather than a login token.
  8552. "/api/v1/connect/token",
  8553. # Version check for updates (no sensitive data)
  8554. "/api/v1/updates/version",
  8555. # Metrics endpoint handles its own prometheus_token authentication
  8556. "/api/v1/metrics",
  8557. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  8558. # this BEFORE a JWT is available to pick up the firstboot wizard's
  8559. # hostname / timezone / locale and the chrony NTP-gate state. The
  8560. # response contains user-set defaults and a public sync flag — no
  8561. # secrets. Without this entry the global auth middleware returns 401
  8562. # before the route handler runs, regardless of the route's own
  8563. # "no auth required" intent.
  8564. "/api/v1/system/appliance",
  8565. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  8566. # authenticates with a long-lived ``camwall``-scoped token in the query
  8567. # string — exactly like the camera streams two lists below, and for the same
  8568. # reason (no header to put a JWT in). "Public" here only means the middleware
  8569. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  8570. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  8571. # plain ``camera_stream`` token does NOT open this door.
  8572. "/api/v1/camwall/printers",
  8573. }
  8574. # Route prefixes that are public (for routes with dynamic segments)
  8575. PUBLIC_API_PREFIXES = [
  8576. # WebSocket connections handle their own auth
  8577. "/api/v1/ws",
  8578. # OIDC authorize redirects — include provider_id in path
  8579. "/api/v1/auth/oidc/authorize/",
  8580. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  8581. # a phone with no session, so no header can carry a JWT — the single-use
  8582. # capability token in the path IS the credential (same reasoning as the
  8583. # /dl/ slicer downloads below). The route grants nothing beyond writing
  8584. # good/reject on the one archive the token was minted for.
  8585. "/api/v1/archives/confirm/",
  8586. ]
  8587. # Route patterns that are public (read-only display data)
  8588. # These are checked with "in path" - needed because browsers load images/videos
  8589. # via <img src> and <video src> which don't include Authorization headers
  8590. PUBLIC_API_PATTERNS = [
  8591. # Thumbnails
  8592. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  8593. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  8594. # Images and media
  8595. "/photos/", # /archives/{id}/photos/{filename}
  8596. "/project-image/", # /archives/{id}/project-image/{path}
  8597. "/qrcode", # /archives/{id}/qrcode
  8598. "/timelapse", # /archives/{id}/timelapse (video)
  8599. "/cover", # /printers/{id}/cover
  8600. "/icon", # /external-links/{id}/icon
  8601. # Camera (streams loaded via <img> tag)
  8602. "/camera/stream", # /printers/{id}/camera/stream
  8603. "/camera/snapshot", # /printers/{id}/camera/snapshot
  8604. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  8605. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  8606. # string (same reasoning as the camera streams above — no header to carry a
  8607. # JWT). "Public" only means the middleware steps aside; the route still runs
  8608. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  8609. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  8610. "/overlay-status", # /printers/{id}/overlay-status
  8611. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  8612. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  8613. # download token in the URL path instead.
  8614. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  8615. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  8616. # and these patterns match by substring. Without its own entry the middleware
  8617. # 401s the slicer's header-less request before the route's token check runs,
  8618. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  8619. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  8620. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  8621. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  8622. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  8623. ]
  8624. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  8625. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  8626. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  8627. Format: comma-separated list of ``scheme://host[:port]`` origins.
  8628. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  8629. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  8630. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  8631. Invalid entries are dropped with a warning rather than failing startup, so
  8632. a typo in one origin doesn't take the whole deployment down.
  8633. """
  8634. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  8635. if not raw:
  8636. return ()
  8637. valid: list[str] = []
  8638. for item in raw.split(","):
  8639. candidate = item.strip()
  8640. if not candidate:
  8641. continue
  8642. try:
  8643. parsed = urlparse(candidate)
  8644. except ValueError as e:
  8645. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  8646. continue
  8647. if parsed.scheme not in ("http", "https"):
  8648. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  8649. continue
  8650. if not parsed.netloc:
  8651. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  8652. continue
  8653. if parsed.path and parsed.path != "/":
  8654. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  8655. continue
  8656. if parsed.query or parsed.fragment:
  8657. _security_headers_logger.warning(
  8658. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  8659. )
  8660. continue
  8661. if "*" in parsed.netloc:
  8662. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  8663. continue
  8664. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  8665. if valid:
  8666. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  8667. return tuple(valid)
  8668. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  8669. def _frame_ancestors(default_value: str) -> str:
  8670. """Compose the ``frame-ancestors`` CSP directive (#1191).
  8671. ``default_value`` is the strict directive used when the operator has not
  8672. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  8673. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  8674. Settings URL builder's preview). When trusted origins
  8675. are configured, ``'self'`` is always included so same-origin embedding never
  8676. breaks even if an operator forgets to add their own origin to the list.
  8677. """
  8678. if _TRUSTED_FRAME_ORIGINS:
  8679. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  8680. return f"frame-ancestors {default_value};"
  8681. # The Vite-emitted STEP preview worker chunk (#2976): src/workers/
  8682. # stepPreview.worker.ts becomes /assets/stepPreview.worker-<hash>.js. Matched
  8683. # exactly so the eval-relaxed CSP below can never apply to any other asset.
  8684. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  8685. @app.middleware("http")
  8686. async def security_headers_middleware(request, call_next):
  8687. """Add standard HTTP security headers to every response."""
  8688. # Per-request nonce stamped into `script-src` (#1460). On its own this
  8689. # changes nothing for Bambuddy's own pages — index.html has no inline
  8690. # scripts since the SW registration moved to /sw-register.js. The reason
  8691. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  8692. # script injected into the HTML on the edge, with a fresh hash on every
  8693. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  8694. # it clones the same nonce onto its injected <script>, and the inline
  8695. # script passes the policy without us needing 'unsafe-inline'. See
  8696. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  8697. csp_nonce = secrets.token_urlsafe(16)
  8698. # Routes that render their own HTML need it too, or their inline script is
  8699. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  8700. # one that does: it submits its own form so a verdict still costs one tap.
  8701. request.state.csp_nonce = csp_nonce
  8702. response = await call_next(request)
  8703. response.headers["X-Content-Type-Options"] = "nosniff"
  8704. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  8705. # browsers honour CSP frame-ancestors instead, and the legacy
  8706. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  8707. # When operators have explicitly allowlisted trusted frame origins (#1191
  8708. # — typically Home Assistant on a different port), drop X-Frame-Options
  8709. # and let the CSP-side frame-ancestors directive govern embedding.
  8710. if not _TRUSTED_FRAME_ORIGINS:
  8711. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  8712. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  8713. # Content-Security-Policy for the React SPA.
  8714. # Notes:
  8715. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  8716. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  8717. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  8718. # - media-src blob:: timelapse video player uses Blob URLs.
  8719. # - font-src data:: some icon fonts are embedded as data URIs.
  8720. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  8721. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  8722. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  8723. # default CSP would render a blank page.
  8724. response.headers["Content-Security-Policy"] = (
  8725. "default-src 'self'; "
  8726. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  8727. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  8728. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  8729. "connect-src 'self'; "
  8730. "font-src 'self' data: https://fonts.gstatic.com; "
  8731. "worker-src 'self' blob:; "
  8732. "object-src 'none'; "
  8733. "base-uri 'self'; " + _frame_ancestors("'none'")
  8734. )
  8735. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  8736. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  8737. # its emscripten/embind glue generates invoker functions with `new
  8738. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  8739. # worker is governed by the policy delivered with the WORKER SCRIPT's
  8740. # own response — not the document's — so relaxing it here confines
  8741. # eval to that DOM-less worker context. The document policy below
  8742. # stays nonce-strict, and this response header has no effect when the
  8743. # file is merely fetched (a fetch's CSP is enforced against the
  8744. # requesting document, not the resource's own headers).
  8745. response.headers["Content-Security-Policy"] = (
  8746. "default-src 'self'; "
  8747. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  8748. "connect-src 'self'; "
  8749. "object-src 'none'; "
  8750. "base-uri 'self'; " + _frame_ancestors("'none'")
  8751. )
  8752. else:
  8753. # The streaming overlay is embedded same-origin by the URL builder's
  8754. # preview in Settings (#1422), so this branch allows 'self'.
  8755. # Embedding from anywhere else is still refused: 'self'
  8756. # only permits a framer on this origin, which is Bambuddy's own UI, so
  8757. # a clickjacking page on another host is blocked exactly as before.
  8758. # (The overlay draws status over a camera feed and its only interactive
  8759. # element is the logo link, so there is nothing to bait a click into
  8760. # even from a same-origin framer.) Cross-origin embedding of the
  8761. # overlay — Home Assistant on another port — remains what
  8762. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  8763. # allowlist in.
  8764. #
  8765. # The connected-app consent page (/connect/authorize) gets the same
  8766. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  8767. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  8768. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  8769. # requires every ancestor to be this origin, so a foreign page -- a
  8770. # sidebar link's site included -- still cannot frame the consent
  8771. # screen to bait a click.
  8772. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  8773. # 'wasm-unsafe-eval' permits WebAssembly compilation ONLY — it does
  8774. # not allow eval()/Function() for JS, unlike 'unsafe-eval'. Needed by
  8775. # the STEP preview, which triangulates in the browser via OpenCascade
  8776. # compiled to WASM (#2976). Browsers that predate the keyword ignore
  8777. # it and simply keep blocking wasm, so this never widens JS execution.
  8778. response.headers["Content-Security-Policy"] = (
  8779. "default-src 'self'; "
  8780. f"script-src 'self' 'wasm-unsafe-eval' 'nonce-{csp_nonce}'; "
  8781. "style-src 'self' 'unsafe-inline'; "
  8782. "img-src 'self' data: blob:; "
  8783. "media-src 'self' blob:; "
  8784. "connect-src 'self' ws: wss:; "
  8785. "font-src 'self' data:; "
  8786. "object-src 'none'; "
  8787. "base-uri 'self'; "
  8788. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  8789. )
  8790. if request.url.scheme == "https":
  8791. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  8792. return response
  8793. @app.middleware("http")
  8794. async def auth_middleware(request, call_next):
  8795. """Enforce authentication on all API routes when auth is enabled.
  8796. This middleware provides defense-in-depth by checking auth at the API gateway level,
  8797. regardless of whether individual routes have auth dependencies.
  8798. """
  8799. from starlette.responses import JSONResponse
  8800. path = request.url.path
  8801. # Only apply to API routes
  8802. if not path.startswith("/api/"):
  8803. return await call_next(request)
  8804. # Allow public routes
  8805. if path in PUBLIC_API_ROUTES:
  8806. return await call_next(request)
  8807. # Allow public prefixes
  8808. for prefix in PUBLIC_API_PREFIXES:
  8809. if path.startswith(prefix):
  8810. return await call_next(request)
  8811. # Allow public patterns (read-only display data like thumbnails)
  8812. for pattern in PUBLIC_API_PATTERNS:
  8813. if pattern in path:
  8814. return await call_next(request)
  8815. # Check if auth is enabled. Fail CLOSED on any exception during the
  8816. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  8817. # an attacker who could force a DB exception (e.g. file-descriptor
  8818. # exhaustion via login flood) bypass auth on every protected endpoint.
  8819. try:
  8820. async with async_session() as db:
  8821. from backend.app.core.auth import is_auth_enabled
  8822. auth_enabled = await is_auth_enabled(db)
  8823. if not auth_enabled:
  8824. # Auth disabled, allow all requests
  8825. return await call_next(request)
  8826. except Exception:
  8827. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  8828. return JSONResponse(
  8829. status_code=503,
  8830. content={"detail": "Authentication service temporarily unavailable"},
  8831. )
  8832. # Auth is enabled - require valid token
  8833. auth_header = request.headers.get("Authorization")
  8834. x_api_key = request.headers.get("X-API-Key")
  8835. # Check for API key auth first
  8836. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  8837. # API key authentication - let the request through to be validated by route handler
  8838. # API keys are validated per-route since they have different permission levels
  8839. return await call_next(request)
  8840. # Check for JWT auth
  8841. if not auth_header or not auth_header.startswith("Bearer "):
  8842. return JSONResponse(
  8843. status_code=401,
  8844. content={"detail": "Authentication required"},
  8845. headers={"WWW-Authenticate": "Bearer"},
  8846. )
  8847. # Validate JWT token
  8848. import jwt
  8849. try:
  8850. from backend.app.core.auth import (
  8851. ALGORITHM,
  8852. SECRET_KEY,
  8853. _is_token_fresh,
  8854. get_user_by_username,
  8855. is_jti_revoked,
  8856. )
  8857. token = auth_header.replace("Bearer ", "")
  8858. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  8859. username = payload.get("sub")
  8860. if not username:
  8861. raise ValueError("No username in token")
  8862. jti = payload.get("jti")
  8863. if not jti:
  8864. raise ValueError("No jti in token")
  8865. iat = payload.get("iat")
  8866. # Verify user exists, is active, and token is still fresh (L-R8-A).
  8867. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  8868. # this session so the gateway adds a single pooled checkout, not two (#2572).
  8869. async with async_session() as db:
  8870. if await is_jti_revoked(jti, db):
  8871. return JSONResponse(
  8872. status_code=401,
  8873. content={"detail": "Token has been revoked"},
  8874. headers={"WWW-Authenticate": "Bearer"},
  8875. )
  8876. user = await get_user_by_username(db, username)
  8877. if not user or not user.is_active:
  8878. return JSONResponse(
  8879. status_code=401,
  8880. content={"detail": "User not found or inactive"},
  8881. headers={"WWW-Authenticate": "Bearer"},
  8882. )
  8883. if not _is_token_fresh(iat, user):
  8884. return JSONResponse(
  8885. status_code=401,
  8886. content={"detail": "Token no longer valid"},
  8887. headers={"WWW-Authenticate": "Bearer"},
  8888. )
  8889. except jwt.ExpiredSignatureError:
  8890. return JSONResponse(
  8891. status_code=401,
  8892. content={"detail": "Token has expired"},
  8893. headers={"WWW-Authenticate": "Bearer"},
  8894. )
  8895. except (jwt.InvalidTokenError, ValueError, Exception):
  8896. return JSONResponse(
  8897. status_code=401,
  8898. content={"detail": "Invalid token"},
  8899. headers={"WWW-Authenticate": "Bearer"},
  8900. )
  8901. return await call_next(request)
  8902. @app.middleware("http")
  8903. async def trace_id_middleware(request, call_next):
  8904. """Stamp every HTTP request with a trace ID and echo it back.
  8905. Decorated AFTER auth_middleware on purpose: Starlette stacks
  8906. @app.middleware decorators LIFO, so the last-decorated runs first
  8907. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  8908. which means auth-middleware log lines (and every line emitted on the
  8909. way down to and back from the route handler) all carry the same
  8910. trace ID. If we put it before auth, auth's logs would be stamped
  8911. with the *previous* request's ID — useless for correlation.
  8912. Honours an inbound ``X-Trace-Id`` header so callers running their
  8913. own tracing can correlate their span IDs with our log lines, but
  8914. only if the value passes the whitelist gate in
  8915. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  8916. rejected (too long, contains control chars, etc.) silently triggers
  8917. a freshly minted server-side ID rather than failing the request.
  8918. The minted (or echoed) ID is set on a ContextVar so that every log
  8919. record emitted during the request — application logs *and* uvicorn's
  8920. access log — carries it via TraceIDFilter, and is also written to
  8921. the ``X-Trace-Id`` response header so clients can pin a server-side
  8922. log search to the exact request they made.
  8923. """
  8924. from backend.app.core.trace import (
  8925. generate_trace_id,
  8926. normalise_inbound_trace_id,
  8927. trace_id_var,
  8928. )
  8929. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  8930. trace_id = inbound if inbound is not None else generate_trace_id()
  8931. token = trace_id_var.set(trace_id)
  8932. try:
  8933. response = await call_next(request)
  8934. finally:
  8935. # Reset the ContextVar so a record emitted in a totally
  8936. # unrelated background task that just happens to inherit this
  8937. # context doesn't keep referencing this request's ID forever.
  8938. # In practice ContextVar.reset is best-effort under asyncio
  8939. # task-spawn semantics, but the cost is one attribute write so
  8940. # we may as well do it.
  8941. trace_id_var.reset(token)
  8942. response.headers["X-Trace-Id"] = trace_id
  8943. return response
  8944. # API routes
  8945. app.include_router(auth.router, prefix=app_settings.api_prefix)
  8946. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  8947. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  8948. app.include_router(users.router, prefix=app_settings.api_prefix)
  8949. app.include_router(groups.router, prefix=app_settings.api_prefix)
  8950. app.include_router(printers.router, prefix=app_settings.api_prefix)
  8951. app.include_router(archives.router, prefix=app_settings.api_prefix)
  8952. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  8953. app.include_router(finance.router, prefix=app_settings.api_prefix)
  8954. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  8955. app.include_router(labels.router, prefix=app_settings.api_prefix)
  8956. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  8957. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  8958. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  8959. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  8960. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  8961. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  8962. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  8963. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  8964. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  8965. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  8966. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  8967. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  8968. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  8969. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  8970. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  8971. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  8972. app.include_router(updates.router, prefix=app_settings.api_prefix)
  8973. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  8974. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  8975. app.include_router(camera.router, prefix=app_settings.api_prefix)
  8976. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  8977. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  8978. app.include_router(projects.router, prefix=app_settings.api_prefix)
  8979. app.include_router(library.router, prefix=app_settings.api_prefix)
  8980. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  8981. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  8982. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  8983. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  8984. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  8985. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  8986. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  8987. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  8988. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  8989. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  8990. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  8991. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  8992. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  8993. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  8994. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  8995. app.include_router(system.router, prefix=app_settings.api_prefix)
  8996. app.include_router(support.router, prefix=app_settings.api_prefix)
  8997. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  8998. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  8999. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9000. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9001. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9002. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9003. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9004. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9005. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9006. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9007. # Serve static files (React build)
  9008. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9009. app.mount(
  9010. "/assets",
  9011. StaticFiles(directory=app_settings.static_dir / "assets"),
  9012. name="assets",
  9013. )
  9014. if (app_settings.static_dir / "img").exists():
  9015. app.mount(
  9016. "/img",
  9017. StaticFiles(directory=app_settings.static_dir / "img"),
  9018. name="img",
  9019. )
  9020. if (app_settings.static_dir / "icons").exists():
  9021. app.mount(
  9022. "/icons",
  9023. StaticFiles(directory=app_settings.static_dir / "icons"),
  9024. name="icons",
  9025. )
  9026. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9027. # falls through to the SPA catch-all and returns index.html, which the
  9028. # browser's font sanitizer rejects ("downloadable font: rejected by
  9029. # sanitizer").
  9030. if (app_settings.static_dir / "fonts").exists():
  9031. app.mount(
  9032. "/fonts",
  9033. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9034. name="fonts",
  9035. )
  9036. @app.get("/")
  9037. async def serve_frontend():
  9038. """Serve the React frontend."""
  9039. index_file = app_settings.static_dir / "index.html"
  9040. if index_file.exists():
  9041. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9042. return {
  9043. "message": "Bambuddy API",
  9044. "docs": "/docs",
  9045. "frontend": "Build and place React app in /static directory",
  9046. }
  9047. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9048. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9049. # forever, but the HTML wrapping it is the only file that knows which hash
  9050. # is current. Without explicit cache-control headers Chromium decides
  9051. # heuristically (typically 10% of the time since Last-Modified) and on
  9052. # long-running kiosks happily serves stale HTML across browser restarts.
  9053. # That stale HTML references an old bundle hash, the old bundle is also
  9054. # in the disk cache, and the user ends up running pre-update JS forever
  9055. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9056. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9057. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9058. @app.get("/health")
  9059. async def health_check():
  9060. """Health check endpoint."""
  9061. return {"status": "healthy"}
  9062. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9063. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9064. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9065. # in deployment debugging.
  9066. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9067. async def serve_manifest():
  9068. """Serve PWA manifest."""
  9069. manifest_file = app_settings.static_dir / "manifest.json"
  9070. if manifest_file.exists():
  9071. return FileResponse(manifest_file, media_type="application/manifest+json")
  9072. return {"error": "Manifest not found"}
  9073. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9074. async def serve_service_worker():
  9075. """Serve service worker."""
  9076. sw_file = app_settings.static_dir / "sw.js"
  9077. if sw_file.exists():
  9078. return FileResponse(
  9079. sw_file,
  9080. media_type="application/javascript",
  9081. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9082. )
  9083. return {"error": "Service worker not found"}
  9084. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9085. async def serve_sw_register():
  9086. """Serve the service-worker registration bootstrap script.
  9087. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9088. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9089. """
  9090. reg_file = app_settings.static_dir / "sw-register.js"
  9091. if reg_file.exists():
  9092. return FileResponse(reg_file, media_type="application/javascript")
  9093. return {"error": "sw-register.js not found"}
  9094. # ── GCode viewer static files ────────────────────────────────────────────────
  9095. # Catch-all route for React Router (must be last)
  9096. @app.get("/{full_path:path}")
  9097. async def serve_spa(full_path: str):
  9098. """Serve React app for client-side routing."""
  9099. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9100. if full_path.startswith("api/"):
  9101. from fastapi import HTTPException
  9102. raise HTTPException(status_code=404, detail="Not found")
  9103. index_file = app_settings.static_dir / "index.html"
  9104. if index_file.exists():
  9105. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9106. return {"error": "Frontend not built"}