main.py 357 KB

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