main.py 390 KB

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