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

+ 12 - 8
FreeAPS/Sources/APS/FetchTreatmentsManager.swift

@@ -30,14 +30,18 @@ final class BaseFetchTreatmentsManager: FetchTreatmentsManager, Injectable {
                     self.nightscoutManager.fetchTempTargets()
                 ).eraseToAnyPublisher()
             }
-            .sink { carbs, targets in
-                let filteredCarbs = carbs.filter { !($0.enteredBy?.contains(CarbsEntry.manual) ?? false) }
-                if filteredCarbs.isNotEmpty {
-                    self.carbsStorage.storeCarbs(filteredCarbs)
-                }
-                let filteredTargets = targets.filter { !($0.enteredBy?.contains(TempTarget.manual) ?? false) }
-                if filteredTargets.isNotEmpty {
-                    self.tempTargetsStorage.storeTempTargets(filteredTargets)
+            .sink { [weak self] carbs, targets in
+                guard let self = self else { return }
+
+                Task {
+                    let filteredCarbs = carbs.filter { !($0.enteredBy?.contains(CarbsEntry.manual) ?? false) }
+                    if filteredCarbs.isNotEmpty {
+                        await self.carbsStorage.storeCarbs(filteredCarbs)
+                    }
+                    let filteredTargets = targets.filter { !($0.enteredBy?.contains(TempTarget.manual) ?? false) }
+                    if filteredTargets.isNotEmpty {
+                        self.tempTargetsStorage.storeTempTargets(filteredTargets)
+                    }
                 }
             }
             .store(in: &lifetime)

+ 10 - 120
FreeAPS/Sources/APS/Storage/CarbsStorage.swift

@@ -8,7 +8,7 @@ protocol CarbsObserver {
 }
 
 protocol CarbsStorage {
-    func storeCarbs(_ carbs: [CarbsEntry])
+    func storeCarbs(_ carbs: [CarbsEntry]) async
     func syncDate() -> Date
     func recent() -> [CarbsEntry]
     func getCarbsNotYetUploadedToNightscout() async -> [NightscoutTreatment]
@@ -28,11 +28,9 @@ final class BaseCarbsStorage: CarbsStorage, Injectable {
         injectServices(resolver)
     }
 
-    func storeCarbs(_ entries: [CarbsEntry]) {
-        processQueue.sync {
-            self.storeCarbEquivalents(entries: entries)
-            self.saveCarbsToCoreData(entries: entries)
-        }
+    func storeCarbs(_ entries: [CarbsEntry]) async {
+        await storeCarbEquivalents(entries: entries)
+        await saveCarbsToCoreData(entries: entries)
     }
 
     /**
@@ -125,7 +123,7 @@ final class BaseCarbsStorage: CarbsStorage, Injectable {
         return (futureCarbArray, carbEquivalents)
     }
 
-    private func storeCarbEquivalents(entries: [CarbsEntry]) {
+    private func storeCarbEquivalents(entries: [CarbsEntry]) async {
         guard let lastEntry = entries.last else { return }
 
         if let fat = lastEntry.fat, let protein = lastEntry.protein, fat > 0 || protein > 0 {
@@ -137,123 +135,15 @@ final class BaseCarbsStorage: CarbsStorage, Injectable {
             )
 
             if carbEquivalentCount > 0 {
-                saveFPUToCoreDataAsBatchInsert(entries: futureCarbEquivalents)
+                await saveFPUToCoreDataAsBatchInsert(entries: futureCarbEquivalents)
             }
         }
     }
 
-//
-//    private func handleFPUCalculations(entries: [CarbsEntry]) {
-//        let file = OpenAPS.Monitor.carbHistory
-//        var uniqEvents: [CarbsEntry] = []
-//
-//        let fat = entries.last?.fat ?? 0
-//        let protein = entries.last?.protein ?? 0
-//
-//        if fat > 0 || protein > 0 {
-//            // -------------------------- FPU--------------------------------------
-//            let interval = settings.settings.minuteInterval // Interval betwwen carbs
-//            let timeCap = settings.settings.timeCap // Max Duration
-//            let adjustment = settings.settings.individualAdjustmentFactor
-//            let delay = settings.settings.delay // Tme before first future carb entry
-//            let kcal = protein * 4 + fat * 9
-//            let carbEquivalents = (kcal / 10) * adjustment
-//            let fpus = carbEquivalents / 10
-//            // Duration in hours used for extended boluses with Warsaw Method. Here used for total duration of the computed carbquivalents instead, excluding the configurable delay.
-//            var computedDuration = 0
-//            switch fpus {
-//            case ..<2:
-//                computedDuration = 3
-//            case 2 ..< 3:
-//                computedDuration = 4
-//            case 3 ..< 4:
-//                computedDuration = 5
-//            default:
-//                computedDuration = timeCap
-//            }
-//            // Size of each created carb equivalent if 60 minutes interval
-//            var equivalent: Decimal = carbEquivalents / Decimal(computedDuration)
-//            // Adjust for interval setting other than 60 minutes
-//            equivalent /= Decimal(60 / interval)
-//            // Round to 1 fraction digit
-//            // equivalent = Decimal(round(Double(equivalent * 10) / 10))
-//            let roundedEquivalent: Double = round(Double(equivalent * 10)) / 10
-//            equivalent = Decimal(roundedEquivalent)
-//            // Number of equivalents
-//            var numberOfEquivalents = carbEquivalents / equivalent
-//            // Only use delay in first loop
-//            var firstIndex = true
-//            // New date for each carb equivalent
-//            var useDate = entries.last?.actualDate ?? Date()
-//            // Group and Identify all FPUs together
-//            let fpuID = entries.last?.fpuID ?? ""
-//            // Create an array of all future carb equivalents.
-//            var futureCarbArray = [CarbsEntry]()
-//            while carbEquivalents > 0, numberOfEquivalents > 0 {
-//                if firstIndex {
-//                    useDate = useDate.addingTimeInterval(delay.minutes.timeInterval)
-//                    firstIndex = false
-//                } else { useDate = useDate.addingTimeInterval(interval.minutes.timeInterval) }
-//
-//                let eachCarbEntry = CarbsEntry(
-//                    id: UUID().uuidString, createdAt: entries.last?.createdAt ?? Date(), actualDate: useDate,
-//                    carbs: equivalent, fat: 0, protein: 0, note: nil,
-//                    enteredBy: CarbsEntry.manual, isFPU: true,
-//                    fpuID: fpuID
-//                )
-//                futureCarbArray.append(eachCarbEntry)
-//                numberOfEquivalents -= 1
-//            }
-//            // Save the array
-//            if carbEquivalents > 0 {
-//                storage.transaction { storage in
-//                    storage.append(futureCarbArray, to: file, uniqBy: \.id)
-//                    uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
-//                        .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
-//                        .sorted { $0.createdAt > $1.createdAt } ?? []
-//                    storage.save(Array(uniqEvents), as: file)
-//                }
-//
-//                // MARK: - save also to core data
-//
-//                saveFPUToCoreDataAsBatchInsert(entries: futureCarbArray)
-//            }
-//        }
-//    }
-//
-//    private func storeNormalCarbs(entries: [CarbsEntry]) {
-//        let file = OpenAPS.Monitor.carbHistory
-//        var uniqEvents: [CarbsEntry] = []
-//
-//        if let entry = entries.last, entry.carbs > 0 {
-//            // uniqEvents = []
-//            let onlyCarbs = CarbsEntry(
-//                id: entry.id ?? "",
-//                createdAt: entry.createdAt,
-//                actualDate: entry.actualDate ?? entry.createdAt,
-//                carbs: entry.carbs,
-//                fat: entry.fat,
-//                protein: entry.protein,
-//                note: entry.note ?? "",
-//                enteredBy: entry.enteredBy ?? "",
-//                isFPU: false,
-//                fpuID: ""
-//            )
-//
-//            storage.transaction { storage in
-//                storage.append(onlyCarbs, to: file, uniqBy: \.id)
-//                uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
-//                    .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
-//                    .sorted { $0.createdAt > $1.createdAt } ?? []
-//                storage.save(Array(uniqEvents), as: file)
-//            }
-//        }
-//    }
-
-    private func saveCarbsToCoreData(entries: [CarbsEntry]) {
+    private func saveCarbsToCoreData(entries: [CarbsEntry]) async {
         guard let entry = entries.last, entry.carbs != 0 else { return }
 
-        coredataContext.perform {
+        await coredataContext.perform {
             let newItem = CarbEntryStored(context: self.coredataContext)
             newItem.date = entry.actualDate ?? entry.createdAt
             newItem.carbs = Double(truncating: NSDecimalNumber(decimal: entry.carbs))
@@ -272,7 +162,7 @@ final class BaseCarbsStorage: CarbsStorage, Injectable {
         }
     }
 
-    private func saveFPUToCoreDataAsBatchInsert(entries: [CarbsEntry]) {
+    private func saveFPUToCoreDataAsBatchInsert(entries: [CarbsEntry]) async {
         let commonFPUID =
             UUID() // all fpus should only get ONE id per batch insert to be able to delete them referencing the fpuID
         var entrySlice = ArraySlice(entries) // convert to ArraySlice
@@ -290,7 +180,7 @@ final class BaseCarbsStorage: CarbsStorage, Injectable {
             carbEntry.isUploadedToNS = false
             return false // return false to continue
         }
-        coredataContext.perform {
+        await coredataContext.perform {
             do {
                 try self.coredataContext.execute(batchInsert)
                 debugPrint("Carbs Storage: \(DebuggingIdentifiers.succeeded) saved fpus to core data")

+ 4 - 6
FreeAPS/Sources/Modules/Bolus/BolusStateModel.swift

@@ -246,7 +246,7 @@ extension Bolus {
                     return
                 }
 
-                saveMeal()
+                await saveMeal()
                 addButtonPressed = true
 
                 // if glucose data is stale end the custom loading animation by hiding the modal
@@ -349,7 +349,7 @@ extension Bolus {
 
         // MARK: - Carbs
 
-        func saveMeal() {
+        @MainActor func saveMeal() async {
             guard carbs > 0 || fat > 0 || protein > 0 else { return }
             carbs = min(carbs, maxCarbs)
             id_ = UUID().uuidString
@@ -365,14 +365,12 @@ extension Bolus {
                 enteredBy: CarbsEntry.manual,
                 isFPU: false, fpuID: UUID().uuidString
             )]
-            carbsStorage.storeCarbs(carbsToStore)
+            await carbsStorage.storeCarbs(carbsToStore)
 
             if carbs > 0 || fat > 0 || protein > 0 {
                 // only perform determine basal sync if the user doesn't use the pump bolus, otherwise the enact bolus func in the APSManger does a sync
                 if amount <= 0 {
-                    Task {
-                        await apsManager.determineBasalSync()
-                    }
+                    await apsManager.determineBasalSync()
                 }
             }
         }

+ 37 - 34
FreeAPS/Sources/Services/WatchManager/WatchManager.swift

@@ -367,22 +367,22 @@ extension BaseWatchManager: WCSessionDelegate {
            let protein = message["protein"] as? Double,
            carbs > 0 || fat > 0 || protein > 0
         {
-            carbsStorage.storeCarbs(
-                [CarbsEntry(
-                    id: UUID().uuidString,
-                    createdAt: Date(),
-                    actualDate: nil,
-                    carbs: Decimal(carbs),
-                    fat: Decimal(fat),
-                    protein: Decimal(protein),
-                    note: nil,
-                    enteredBy: CarbsEntry.manual,
-                    isFPU: false,
-                    fpuID: nil
-                )]
-            )
-
             Task {
+                await carbsStorage.storeCarbs(
+                    [CarbsEntry(
+                        id: UUID().uuidString,
+                        createdAt: Date(),
+                        actualDate: nil,
+                        carbs: Decimal(carbs),
+                        fat: Decimal(fat),
+                        protein: Decimal(protein),
+                        note: nil,
+                        enteredBy: CarbsEntry.manual,
+                        isFPU: false,
+                        fpuID: nil
+                    )]
+                )
+
                 if settingsManager.settings.skipBolusScreenAfterCarbs {
                     let success = await apsManager.determineBasal()
                     replyHandler(["confirmation": success])
@@ -395,32 +395,35 @@ extension BaseWatchManager: WCSessionDelegate {
         }
 
         if let tempTargetID = message["tempTarget"] as? String {
-            if var preset = tempTargetsStorage.presets().first(where: { $0.id == tempTargetID }) {
-                preset.createdAt = Date()
-                tempTargetsStorage.storeTempTargets([preset])
-                replyHandler(["confirmation": true])
-                return
-            } else if tempTargetID == "cancel" {
-                let entry = TempTarget(
-                    name: TempTarget.cancel,
-                    createdAt: Date(),
-                    targetTop: 0,
-                    targetBottom: 0,
-                    duration: 0,
-                    enteredBy: TempTarget.manual,
-                    reason: TempTarget.cancel
-                )
-                tempTargetsStorage.storeTempTargets([entry])
-                replyHandler(["confirmation": true])
-                return
+            Task {
+                if var preset = tempTargetsStorage.presets().first(where: { $0.id == tempTargetID }) {
+                    preset.createdAt = Date()
+                    await tempTargetsStorage.storeTempTargets([preset])
+                    replyHandler(["confirmation": true])
+                } else if tempTargetID == "cancel" {
+                    let entry = TempTarget(
+                        name: TempTarget.cancel,
+                        createdAt: Date(),
+                        targetTop: 0,
+                        targetBottom: 0,
+                        duration: 0,
+                        enteredBy: TempTarget.manual,
+                        reason: TempTarget.cancel
+                    )
+                    await tempTargetsStorage.storeTempTargets([entry])
+                    replyHandler(["confirmation": true])
+                } else {
+                    replyHandler(["confirmation": false])
+                }
             }
+            return
         }
 
         if let bolus = message["bolus"] as? Double, bolus > 0 {
             Task {
                 await apsManager.enactBolus(amount: bolus, isSMB: false)
+                replyHandler(["confirmation": true])
             }
-            replyHandler(["confirmation": true])
             return
         }
 

+ 1 - 1
FreeAPS/Sources/Shortcuts/Carbs/AddCarbPresetIntent.swift

@@ -82,7 +82,7 @@ import Swinject
                 )
             }
 
-            let finalQuantityCarbsDisplay = try carbRequest.addCarbs(quantityCarbs, fatQuantity, proteinQuantity, dateAdded)
+            let finalQuantityCarbsDisplay = try await carbRequest.addCarbs(quantityCarbs, fatQuantity, proteinQuantity, dateAdded)
             return .result(
                 dialog: IntentDialog(stringLiteral: finalQuantityCarbsDisplay)
             )

+ 7 - 2
FreeAPS/Sources/Shortcuts/Carbs/CarbPresetIntentRequest.swift

@@ -2,14 +2,19 @@ import CoreData
 import Foundation
 
 @available(iOS 16.0,*) final class CarbPresetIntentRequest: BaseIntentsRequest {
-    func addCarbs(_ quantityCarbs: Double, _ quantityFat: Double, _ quantityProtein: Double, _ dateAdded: Date) throws -> String {
+    func addCarbs(
+        _ quantityCarbs: Double,
+        _ quantityFat: Double,
+        _ quantityProtein: Double,
+        _ dateAdded: Date
+    ) async throws -> String {
         guard quantityCarbs >= 0.0 || quantityFat >= 0.0 || quantityProtein >= 0.0 else {
             return "no adding carbs in iAPS"
         }
 
         let carbs = min(Decimal(quantityCarbs), settingsManager.settings.maxCarbs)
 
-        carbsStorage.storeCarbs(
+        await carbsStorage.storeCarbs(
             [CarbsEntry(
                 id: UUID().uuidString,
                 createdAt: dateAdded,