Просмотр исходного кода

Cleanup unused functions; remove dynamicCR, hard-code to false

Deniz Cengiz 1 год назад
Родитель
Сommit
2abc70be77

+ 0 - 149
Trio/Sources/APS/APSManager.swift

@@ -715,10 +715,6 @@ final class BaseAPSManager: APSManager, Injectable {
                 guard self.privateContext.hasChanges else { return }
                 try self.privateContext.save()
                 debug(.apsManager, "Determination enacted. Enacted: \(wasEnacted)")
-
-                Task.detached(priority: .low) {
-                    await self.statistics()
-                }
             }
         } catch {
             debug(
@@ -904,125 +900,6 @@ final class BaseAPSManager: APSManager, Injectable {
         }
     }
 
-    // TODO: - Refactor this whole shit here...
-
-    // Add to statistics.JSON for upload to NS.
-    private func statistics() async {
-        let now = Date()
-        if settingsManager.settings.uploadStats != nil {
-            let hour = Calendar.current.component(.hour, from: now)
-            guard hour > 20 else {
-                return
-            }
-
-            // MARK: - Core Data related
-
-            async let glucoseStats = glucoseForStats()
-            async let lastLoopForStats = lastLoopForStats()
-            async let carbTotal = carbsForStats()
-            async let preferences = settingsManager.preferences
-
-            let loopStats = await loopStats(oneDayGlucose: Double(rawValue: (await glucoseStats?.oneDayGlucose.readings)!) ?? 0.0)
-
-            // Only save and upload once per day
-            guard (-1 * (await lastLoopForStats ?? .distantPast).timeIntervalSinceNow.hours) > 22 else { return }
-
-            let units = settingsManager.settings.units
-
-            // MARK: - Not Core Data related stuff
-
-            let pref = await preferences
-            var algo_ = "Oref0"
-
-            if pref.sigmoid, pref.enableDynamicCR {
-                algo_ = "Dynamic ISF + CR: Sigmoid"
-            } else if pref.sigmoid, !pref.enableDynamicCR {
-                algo_ = "Dynamic ISF: Sigmoid"
-            } else if pref.useNewFormula, pref.enableDynamicCR {
-                algo_ = "Dynamic ISF + CR: Logarithmic"
-            } else if pref.useNewFormula, !pref.sigmoid,!pref.enableDynamicCR {
-                algo_ = "Dynamic ISF: Logarithmic"
-            }
-            let af = pref.adjustmentFactor
-            let insulin_type = pref.curve
-            let buildDate = BuildDetails.shared.buildDate()
-            let version = Bundle.main.releaseVersionNumber
-            let build = Bundle.main.buildVersionNumber
-
-            var branch = BuildDetails.shared.branchAndSha
-
-            let copyrightNotice_ = Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String ?? ""
-            let pump_ = pumpManager?.localizedTitle ?? ""
-            let cgm = settingsManager.settings.cgm
-            let file = OpenAPS.Monitor.statistics
-            var iPa: Decimal = 75
-            if pref.useCustomPeakTime {
-                iPa = pref.insulinPeakTime
-            } else if pref.curve.rawValue == "rapid-acting" {
-                iPa = 65
-            } else if pref.curve.rawValue == "ultra-rapid" {
-                iPa = 50
-            }
-
-            // Insulin placeholder
-            let insulin = Ins(
-                TDD: 0,
-                bolus: 0,
-                temp_basal: 0,
-                scheduled_basal: 0,
-                total_average: 0
-            )
-            guard let processedGlucoseStats = await glucoseStats else { return }
-
-            let eA1cDisplayUnit = processedGlucoseStats.eA1cDisplayUnit
-
-            let dailystat = await Statistics(
-                created_at: Date(),
-                iPhone: UIDevice.current.getDeviceId,
-                iOS: UIDevice.current.getOSInfo,
-                Build_Version: version ?? "",
-                Build_Number: build ?? "1",
-                Branch: branch,
-                CopyRightNotice: String(copyrightNotice_.prefix(32)),
-                Build_Date: buildDate ?? Date(),
-                Algorithm: algo_,
-                AdjustmentFactor: af,
-                Pump: pump_,
-                CGM: cgm.rawValue,
-                insulinType: insulin_type.rawValue,
-                peakActivityTime: iPa,
-                Carbs_24h: await carbTotal,
-                GlucoseStorage_Days: Decimal(roundDouble(Double(rawValue: processedGlucoseStats.numberofDays) ?? 0.0, 1)),
-                Statistics: Stats(
-                    Distribution: processedGlucoseStats.TimeInRange,
-                    Glucose: processedGlucoseStats.avg,
-                    EstimatedA1c: processedGlucoseStats.hbs,
-                    Units: Units(Glucose: units.rawValue, EstimatedA1c: eA1cDisplayUnit.rawValue),
-                    LoopCycles: loopStats,
-                    Insulin: insulin,
-                    Variance: processedGlucoseStats.variance
-                )
-            )
-            storage.save(dailystat, as: file)
-
-            await saveStatsToCoreData()
-        }
-    }
-
-    private func saveStatsToCoreData() async {
-        await privateContext.perform {
-            let saveStatsCoreData = StatsData(context: self.privateContext)
-            saveStatsCoreData.lastrun = Date()
-
-            do {
-                guard self.privateContext.hasChanges else { return }
-                try self.privateContext.save()
-            } catch {
-                print(error.localizedDescription)
-            }
-        }
-    }
-
     private func lastLoopForStats() async -> Date? {
         let requestStats = StatsData.fetchRequest() as NSFetchRequest<StatsData>
         let sortStats = NSSortDescriptor(key: "lastrun", ascending: false)
@@ -1039,32 +916,6 @@ final class BaseAPSManager: APSManager, Injectable {
         }
     }
 
-    private func carbsForStats() async -> Decimal {
-        let requestCarbs = CarbEntryStored.fetchRequest() as NSFetchRequest<CarbEntryStored>
-        let daysAgo = Date().addingTimeInterval(-1.days.timeInterval)
-        requestCarbs.predicate = NSPredicate(format: "carbs > 0 AND date > %@", daysAgo as NSDate)
-        requestCarbs.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
-
-        return await privateContext.perform {
-            do {
-                let carbs = try self.privateContext.fetch(requestCarbs)
-                debugPrint(
-                    "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) fetched carbs"
-                )
-
-                return carbs.reduce(0) { sum, meal in
-                    let mealCarbs = Decimal(string: "\(meal.carbs)") ?? Decimal.zero
-                    return sum + mealCarbs
-                }
-            } catch {
-                debugPrint(
-                    "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while fetching carbs"
-                )
-                return 0
-            }
-        }
-    }
-
     private func loopStats(oneDayGlucose: Double) async -> LoopCycles {
         let requestLSR = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
         requestLSR.predicate = NSPredicate(

+ 5 - 0
Trio/Sources/APS/OpenAPS/OpenAPS.swift

@@ -520,6 +520,11 @@ final class OpenAPS {
                 adjustedPreferences.lowTemptargetLowersSensitivity = false
                 debug(.openAPS, "Setting lowTTlowersSens to false due to insufficient autosensMax: \(preferences.autosensMax)")
             }
+
+            // FIXME: remove this at a later release; hard code it to false for now
+            if preferences.enableDynamicCR {
+                adjustedPreferences.enableDynamicCR = false
+            }
         }
 
         do {

+ 6 - 3
Trio/Sources/Localizations/Main/Localizable.xcstrings

@@ -70220,6 +70220,9 @@
         }
       }
     },
