Przeglądaj źródła

merge dans version of 'core-data-sync-trio'

polscm32 aka Marvout 1 rok temu
rodzic
commit
dde1d23c53

+ 2 - 2
FreeAPS/Sources/APS/OpenAPS/OpenAPS.swift

@@ -129,7 +129,7 @@ final class OpenAPS {
         let results = await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: GlucoseStored.self,
             onContext: context,
-            predicate: NSPredicate.predicateForSixHoursAgo,
+            predicate: NSPredicate.predicateForOneDayAgoInMinutes,
             key: "date",
             ascending: false,
             fetchLimit: 72,
@@ -191,7 +191,7 @@ final class OpenAPS {
         let results = await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: PumpEventStored.self,
             onContext: context,
-            predicate: NSPredicate.pumpHistoryLast24h,
+            predicate: NSPredicate.pumpHistoryLast1440Minutes,
             key: "timestamp",
             ascending: false,
             batchSize: 50

+ 3 - 13
FreeAPS/Sources/APS/Storage/DeterminationStorage.swift

@@ -100,13 +100,9 @@ final class BaseDeterminationStorage: DeterminationStorage, Injectable {
         var result: Determination?
 
         guard let determinationId = determinationIds.first else {
-            print("No determination ID found.")
             return nil
         }
 
-        print("Using context: \(backgroundContext)")
-        print("Determination ID: \(determinationId)")
-
         let predictions = Predictions(
             iob: await parseForecastValues(ofType: "iob", from: determinationId),
             zt: await parseForecastValues(ofType: "zt", from: determinationId),
@@ -118,15 +114,9 @@ final class BaseDeterminationStorage: DeterminationStorage, Injectable {
             do {
                 let orefDetermination = try self.backgroundContext.existingObject(with: determinationId) as? OrefDetermination
 
-                // Log the type of the fetched object
-                print("Fetched object type: \(type(of: orefDetermination))")
-                print("Fetched object description: \(orefDetermination)")
-
                 // Check if the fetched object is of the expected type
                 if let orefDetermination = orefDetermination {
-                    print("Successfully cast to OrefDetermination")
                     let forecastSet = orefDetermination.forecasts
-                    print("Fetched forecast set: \(forecastSet)")
 
                     result = Determination(
                         id: orefDetermination.id ?? UUID(),
@@ -160,11 +150,11 @@ final class BaseDeterminationStorage: DeterminationStorage, Injectable {
                         carbRatio: self.decimal(from: orefDetermination.carbRatio),
                         received: orefDetermination.enacted // this is actually part of NS...
                     )
-                } else {
-                    print("Fetched object is not of type OrefDetermination")
                 }
             } catch {
-                print("Failed to fetch managed object: \(error)")
+                debugPrint(
+                    "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to fetch managed object with error: \(error.localizedDescription)"
+                )
             }
 
             return result

+ 1 - 3
FreeAPS/Sources/APS/Storage/GlucoseStorage.swift

@@ -47,8 +47,6 @@ final class BaseGlucoseStorage: GlucoseStorage, Injectable {
 
     func storeGlucose(_ glucose: [BloodGlucose]) {
         processQueue.sync {
-            debug(.deviceManager, "Start storage of glucose data")
-
             self.coredataContext.perform {
                 let datesToCheck: Set<Date?> = Set(glucose.compactMap { $0.dateString as Date? })
                 let fetchRequest: NSFetchRequest<NSFetchRequestResult> = GlucoseStored.fetchRequest()
@@ -89,7 +87,7 @@ final class BaseGlucoseStorage: GlucoseStorage, Injectable {
                 // process batch insert
                 do {
                     try self.coredataContext.execute(batchInsert)
-                    debugPrint("Glucose Storage: \(#function) \(DebuggingIdentifiers.succeeded) saved glucose to Core Data")
+//                    debugPrint("Glucose Storage: \(#function) \(DebuggingIdentifiers.succeeded) saved glucose to Core Data")
 
                     // Send notification for triggering a fetch in Home State Model to update the Glucose Array
                     /// This is necessary because changes only get merged automatically into the viewContext because of the Persistent History Tracking

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

@@ -1008,9 +1008,6 @@ extension MainChartView {
 
         minValue = minOverall * conversionFactor - 50 * conversionFactor
         maxValue = maxOverall * conversionFactor + 80 * conversionFactor
-
-        debug(.default, "min \(minValue)")
-        debug(.default, "max \(maxValue)")
     }
 
     private func yAxisChartDataCobChart() {

+ 11 - 11
FreeAPS/Sources/Services/Network/NightscoutAPI.swift

@@ -344,8 +344,8 @@ extension NightscoutAPI {
         do {
             let encodedBody = try JSONCoding.encoder.encode(treatments)
             request.httpBody = encodedBody
-            debugPrint("Payload treatments size: \(encodedBody.count) bytes")
-            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
+//            debugPrint("Payload treatments size: \(encodedBody.count) bytes")
+//            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
         } catch {
             debugPrint("Error encoding payload: \(error.localizedDescription)")
             throw error
@@ -359,7 +359,7 @@ extension NightscoutAPI {
             throw URLError(.badServerResponse)
         }
 
-        debugPrint("Upload successful, response data: \(String(data: data, encoding: .utf8) ?? "No data")")
+//        debugPrint("Upload successful, response data: \(String(data: data, encoding: .utf8) ?? "No data")")
     }
 
     func uploadGlucose(_ glucose: [BloodGlucose]) async throws {
@@ -380,8 +380,8 @@ extension NightscoutAPI {
         do {
             let encodedBody = try JSONCoding.encoder.encode(glucose)
             request.httpBody = encodedBody
-            debugPrint("Payload glucose size: \(encodedBody.count) bytes")
-            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
+//            debugPrint("Payload glucose size: \(encodedBody.count) bytes")
+//            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
         } catch {
             debugPrint("Error encoding payload: \(error.localizedDescription)")
             throw error
@@ -395,7 +395,7 @@ extension NightscoutAPI {
             throw URLError(.badServerResponse)
         }
 
-        debugPrint("Upload successful, response data: \(String(data: data, encoding: .utf8) ?? "No data")")
+//        debugPrint("Upload successful, response data: \(String(data: data, encoding: .utf8) ?? "No data")")
     }
 
     func uploadStats(_ stats: NightscoutStatistics) async throws {
@@ -442,8 +442,8 @@ extension NightscoutAPI {
         do {
             let encodedBody = try JSONCoding.encoder.encode(status)
             request.httpBody = encodedBody
-            debugPrint("Payload glucose size: \(encodedBody.count) bytes")
-            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
+//            debugPrint("Payload glucose size: \(encodedBody.count) bytes")
+//            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
         } catch {
             debugPrint("Error encoding payload: \(error.localizedDescription)")
             throw error
@@ -572,8 +572,8 @@ extension NightscoutAPI {
         do {
             let encodedBody = try JSONCoding.encoder.encode(overrides)
             request.httpBody = encodedBody
-            debugPrint("Payload glucose size: \(encodedBody.count) bytes")
-            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
+//            debugPrint("Payload glucose size: \(encodedBody.count) bytes")
+//            debugPrint(String(data: encodedBody, encoding: .utf8) ?? "Invalid payload")
         } catch {
             debugPrint("Error encoding payload: \(error.localizedDescription)")
             throw error
@@ -587,7 +587,7 @@ extension NightscoutAPI {
             throw URLError(.badServerResponse)
         }
 
-        debugPrint("Upload successful, response data: \(String(data: data, encoding: .utf8) ?? "No data")")
+//        debugPrint("Upload successful, response data: \(String(data: data, encoding: .utf8) ?? "No data")")
     }
 }
 

+ 0 - 14
FreeAPS/Sources/Services/Network/NightscoutManager.swift

@@ -482,13 +482,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateOrefDeterminationAsUploaded(_ determination: [Determination]) async {
         await backgroundContext.perform {
             let ids = determination.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<OrefDetermination> = OrefDetermination.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }
@@ -737,13 +735,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
         await backgroundContext.perform {
             let ids = glucose.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }
@@ -780,13 +776,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateTreatmentsAsUploaded(_ treatments: [NightscoutTreatment]) async {
         await backgroundContext.perform {
             let ids = treatments.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }
@@ -823,13 +817,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateManualGlucoseAsUploaded(_ treatments: [NightscoutTreatment]) async {
         await backgroundContext.perform {
             let ids = treatments.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }
@@ -866,13 +858,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateCarbsAsUploaded(_ treatments: [NightscoutTreatment]) async {
         await backgroundContext.perform {
             let ids = treatments.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }
@@ -909,13 +899,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateOverridesAsUploaded(_ overrides: [NightscoutExercise]) async {
         await backgroundContext.perform {
             let ids = overrides.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<OverrideStored> = OverrideStored.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }
@@ -952,13 +940,11 @@ final class BaseNightscoutManager: NightscoutManager, Injectable {
     private func updateOverrideRunsAsUploaded(_ overrideRuns: [NightscoutExercise]) async {
         await backgroundContext.perform {
             let ids = overrideRuns.map(\.id) as NSArray
-            print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
             let fetchRequest: NSFetchRequest<OverrideRunStored> = OverrideRunStored.fetchRequest()
             fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
 
             do {
                 let results = try self.backgroundContext.fetch(fetchRequest)
-                print("\(DebuggingIdentifiers.inProgress) results: \(results)")
                 for result in results {
                     result.isUploadedToNS = true
                 }

+ 1 - 1
FreeAPS/Sources/Services/UserNotifications/UserNotificationsManager.swift

@@ -240,7 +240,7 @@ final class BaseUserNotificationsManager: NSObject, UserNotificationsManager, In
 
             guard let lastReading = glucoseObjects.first?.glucose,
                   let secondLastReading = glucoseObjects.dropFirst().first?.glucose,
-                  let lastDirection = glucoseObjects.first?.direction else { return }
+                  let lastDirection = glucoseObjects.first?.directionEnum?.symbol else { return }
 
             addAppBadge(glucose: (glucoseObjects.first?.glucose).map { Int($0) })
 

+ 1 - 1
FreeAPS/Sources/Services/WatchManager/WatchManager.swift

@@ -199,7 +199,7 @@ final class BaseWatchManager: NSObject, WatchManager, Injectable {
                 let value = settingsManager.settings
                     .units == .mgdL ? Decimal(firstGlucoseValue.glucose) : Decimal(firstGlucoseValue.glucose).asMmolL
                 state.glucose = glucoseFormatter.string(from: value as NSNumber)
-                state.trend = firstGlucoseValue.direction
+                state.trend = firstGlucoseValue.directionEnum?.symbol
                 let delta = glucoseValues
                     .count >= 2 ? Decimal(firstGlucoseValue.glucose) - Decimal(glucoseValues.dropFirst().first?.glucose ?? 0) : 0
                 let deltaConverted = settingsManager.settings.units == .mgdL ? delta : delta.asMmolL

+ 12 - 14
Model/CoreDataStack.swift

@@ -106,7 +106,7 @@ class CoreDataStack: ObservableObject {
     private func fetchPersistentHistoryTransactionsAndChanges() async throws {
         let taskContext = newTaskContext()
         taskContext.name = "persistentHistoryContext"
-        debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
+//        debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
 
         try await taskContext.perform {
             // Execute the persistent history change since the last transaction
@@ -121,7 +121,7 @@ class CoreDataStack: ObservableObject {
     }
 
     private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
-        debugPrint("Received \(history.count) persistent history transactions")
+//        debugPrint("Received \(history.count) persistent history transactions")
         // Update view context with objectIDs from history change request
         /// - Tag: mergeChanges
         let viewContext = persistentContainer.viewContext
@@ -210,7 +210,7 @@ extension CoreDataStack {
 
             // Guard check if there are NSManagedObjects older than the specified days
             guard !objectIDs.isEmpty else {
-                debugPrint("No objects found older than \(days) days.")
+//                debugPrint("No objects found older than \(days) days.")
                 return
             }
 
@@ -258,7 +258,7 @@ extension CoreDataStack {
             }
 
             guard !parentObjectIDs.isEmpty else {
-                debugPrint("No \(parentType) objects found older than \(days) days.")
+//                debugPrint("No \(parentType) objects found older than \(days) days.")
                 return
             }
 
@@ -272,7 +272,7 @@ extension CoreDataStack {
             }
 
             guard !childObjectIDs.isEmpty else {
-                debugPrint("No \(childType) objects found related to \(parentType) objects older than \(days) days.")
+//                debugPrint("No \(childType) objects found related to \(parentType) objects older than \(days) days.")
                 return
             }
 
@@ -339,9 +339,9 @@ extension CoreDataStack {
         /// we need to ensure that the fetch immediately returns a value as long as the whole app does not use the async await pattern, otherwise we could perform this asynchronously with backgroundContext.perform and not block the thread
         context.performAndWait {
             do {
-                debugPrint(
-                    "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
-                )
+//                debugPrint(
+//                    "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
+//                )
                 result = try context.fetch(request)
             } catch let error as NSError {
                 debugPrint(
@@ -387,9 +387,7 @@ extension CoreDataStack {
 
         return await context.perform {
             do {
-                debugPrint(
-                    "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
-                )
+//                debugPrint("Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)")
                 return try context.fetch(request)
             } catch let error as NSError {
                 debugPrint(
@@ -449,9 +447,9 @@ extension NSManagedObjectContext {
         do {
             guard onContext.hasChanges else { return }
             try onContext.save()
-            debugPrint(
-                "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
-            )
+//            debugPrint(
+//                "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
+//            )
         } catch let error as NSError {
             debugPrint(
                 "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"

+ 9 - 0
Model/Helper/NSPredicates.swift

@@ -6,6 +6,10 @@ extension Date {
         Calendar.current.startOfDay(for: Date())
     }
 
+    static var oneDayAgoInMinutes: Date {
+        Calendar.current.date(byAdding: .minute, value: -1440, to: Date())!
+    }
+
     static var oneDayAgo: Date {
         Calendar.current.date(byAdding: .day, value: -1, to: Date())!
     }
@@ -52,6 +56,11 @@ extension NSPredicate {
 
     static let none = NSPredicate(format: "FALSEPREDICATE")
 
+    static var predicateForOneDayAgoInMinutes: NSPredicate {
+        let date = Date.oneDayAgoInMinutes
+        return NSPredicate(format: "date >= %@", date as NSDate)
+    }
+
     static var predicateForOneDayAgo: NSPredicate {
         let date = Date.oneDayAgo
         return NSPredicate(format: "date >= %@", date as NSDate)

+ 8 - 3
Model/Helper/PumpEvent+helper.swift

@@ -53,6 +53,11 @@ public extension PumpEventStored {
 }
 
 extension NSPredicate {
+    static var pumpHistoryLast1440Minutes: NSPredicate {
+        let date = Date.oneDayAgoInMinutes
+        return NSPredicate(format: "timestamp >= %@", date as NSDate)
+    }
+
     static var pumpHistoryLast24h: NSPredicate {
         let date = Date.oneDayAgo
         return NSPredicate(format: "timestamp >= %@", date as NSDate)
@@ -155,7 +160,7 @@ extension PumpEventStored {
     }
 
     func toTempBasalDTOEnum() -> PumpEventDTO? {
-        guard let timestamp = timestamp, let tempBasal = tempBasal, let rate = tempBasal.rate else {
+        guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal, let rate = tempBasal.rate else {
             return nil
         }
 
@@ -169,12 +174,12 @@ extension PumpEventStored {
     }
 
     func toTempBasalDurationDTOEnum() -> PumpEventDTO? {
-        guard let timestamp = timestamp, let tempBasal = tempBasal else {
+        guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal else {
             return nil
         }
 
         let tempBasalDurationDTO = TempBasalDurationDTO(
-            id: id ?? UUID().uuidString,
+            id: id,
             timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
             duration: Int(tempBasal.duration)
         )

+ 3 - 2
Trio.xcworkspace/xcshareddata/swiftpm/Package.resolved

@@ -1,4 +1,5 @@
 {
+  "originHash" : "59ac7eba66375d6eb406e758cb0b9964f4b3b0ae45c5665596f00384c32262b9",
   "pins" : [
     {
       "identity" : "cryptoswift",
@@ -48,7 +49,7 @@
     {
       "identity" : "swiftcharts",
       "kind" : "remoteSourceControl",
-      "location" : "https://github.com/ivanschuetz/SwiftCharts",
+      "location" : "https://github.com/ivanschuetz/SwiftCharts.git",
       "state" : {
         "branch" : "master",
         "revision" : "c354c1945bb35a1f01b665b22474f6db28cba4a2"
@@ -91,5 +92,5 @@
       }
     }
   ],
-  "version" : 2
+  "version" : 3
 }