Browse Source

merge core-data-sync-trio

polscm32 aka Marvout 1 năm trước cách đây
mục cha
commit
3e0ac7e94d

+ 25 - 6
FreeAPS/Sources/APS/CGM/PluginSource.swift

@@ -135,13 +135,24 @@ extension PluginSource: CGMManagerDelegate {
         return glucoseStorage.lastGlucoseDate()
     }
 
-    func cgmManagerDidUpdateState(_: CGMManager) {
+    func cgmManagerDidUpdateState(_ cgmManager: CGMManager) {
         dispatchPrecondition(condition: .onQueue(processQueue))
-//        guard let g6Manager = manager as? TransmitterManager else {
-//            return
-//        }
-//        glucoseManager?.settingsManager.settings.uploadGlucose = g6Manager.shouldSyncToRemoteService
-//        UserDefaults.standard.dexcomTransmitterID = g6Manager.rawState["transmitterID"] as? String
+
+        guard let fetchGlucoseManager = glucoseManager else {
+            debug(
+                .deviceManager,
+                "Could not gracefully unwrap FetchGlucoseManager upon observing LoopKit's cgmManagerDidUpdateState"
+            )
+            return
+        }
+        // Adjust app-specific NS Upload setting value when CGM setting is changed
+        fetchGlucoseManager.settingsManager.settings.uploadGlucose = cgmManager.shouldSyncToRemoteService
+
+        fetchGlucoseManager.updateGlucoseSource(
+            cgmGlucoseSourceType: fetchGlucoseManager.settingsManager.settings.cgm,
+            cgmGlucosePluginId: fetchGlucoseManager.settingsManager.settings.cgmPluginIdentifier,
+            newManager: cgmManager as? CGMManagerUI
+        )
     }
 
     func credentialStoragePrefix(for _: CGMManager) -> String {
@@ -160,6 +171,14 @@ extension PluginSource: CGMManagerDelegate {
 
     private func readCGMResult(readingResult: CGMReadingResult) -> Result<[BloodGlucose], Error> {
         debug(.deviceManager, "PLUGIN CGM - Process CGM Reading Result launched with \(readingResult)")
+
+        if glucoseManager?.glucoseSource == nil {
+            debug(
+                .deviceManager,
+                "No glucose source available."
+            )
+        }
+
         switch readingResult {
         case let .newData(values):
 

+ 0 - 1
FreeAPS/Sources/APS/DeviceDataManager.swift

@@ -475,7 +475,6 @@ extension BaseDeviceDataManager: PumpManagerDelegate {
         completion: @escaping (_ error: Error?) -> Void
     ) {
         dispatchPrecondition(condition: .onQueue(processQueue))
-        debug(.deviceManager, "New pump events:\n\(events.map(\.title).joined(separator: "\n"))")
 
         // filter buggy TBRs > maxBasal from MDT
         let events = events.filter {

+ 18 - 16
FreeAPS/Sources/APS/FetchGlucoseManager.swift

@@ -105,6 +105,7 @@ final class BaseFetchGlucoseManager: FetchGlucoseManager, Injectable {
         if self.cgmGlucoseSourceType != cgmGlucoseSourceType || self.cgmGlucosePluginId != cgmGlucosePluginId {
             removeCalibrations()
             cgmManager = nil
+            glucoseSource = nil
         }
 
         self.cgmGlucoseSourceType = cgmGlucoseSourceType
@@ -125,23 +126,24 @@ final class BaseFetchGlucoseManager: FetchGlucoseManager, Injectable {
             saveConfigManager()
         }
 
-        switch self.cgmGlucoseSourceType {
-        case .none:
-            glucoseSource = nil
-        case .xdrip:
-            glucoseSource = AppGroupSource(from: "xDrip", cgmType: .xdrip)
-        case .nightscout:
-            glucoseSource = nightscoutManager
-        case .simulator:
-            glucoseSource = simulatorSource
-        case .glucoseDirect:
-            glucoseSource = AppGroupSource(from: "GlucoseDirect", cgmType: .glucoseDirect)
-        case .enlite:
-            glucoseSource = deviceDataManager
-        case .plugin:
-            glucoseSource = PluginSource(glucoseStorage: glucoseStorage, glucoseManager: self)
+        if glucoseSource == nil {
+            switch self.cgmGlucoseSourceType {
+            case .none:
+                glucoseSource = nil
+            case .xdrip:
+                glucoseSource = AppGroupSource(from: "xDrip", cgmType: .xdrip)
+            case .nightscout:
+                glucoseSource = nightscoutManager
+            case .simulator:
+                glucoseSource = simulatorSource
+            case .glucoseDirect:
+                glucoseSource = AppGroupSource(from: "GlucoseDirect", cgmType: .glucoseDirect)
+            case .enlite:
+                glucoseSource = deviceDataManager
+            case .plugin:
+                glucoseSource = PluginSource(glucoseStorage: glucoseStorage, glucoseManager: self)
+            }
         }
-        // update the config
     }
 
     /// Upload cgmManager from raw value

+ 10 - 5
FreeAPS/Sources/Modules/Bolus/BolusStateModel.swift

@@ -28,6 +28,7 @@ extension Bolus {
         @Published var percentage: Decimal = 0
         @Published var threshold: Decimal = 0
         @Published var maxBolus: Decimal = 0
+        var maxExternal: Decimal { maxBolus * 3 }
         @Published var errorString: Decimal = 0
         @Published var evBG: Decimal = 0
         @Published var insulin: Decimal = 0
@@ -91,6 +92,8 @@ extension Bolus {
         @Published var selection: MealPresetStored?
         @Published var summation: [String] = []
         @Published var maxCarbs: Decimal = 0
+        @Published var maxFat: Decimal = 0
+        @Published var maxProtein: Decimal = 0
 
         @Published var id_: String = ""
         @Published var summary: String = ""
@@ -155,6 +158,8 @@ extension Bolus {
             highGlucose = units == .mgdL ? settingsManager.settings.high : settingsManager.settings.high.asMmolL
 
             maxCarbs = settings.settings.maxCarbs
+            maxFat = settings.settings.maxFat
+            maxProtein = settings.settings.maxProtein
             skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
             useFPUconversion = settingsManager.settings.useFPUconversion
 
@@ -405,7 +410,7 @@ extension Bolus {
                 return
             }
 
-            amount = min(amount, maxBolus * 3)
+            amount = min(amount, maxExternal)
 
             do {
                 let authenticated = try await unlockmanager.unlock()
@@ -433,10 +438,10 @@ extension Bolus {
         @MainActor func saveMeal() async {
             guard carbs > 0 || fat > 0 || protein > 0 else { return }
 
-            await MainActor.run {
-                self.carbs = min(self.carbs, self.maxCarbs)
-                self.id_ = UUID().uuidString
-            }
+            carbs = min(carbs, maxCarbs)
+            fat = min(fat, maxFat)
+            protein = min(protein, maxProtein)
+            id_ = UUID().uuidString
 
             let carbsToStore = [CarbsEntry(
                 id: id_,

+ 43 - 38
FreeAPS/Sources/Modules/Bolus/View/BolusRootView.swift

@@ -386,10 +386,7 @@ extension Bolus {
                         .frame(minHeight: 50)
                 }
                 .disabled(disableTaskButton)
-                .background(
-                    (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
-                        Color(.systemBlue)
-                )
+                .background(limitExceeded ? Color(.systemRed) : Color(.systemBlue))
                 .shadow(radius: 3)
                 .clipShape(RoundedRectangle(cornerRadius: 8))
                 .padding()
@@ -398,61 +395,69 @@ extension Bolus {
         }
 
         private var taskButtonLabel: some View {
+            if pumpBolusLimitExceeded {
+                return Text("Max Bolus of \(state.maxBolus) U Exceeded")
+            } else if externalBolusLimitExceeded {
+                return Text("Max External Bolus of \(state.maxExternal) U Exceeded")
+            } else if carbLimitExceeded {
+                return Text("Max Carbs of \(state.maxCarbs) g Exceeded")
+            } else if fatLimitExceeded {
+                return Text("Max Fat of \(state.maxFat) g Exceeded")
+            } else if proteinLimitExceeded {
+                return Text("Max Protein of \(state.maxProtein) g Exceeded")
+            }
+
             let hasInsulin = state.amount > 0
             let hasCarbs = state.carbs > 0
             let hasFatOrProtein = state.fat > 0 || state.protein > 0
+            let bolusString = state.externalInsulin ? "External Insulin" : "Enact Bolus"
 
             switch (hasInsulin, hasCarbs, hasFatOrProtein) {
             case (true, true, true):
-                return Text(
-                    state
-                        .externalInsulin ? (
-                            externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log meal and external insulin"
-                        ) :
-                        (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log meal and enact bolus")
-                )
+                return Text("Log Meal and \(bolusString)")
             case (true, true, false):
-                return Text(
-                    state
-                        .externalInsulin ?
-                        (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log carbs and external insulin") :
-                        (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log carbs and enact bolus")
-                )
+                return Text("Log Carbs and \(bolusString)")
             case (true, false, true):
-                return Text(
-                    state
-                        .externalInsulin ?
-                        (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log FPUs and external insulin") :
-                        (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log FPUs and enact bolus")
-                )
+                return Text("Log FPU and \(bolusString)")
             case (true, false, false):
-                return Text(
-                    state
-                        .externalInsulin ? (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin") :
-                        (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus")
-                )
+                return Text(state.externalInsulin ? "Log External Insulin" : "Enact Bolus")
             case (false, true, true):
-                return Text("Log meal")
+                return Text("Log Meal")
             case (false, true, false):
-                return Text("Log carbs")
+                return Text("Log Carbs")
             case (false, false, true):
-                return Text("Log FPUs")
+                return Text("Log FPU")
             default:
-                return Text("Continue without treatment")
+                return Text("Continue Without Treatment")
             }
         }
 
-        private var pumpBolusLimit: Bool {
-            state.amount > state.maxBolus
+        private var pumpBolusLimitExceeded: Bool {
+            !state.externalInsulin && state.amount > state.maxBolus
+        }
+
+        private var externalBolusLimitExceeded: Bool {
+            state.externalInsulin && state.amount > state.maxExternal
+        }
+
+        private var carbLimitExceeded: Bool {
+            state.carbs > state.maxCarbs
+        }
+
+        private var fatLimitExceeded: Bool {
+            state.fat > state.maxFat
+        }
+
+        private var proteinLimitExceeded: Bool {
+            state.protein > state.maxProtein
         }
 
-        private var externalBolusLimit: Bool {
-            state.amount > state.maxBolus * 3
+        private var limitExceeded: Bool {
+            pumpBolusLimitExceeded || externalBolusLimitExceeded || carbLimitExceeded || fatLimitExceeded || proteinLimitExceeded
         }
 
         private var disableTaskButton: Bool {
-            state.addButtonPressed ||
-                (state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false)
+            state.addButtonPressed || limitExceeded
         }
     }
 

+ 8 - 0
FreeAPS/Sources/Modules/HealthKit/View/AppleHealthKitRootView.swift

@@ -27,6 +27,14 @@ extension AppleHealthKit {
         var body: some View {
             Form {
                 Section {
+                    HStack {
+                        Image(systemName: "exclamationmark.triangle")
+                        Text(
+                            "Connecting to Apple Health will use an excessive amount of storage and may cause Apple Health to lag. This will be improved in a future release."
+                        )
+                        .font(.caption)
+                    }
+                    .foregroundColor(Color.secondary)
                     Toggle("Connect to Apple Health", isOn: $state.useAppleHealth)
                     HStack {
                         Image(systemName: "pencil.circle.fill")

+ 2 - 2
FreeAPS/Sources/Modules/Home/View/Chart/MainChartView.swift

@@ -1250,7 +1250,7 @@ extension MainChartView {
     private var mainChartYAxis: some AxisContent {
         AxisMarks(position: .trailing) { value in
 
-            if displayXgridLines {
+            if displayYgridLines {
                 AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
             } else {
                 AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
@@ -1268,7 +1268,7 @@ extension MainChartView {
 
     private var cobChartYAxis: some AxisContent {
         AxisMarks(position: .trailing) { _ in
-            if displayXgridLines {
+            if displayYgridLines {
                 AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
             } else {
                 AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))

+ 3 - 32
FreeAPS/Sources/Services/HealthKit/HealthKitManager.swift

@@ -168,14 +168,7 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
                 }
 
             healthKitStore.save(samplesToSave) { (success: Bool, error: Error?) -> Void in
-                if success {
-                    for sample in samplesToSave {
-                        debug(
-                            .service,
-                            "Stored blood glucose \(sample.quantity) in HealthKit Store! Metadata: \(String(describing: sample.metadata?.values))"
-                        )
-                    }
-                } else {
+                if !success {
                     debug(.service, "Failed to store blood glucose in HealthKit Store!")
                     debug(.service, error?.localizedDescription ?? "Unknown error")
                 }
@@ -222,14 +215,7 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
                 }
 
             healthKitStore.save(samplesToSave) { (success: Bool, error: Error?) -> Void in
-                if success {
-                    for sample in samplesToSave {
-                        debug(
-                            .service,
-                            "Stored carb entry \(sample.quantity) in HealthKit Store! Metadata: \(String(describing: sample.metadata?.values))"
-                        )
-                    }
-                } else {
+                if !success {
                     debug(.service, "Failed to store carb entry in HealthKit Store!")
                     debug(.service, error?.localizedDescription ?? "Unknown error")
                 }
@@ -298,14 +284,7 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
                 }
 
             healthKitStore.save(bolusSamples + basalSamples) { (success: Bool, error: Error?) -> Void in
-                if success {
-                    for sample in bolusSamples + basalSamples {
-                        debug(
-                            .service,
-                            "Stored insulin entry in HealthKit Store! Metadata: \(String(describing: sample.metadata?.values))"
-                        )
-                    }
-                } else {
+                if !success {
                     debug(.service, "Failed to store insulin entry in HealthKit Store!")
                     debug(.service, error?.localizedDescription ?? "Unknown error")
                 }
@@ -493,7 +472,6 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
 
     private func prepareBGSamplesToPublisherFetch(_ samples: [HKQuantitySample]) {
         dispatchPrecondition(condition: .onQueue(processQueue))
-        debug(.service, "Start preparing samples: \(String(describing: samples))")
 
         newGlucose += samples
             .compactMap { sample -> HealthKitSample? in
@@ -522,11 +500,6 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
             .filter { $0.dateString >= Date().addingTimeInterval(-1.days.timeInterval) }
 
         newGlucose = newGlucose.removeDublicates()
-
-        debug(
-            .service,
-            "Current BloodGlucose.Type objects will be send from Publisher during fetch: \(String(describing: newGlucose))"
-        )
     }
 
     // MARK: - GlucoseSource
@@ -542,9 +515,7 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
             }
 
             self.processQueue.async {
-                //   debug(.service, "Start fetching HealthKitManager")
                 guard self.settingsManager.settings.useAppleHealth else {
-                    debug(.service, "HealthKitManager cant return any data, because useAppleHealth option is disable")
                     promise(.success([]))
                     return
                 }

+ 1 - 6
scripts/capture-build-details.sh

@@ -1,22 +1,17 @@
 #!/bin/sh -e
-
 #  capture-build-details.sh
 #  Trio
 #
 #  Created by Jonas Björkert on 2024-05-08.
-
 # Enable debugging if needed
 #set -x
-
 info_plist_path="${BUILT_PRODUCTS_DIR}/${CONTENTS_FOLDER_PATH}/BuildDetails.plist"
-
 # Ensure the path to BuildDetails.plist is valid.
 if [ "${info_plist_path}" == "/" -o ! -e "${info_plist_path}" ]; then
     echo "BuildDetails.plist file does not exist at path: ${info_plist_path}" >&2
     exit 1
 else
     echo "Gathering build details..."
-
     # Capture the current date and write it to BuildDetails.plist
     plutil -replace com-trio-build-date -string "$(date)" "${info_plist_path}"
 
@@ -40,4 +35,4 @@ else
 
     # Update BuildDetails.plist with the SHA information
     plutil -replace com-trio-commit-sha -string "${git_commit_sha}" "${info_plist_path}"
-fi
+fi