+    "Dynamic Insulin Sensitivity" : {
+
+    },
     "Dynamic ISF" : {
 
     },
@@ -100596,9 +100599,6 @@
         }
       }
     },
-    "Insufficient insulin data. Cannot enable dynamic ISF." : {
-
-    },
     "Insulin" : {
       "comment" : "Title for insulin-related statistics",
       "localizations" : {
@@ -182164,6 +182164,9 @@
         }
       }
     },
+    "Trio has only been actively used and looping for less than seven days. Cannot enable dynamic ISF." : {
+
+    },
     "Trio has successfully imported your default Nightscout profile and stored it as therapy settings. " : {
       "localizations" : {
         "bg" : {

+ 2 - 1
Trio/Sources/Models/Preferences.swift

@@ -298,8 +298,9 @@ extension Preferences: Decodable {
             preferences.sigmoid = sigmoid
         }
 
+        // FIXME: remove this at a later release; hard code it to false for now
         if let enableDynamicCR = try? container.decode(Bool.self, forKey: .enableDynamicCR) {
-            preferences.enableDynamicCR = enableDynamicCR
+            preferences.enableDynamicCR = false
         }
 
         if let useNewFormula = try? container.decode(Bool.self, forKey: .useNewFormula) {

+ 1 - 3
Trio/Sources/Modules/DynamicSettings/DynamicSettingsStateModel.swift

@@ -27,7 +27,6 @@ extension DynamicSettings {
 
         @Published var hasValidTDD: Bool = false
         @Published var useNewFormula: Bool = false
-        @Published var enableDynamicCR: Bool = false
         @Published var sigmoid: Bool = false
         @Published var adjustmentFactor: Decimal = 0.8
         @Published var adjustmentFactorSigmoid: Decimal = 0.5
@@ -53,7 +52,6 @@ extension DynamicSettings {
             subscribePreferencesSetting(\.useNewFormula, on: $useNewFormula) { _ in }
             subscribePreferencesSetting(\.sigmoid, on: $sigmoid) { _ in }
 
-            subscribePreferencesSetting(\.enableDynamicCR, on: $enableDynamicCR) { enableDynamicCR = $0 }
             subscribePreferencesSetting(\.adjustmentFactor, on: $adjustmentFactor) { adjustmentFactor = $0 }
             subscribePreferencesSetting(\.adjustmentFactorSigmoid, on: $adjustmentFactorSigmoid) { adjustmentFactorSigmoid = $0 }
             subscribePreferencesSetting(\.weightPercentage, on: $weightPercentage) { weightPercentage = $0 }
@@ -84,7 +82,7 @@ extension DynamicSettings {
                 dynamicSensitivityType = .disabled
             }
         }
-            
+
         /// Checks if there is enough Total Daily Dose (TDD) data collected over the past 7 days.
         ///
         /// This function fetches TDD records from Core Data where:

+ 3 - 32
Trio/Sources/Modules/DynamicSettings/View/DynamicSettingsRootView.swift

@@ -61,7 +61,9 @@ extension DynamicSettings {
                                     String(
                                         localized: "Dynamically adjust insulin sensitivity using Dynamic Ratio rather than Autosens Ratio."
                                     ) :
-                                    String(localized: "Trio has only been actively used and looping for less than seven days. Cannot enable dynamic ISF.")
+                                    String(
+                                        localized: "Trio has only been actively used and looping for less than seven days. Cannot enable dynamic ISF."
+                                    )
                                 let miniHintTextColorForDisabled: Color = colorScheme == .dark ? .orange :
                                     .accentColor
                                 let miniHintTextColor: Color = state.hasValidTDD ? .secondary : miniHintTextColorForDisabled
@@ -231,37 +233,6 @@ extension DynamicSettings {
                         )
                     }
 
-                    //                    SettingInputSection(
-                    //                        decimalValue: $decimalPlaceholder,
-                    //                        booleanValue: $state.enableDynamicCR,
-                    //                        shouldDisplayHint: $shouldDisplayHint,
-                    //                        selectedVerboseHint: Binding(
-                    //                            get: { selectedVerboseHint },
-                    //                            set: {
-                    //                                selectedVerboseHint = $0.map { AnyView($0) }
-                    //                                hintLabel = String(localized: "Activate Dynamic CR (Carb Ratio)")
-                    //                            }
-                    //                        ),
-                    //                        units: state.units,
-                    //                        type: .boolean,
-                    //                        label: String(localized: "Activate Dynamic CR (Carb Ratio)"),
-                    //                        miniHint: String(localized: "Dynamically adjust your Carb Ratio (CR)."),
-                    //                        verboseHint:
-                    //
-                    //                        VStack(alignment: .leading, spacing: 10) {
-                    //                            Text("Default: OFF").bold()
-                    //                            Text(
-                    //                                "Dynamic CR adjusts your carb ratio based on your Dynamic Ratio, adapting automatically to changes in insulin sensitivity."
-                    //                            )
-                    //                            Text(
-                    //                                "When Dynamic Ratio increases, indicating you need more insulin, the carb ratio value is decreased to make your insulin dosing more effective."
-                    //                            )
-                    //                            Text(
-                    //                                "When Dynamic Ratio decreases, indicating you need less insulin, the carb ratio value is increased to avoid over-delivery."
-                    //                            )
-                    //                        }
-                    //                    )
-
                     SettingInputSection(
                         decimalValue: $decimalPlaceholder,
                         booleanValue: $state.tddAdjBasal,