main.py 360 KB

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