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

Let Upload of manual glucose conform to BloodGlucose struct

polscm32 aka Marvout 1 год назад
Родитель
Сommit
d7818a4679

+ 39 - 26
FreeAPS/Sources/APS/Storage/GlucoseStorage.swift

@@ -16,7 +16,7 @@ protocol GlucoseStorage {
     func getCGMStateNotYetUploadedToNightscout() async -> [NightscoutTreatment]
     func getManualGlucoseNotYetUploadedToNightscout() async -> [NightscoutTreatment]
     func getGlucoseNotYetUploadedToHealth() async -> [BloodGlucose]
-    func getManualGlucoseNotYetUploadedToHealth() async -> [NightscoutTreatment]
+    func getManualGlucoseNotYetUploadedToHealth() async -> [BloodGlucose]
     var alarm: GlucoseAlarm? { get }
 }
 
@@ -356,7 +356,7 @@ final class BaseGlucoseStorage: GlucoseStorage, Injectable {
 
     // Fetch manual glucose that is not uploaded to Nightscout yet
     /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
-    func getManualGlucoseNotYetUploadedToHealth() async -> [NightscoutTreatment] {
+    func getManualGlucoseNotYetUploadedToHealth() async -> [BloodGlucose] {
         let results = await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: GlucoseStored.self,
             onContext: coredataContext,
@@ -370,31 +370,44 @@ final class BaseGlucoseStorage: GlucoseStorage, Injectable {
 
         return await coredataContext.perform {
             return fetchedResults.map { result in
-                NightscoutTreatment(
-                    duration: nil,
-                    rawDuration: nil,
-                    rawRate: nil,
-                    absolute: nil,
-                    rate: nil,
-                    eventType: .capillaryGlucose,
-                    createdAt: result.date,
-                    enteredBy: "Trio",
-                    bolus: nil,
-                    insulin: nil,
-                    notes: "Trio User",
-                    carbs: nil,
-                    fat: nil,
-                    protein: nil,
-                    foodType: nil,
-                    targetTop: nil,
-                    targetBottom: nil,
-                    glucoseType: "Manual",
-                    glucose: self.settingsManager.settings
-                        .units == .mgdL ? (self.glucoseFormatter.string(from: Int(result.glucose) as NSNumber) ?? "")
-                        : (self.glucoseFormatter.string(from: Decimal(result.glucose).asMmolL as NSNumber) ?? ""),
-                    units: self.settingsManager.settings.units == .mmolL ? "mmol" : "mg/dl",
-                    id: result.id?.uuidString
+                BloodGlucose(
+                    _id: result.id?.uuidString ?? UUID().uuidString,
+                    sgv: Int(result.glucose),
+                    direction: BloodGlucose.Direction(from: result.direction ?? ""),
+                    date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
+                    dateString: result.date ?? Date(),
+                    unfiltered: Decimal(result.glucose),
+                    filtered: Decimal(result.glucose),
+                    noise: nil,
+                    glucose: Int(result.glucose)
                 )
+                
+                
+//                NightscoutTreatment(
+//                    duration: nil,
+//                    rawDuration: nil,
+//                    rawRate: nil,
+//                    absolute: nil,
+//                    rate: nil,
+//                    eventType: .capillaryGlucose,
+//                    createdAt: result.date,
+//                    enteredBy: "Trio",
+//                    bolus: nil,
+//                    insulin: nil,
+//                    notes: "Trio User",
+//                    carbs: nil,
+//                    fat: nil,
+//                    protein: nil,
+//                    foodType: nil,
+//                    targetTop: nil,
+//                    targetBottom: nil,
+//                    glucoseType: "Manual",
+//                    glucose: self.settingsManager.settings
+//                        .units == .mgdL ? (self.glucoseFormatter.string(from: Int(result.glucose) as NSNumber) ?? "")
+//                        : (self.glucoseFormatter.string(from: Decimal(result.glucose).asMmolL as NSNumber) ?? ""),
+//                    units: self.settingsManager.settings.units == .mmolL ? "mmol" : "mg/dl",
+//                    id: result.id?.uuidString
+//                )
             }
         }
     }

+ 1 - 46
FreeAPS/Sources/Services/HealthKit/HealthKitManager.swift

@@ -150,7 +150,7 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
 
     func uploadGlucose() async {
         await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToHealth())
-        await uploadManualGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToHealth())
+        await uploadGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToHealth())
     }
 
     func uploadGlucose(_ glucose: [BloodGlucose]) async {
@@ -196,51 +196,6 @@ final class BaseHealthKitManager: HealthKitManager, Injectable, CarbsObserver, P
         }
     }
 
-    func uploadManualGlucose(_ glucose: [NightscoutTreatment]) async {
-        guard settingsManager.settings.useAppleHealth,
-              let sampleType = Config.healthBGObject,
-              checkAvailabilitySave(objectTypeToHealthStore: sampleType),
-              glucose.isNotEmpty
-        else { return }
-
-        do {
-            // Create HealthKit samples from all the passed glucose values
-            let glucoseSamples = glucose.compactMap { glucoseSample -> HKQuantitySample? in
-                guard let glucoseValue = glucoseSample.glucose else { return nil }
-                guard let glucoseValueAsDouble = Double(glucoseValue) else { return nil }
-                guard let date = glucoseSample.dateString as? Date else { return nil }
-
-                return HKQuantitySample(
-                    type: sampleType,
-                    quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: glucoseValueAsDouble),
-                    start: date,
-                    end: date,
-                    metadata: [
-                        HKMetadataKeyExternalUUID: glucoseSample.id ?? UUID(),
-                        HKMetadataKeySyncIdentifier: glucoseSample.id ?? UUID(),
-                        HKMetadataKeySyncVersion: 1,
-                        Config.freeAPSMetaKey: true
-                    ]
-                )
-            }
-
-            guard glucoseSamples.isNotEmpty else {
-                debug(.service, "No glucose samples available for upload.")
-                return
-            }
-
-            // Attempt to save the blood glucose samples to Apple Health
-            try await healthKitStore.save(glucoseSamples)
-            debug(.service, "Successfully stored \(glucoseSamples.count) blood glucose samples in HealthKit.")
-
-            // After successful upload, update the isUploadedToHealth flag in Core Data
-            await updateManualGlucoseAsUploaded(glucose)
-
-        } catch {
-            debug(.service, "Failed to upload glucose samples to HealthKit: \(error.localizedDescription)")
-        }
-    }
-
     private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
         await backgroundContext.perform {
             let ids = glucose.map(\.id) as NSArray