polscm32 1 год назад
Родитель
Сommit
00544306e1

+ 0 - 254
FreeAPS/Sources/Modules/NightscoutConfig/NightscoutConfigStateModel.swift

@@ -1,9 +1,6 @@
 import Combine
 import CoreData
-<<<<<<< HEAD
 import G7SensorKit
-=======
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
 import LoopKit
 import SwiftDate
 import SwiftUI
@@ -18,11 +15,7 @@ extension NightscoutConfig {
         @Injected() private var storage: FileStorage!
         @Injected() var apsManager: APSManager!
 
-<<<<<<< HEAD
         let coredataContext = CoreDataStack.shared.newTaskContext()
-=======
-        let coredataContext = CoreDataStack.shared.persistentContainer.viewContext
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
 
         @Published var url = ""
         @Published var secret = ""
@@ -35,11 +28,7 @@ extension NightscoutConfig {
         @Published var changeUploadGlucose = true // if plugin, need to be change in CGM configuration
         @Published var useLocalSource = false
         @Published var localPort: Decimal = 0
-<<<<<<< HEAD
         @Published var units: GlucoseUnits = .mgdL
-=======
-        @Published var units: GlucoseUnits = .mmolL
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
         @Published var dia: Decimal = 6
         @Published var maxBasal: Decimal = 2
         @Published var maxBolus: Decimal = 10
@@ -52,10 +41,7 @@ extension NightscoutConfig {
             dia = settingsManager.pumpSettings.insulinActionCurve
             maxBasal = settingsManager.pumpSettings.maxBasal
             maxBolus = settingsManager.pumpSettings.maxBolus
-<<<<<<< HEAD
-=======
             changeUploadGlucose = (cgmManager.cgmGlucoseSourceType != CGMType.plugin)
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
 
             subscribeSetting(\.allowAnnouncements, on: $allowAnnouncements) { allowAnnouncements = $0 }
             subscribeSetting(\.isUploadEnabled, on: $isUploadEnabled) { isUploadEnabled = $0 }
@@ -102,8 +88,6 @@ extension NightscoutConfig {
             }
             return NightscoutAPI(url: url, secret: secret)
         }
-<<<<<<< HEAD
-=======
 
         private func getMedianTarget(
             lowTargetValue: Decimal,
@@ -357,244 +341,6 @@ extension NightscoutConfig {
             }
         }
 
-        func backfillGlucose() {
-            backfilling = true
-            nightscoutManager.fetchGlucose(since: Date().addingTimeInterval(-1.days.timeInterval))
-                .sink { [weak self] glucose in
-                    guard let self = self else { return }
-                    DispatchQueue.main.async {
-                        self.backfilling = false
-                    }
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
-
-        func importSettings() {
-            guard let nightscout = nightscoutAPI else {
-                saveError("Can't access nightscoutAPI")
-                return
-            }
-            let group = DispatchGroup()
-            group.enter()
-            var error = ""
-            let path = "/api/v1/profile.json"
-            let timeout: TimeInterval = 60
-
-            var components = URLComponents()
-            components.scheme = nightscout.url.scheme
-            components.host = nightscout.url.host
-            components.port = nightscout.url.port
-            components.path = path
-            components.queryItems = [
-                URLQueryItem(name: "count", value: "1")
-            ]
-            var url = URLRequest(url: components.url!)
-            url.allowsConstrainedNetworkAccess = false
-            url.timeoutInterval = timeout
-
-            if let secret = nightscout.secret {
-                url.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
-            }
-            let task = URLSession.shared.dataTask(with: url) { data, response, error_ in
-                if let error_ = error_ {
-                    print("Error occured: " + error_.localizedDescription)
-                    // handle error
-                    self.saveError("Error occured: " + error_.localizedDescription)
-                    error = error_.localizedDescription
-                    return
-                }
-                guard let httpResponse = response as? HTTPURLResponse,
-                      (200 ... 299).contains(httpResponse.statusCode)
-                else {
-                    print("Error occured! " + error_.debugDescription)
-                    // handle error
-                    self.saveError(error_.debugDescription)
-                    return
-                }
-                let jsonDecoder = JSONCoding.decoder
-
-                if let mimeType = httpResponse.mimeType, mimeType == "application/json",
-                   let data = data
-                {
-                    do {
-                        let fetchedProfileStore = try jsonDecoder.decode([FetchedNightscoutProfileStore].self, from: data)
-                        guard let fetchedProfile: ScheduledNightscoutProfile = fetchedProfileStore.first?.store["default"]
-                        else {
-                            error = "\nCan't find the default Nightscout Profile."
-                            group.leave()
-                            return
-                        }
-
-                        guard fetchedProfile.units.contains(self.units.rawValue.prefix(4)) else {
-                            debug(
-                                .nightscout,
-                                "Mismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
-                            )
-                            error = "\nMismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
-                            group.leave()
-                            return
-                        }
-
-                        var areCRsOK = true
-                        let carbratios = fetchedProfile.carbratio
-                            .map { carbratio -> CarbRatioEntry in
-                                if carbratio.value <= 0 {
-                                    error =
-                                        "\nInvalid Carb Ratio settings in Nightscout.\n\nImport aborted. Please check your Nightscout Profile Carb Ratios Settings!"
-                                    areCRsOK = false
-                                }
-                                return CarbRatioEntry(
-                                    start: carbratio.time,
-                                    offset: self.offset(carbratio.time) / 60,
-                                    ratio: carbratio.value
-                                ) }
-                        let carbratiosProfile = CarbRatios(units: CarbUnit.grams, schedule: carbratios)
-                        guard areCRsOK else {
-                            group.leave()
-                            return
-                        }
-
-                        var areBasalsOK = true
-                        let pumpName = self.apsManager.pumpName.value
-                        let basals = fetchedProfile.basal
-                            .map { basal -> BasalProfileEntry in
-                                if pumpName != "Omnipod DASH", basal.value <= 0
-                                {
-                                    error =
-                                        "\nInvalid Nightcsout Basal Settings. Some or all of your basal settings are 0 U/h.\n\nImport aborted. Please check your Nightscout Profile Basal Settings before trying to import again. Import has been aborted.)"
-                                    areBasalsOK = false
-                                }
-                                return BasalProfileEntry(
-                                    start: basal.time,
-                                    minutes: self.offset(basal.time) / 60,
-                                    rate: basal.value
-                                ) }
-                        // DASH pumps can have 0U/h basal rates but don't import if total basals (24 hours) amount to 0 U.
-                        if pumpName == "Omnipod DASH", basals.map({ each in each.rate }).reduce(0, +) <= 0
-                        {
-                            error =
-                                "\nYour total Basal insulin amount to 0 U or lower in Nightscout Profile settings.\n\n Please check your Nightscout Profile Basal Settings before trying to import again. Import has been aborted.)"
-                            areBasalsOK = false
-                        }
-                        guard areBasalsOK else {
-                            group.leave()
-                            return
-                        }
-
-                        let sensitivities = fetchedProfile.sens.map { sensitivity -> InsulinSensitivityEntry in
-                            InsulinSensitivityEntry(
-                                sensitivity: self.units == .mmolL ? sensitivity.value : sensitivity.value.asMgdL,
-                                offset: self.offset(sensitivity.time) / 60,
-                                start: sensitivity.time
-                            )
-                        }
-                        if sensitivities.filter({ $0.sensitivity <= 0 }).isNotEmpty {
-                            error =
-                                "\nInvalid Nightcsout Sensitivities Settings. \n\nImport aborted. Please check your Nightscout Profile Sensitivities Settings!"
-                            group.leave()
-                            return
-                        }
-
-                        let sensitivitiesProfile = InsulinSensitivities(
-                            units: self.units,
-                            userPrefferedUnits: self.units,
-                            sensitivities: sensitivities
-                        )
-
-                        let targets = fetchedProfile.target_low
-                            .map { target -> BGTargetEntry in
-                                BGTargetEntry(
-                                    low: self.units == .mmolL ? target.value : target.value.asMgdL,
-                                    high: self.units == .mmolL ? target.value : target.value.asMgdL,
-                                    start: target.time,
-                                    offset: self.offset(target.time) / 60
-                                ) }
-                        let targetsProfile = BGTargets(
-                            units: self.units,
-                            userPrefferedUnits: self.units,
-                            targets: targets
-                        )
-                        // IS THERE A PUMP?
-                        guard let pump = self.apsManager.pumpManager else {
-                            self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
-                            self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
-                            self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
-                            self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
-                            debug(
-                                .service,
-                                "Settings were imported but the Basals couldn't be saved to pump (No pump). Check your basal settings and tap ´Save on Pump´ to sync the new basal settings"
-                            )
-                            error =
-                                "\nSettings were imported but the Basals couldn't be saved to pump (No pump). Check your basal settings and tap ´Save on Pump´ to sync the new basal settings"
-                            group.leave()
-                            return
-                        }
-                        let syncValues = basals.map {
-                            RepeatingScheduleValue(startTime: TimeInterval($0.minutes * 60), value: Double($0.rate))
-                        }
-                        // SSAVE TO STORAGE. SAVE TO PUMP (LoopKit)
-                        pump.syncBasalRateSchedule(items: syncValues) { result in
-                            switch result {
-                            case .success:
-                                self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
-                                self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
-                                self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
-                                self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
-                                debug(.service, "Settings have been imported and the Basals saved to pump!")
-                                // DIA. Save if changed.
-                                let dia = fetchedProfile.dia
-                                print("dia: " + dia.description)
-                                print("pump dia: " + self.dia.description)
-                                if dia != self.dia, dia >= 0 {
-                                    let file = PumpSettings(
-                                        insulinActionCurve: dia,
-                                        maxBolus: self.maxBolus,
-                                        maxBasal: self.maxBasal
-                                    )
-                                    self.storage.save(file, as: OpenAPS.Settings.settings)
-                                    debug(.nightscout, "DIA setting updated to " + dia.description + " after a NS import.")
-                                }
-                                group.leave()
-                            case .failure:
-                                error =
-                                    "\nSettings were imported but the Basals couldn't be saved to pump (communication error). Check your basal settings and tap ´Save on Pump´ to sync the new basal settings"
-                                debug(.service, "Basals couldn't be save to pump")
-                                group.leave()
-                            }
-                        }
-                    } catch let parsingError {
-                        print(parsingError)
-                        error = parsingError.localizedDescription
-                        group.leave()
-                    }
-                }
-            }
-            task.resume()
-            group.wait(wallTimeout: .now() + 5)
-            group.notify(queue: .global(qos: .background)) {
-                self.saveError(error)
-            }
-        }
-
-        func offset(_ string: String) -> Int {
-            let hours = Int(string.prefix(2)) ?? 0
-            let minutes = Int(string.suffix(2)) ?? 0
-            return ((hours * 60) + minutes) * 60
-        }
-
-        func saveError(_ string: String) {
-            coredataContext.performAndWait {
-                let saveToCoreData = ImportError(context: self.coredataContext)
-                saveToCoreData.date = Date()
-                saveToCoreData.error = string
-
-                do {
-                    guard self.coredataContext.hasChanges else { return }
-                    try self.coredataContext.save()
-                } catch {
-                    print(error.localizedDescription)
-                }
-            }
-        }
-
         func backfillGlucose() async {
             backfilling = true
 

+ 3 - 122
FreeAPS/Sources/Modules/NightscoutConfig/View/NightscoutConfigRootView.swift

@@ -7,7 +7,6 @@ extension NightscoutConfig {
         let resolver: Resolver
         let displayClose: Bool
         @StateObject var state = StateModel()
-<<<<<<< HEAD
         @State var importAlert: Alert?
         @State var isImportAlertPresented = false
         @State var importedHasRun = false
@@ -43,17 +42,6 @@ extension NightscoutConfig {
             formatter.usesGroupingSeparator = false
             return formatter
         }
-=======
-        @State private var importAlert: Alert?
-        @State private var isImportAlertPresented = false
-        @State private var importedHasRun = false
-
-        @FetchRequest(
-            entity: ImportError.entity(),
-            sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)],
-            predicate: NSPredicate(format: "date > %@", Date().addingTimeInterval(-1.minutes.timeInterval) as NSDate)
-        ) var fetchedErrors: FetchedResults<ImportError>
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
 
         var body: some View {
             Form {
@@ -114,119 +102,13 @@ extension NightscoutConfig {
                             )
                         }
                 }
-<<<<<<< HEAD
-
-                Section {
-                    Button("Connect") { state.connect() }
-                        .disabled(state.url.isEmpty || state.connecting)
-                    Button("Delete") { state.delete() }.foregroundColor(.red).disabled(state.connecting)
-                }
-
-                Section {
-                    Toggle("Upload", isOn: $state.isUploadEnabled)
-                    if state.isUploadEnabled {
-                        Toggle("Statistics", isOn: $state.uploadStats)
-                        HStack(alignment: .top) {
-                            Image(systemName: "pencil.circle.fill")
-                            VStack {
-                                Text(
-                                    "This enables uploading of statistics.json to Nightscout, which can be used by the Community Statistics and Demographics Project.\n\nParticipation in Community Statistics is opt-in, and requires separate registration at:\n"
-                                )
-                                .font(.caption)
-                                Text(
-                                    "https://iaps-stats.hub.org"
-                                )
-                                .font(.caption)
-                                .multilineTextAlignment(.center)
-                            }
-                        }
-                        .foregroundColor(Color.secondary)
-                        Toggle("Glucose", isOn: $state.uploadGlucose)
-                    }
-                } header: {
-                    Text("Allow Uploads")
-                }
-
-                Section {
-                    Button("Import settings from Nightscout") {
-                        importAlert = Alert(
-                            title: Text("Import settings?"),
-                            message: Text(
-                                "\n" +
-                                    NSLocalizedString(
-                                        "This will replace some or all of your current pump settings. Are you sure you want to import profile settings from Nightscout?",
-                                        comment: "Profile Import Alert"
-                                    ) +
-                                    "\n"
-                            ),
-                            primaryButton: .destructive(
-                                Text("Yes, Import"),
-                                action: {
-                                    state.importSettings()
-                                    importedHasRun = true
-                                }
-                            ),
-                            secondaryButton: .cancel()
-                        )
-                        isImportAlertPresented.toggle()
-                    }.disabled(state.url.isEmpty || state.connecting)
-
-                } header: { Text("Import from Nightscout") }
-
-                    .alert(isPresented: $importedHasRun) {
-                        Alert(
-                            title: Text((fetchedErrors.first?.error ?? "").count < 4 ? "Settings imported" : "Import Error"),
-                            message: Text(
-                                (fetchedErrors.first?.error ?? "").count < 4 ?
-                                    NSLocalizedString(
-                                        "\nNow please verify all of your new settings thoroughly:\n\n* Basal Settings\n * Carb Ratios\n * Glucose Targets\n * Insulin Sensitivities\n * DIA\n\n in iAPS Settings > Configuration.\n\nBad or invalid profile settings could have disatrous effects.",
-                                        comment: "Imported Profiles Alert"
-                                    ) :
-                                    NSLocalizedString(fetchedErrors.first?.error ?? "", comment: "Import Error")
-                            ),
-                            primaryButton: .destructive(
-                                Text("OK")
-                            ),
-                            secondaryButton: .cancel()
-                        )
-                    }
-
-                Section {
-                    Toggle("Use local glucose server", isOn: $state.useLocalSource)
-                    HStack {
-                        Text("Port")
-                        TextFieldWithToolBar(
-                            text: $state.localPort,
-                            placeholder: "",
-                            keyboardType: .numberPad,
-                            numberFormatter: portFormater,
-                            allowDecimalSeparator: false
-                        )
-                    }
-                } header: { Text("Local glucose source") }
+                
                 Section {
-                    Button("Backfill glucose") {
+                    Button("Backfill glucose") { 
                         Task {
-                            await state.backfillGlucose()
+                            state.backfillGlucose()
                         }
                     }
-                    .disabled(state.url.isEmpty || state.connecting || state.backfilling)
-                }
-
-                Section {
-                    Toggle("Remote control", isOn: $state.allowAnnouncements)
-                } header: { Text("Allow Remote control of iAPS") }
-            }
-            .scrollContentBackground(.hidden).background(color)
-            .onAppear(perform: configureView)
-            .navigationBarTitle("Nightscout Config")
-            .navigationBarTitleDisplayMode(.automatic)
-            .alert(isPresented: $isImportAlertPresented) {
-                importAlert!
-            }
-=======
-                Section {
-                    Button("Backfill glucose") { state.backfillGlucose() }
                         .disabled(state.url.isEmpty || state.connecting || state.backfilling)
                 } header: { Text("Backfill glucose from Nightscout")
                 }
@@ -239,7 +121,6 @@ extension NightscoutConfig {
             }
 
             .onAppear(perform: configureView)
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
         }
     }
 }

+ 0 - 8
FreeAPS/Sources/Modules/NotificationsConfig/NotificationsConfigStateModel.swift

@@ -10,12 +10,8 @@ extension NotificationsConfig {
         @Published var highGlucose: Decimal = 0
         @Published var carbsRequiredThreshold: Decimal = 0
         @Published var useLiveActivity = false
-<<<<<<< HEAD
         var units: GlucoseUnits = .mgdL
-=======
         @Published var lockScreenView: LockScreenView = .simple
-        var units: GlucoseUnits = .mmolL
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
 
         override func subscribe() {
             let units = settingsManager.settings.units
@@ -27,11 +23,7 @@ extension NotificationsConfig {
             subscribeSetting(\.addSourceInfoToGlucoseNotifications, on: $addSourceInfoToGlucoseNotifications) {
                 addSourceInfoToGlucoseNotifications = $0 }
             subscribeSetting(\.useLiveActivity, on: $useLiveActivity) { useLiveActivity = $0 }
-<<<<<<< HEAD
-
-=======
             subscribeSetting(\.lockScreenView, on: $lockScreenView) { lockScreenView = $0 }
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
             subscribeSetting(\.lowGlucose, on: $lowGlucose, initial: {
                 let value = max(min($0, 400), 40)
                 lowGlucose = units == .mmolL ? value.asMmolL : value

+ 0 - 8
FreeAPS/Sources/Services/UserNotifiactions/UserNotificationsManager.swift

@@ -128,11 +128,7 @@ final class BaseUserNotificationsManager: NSObject, UserNotificationsManager, In
 
     private func scheduleMissingLoopNotifiactions(date _: Date) {
         ensureCanSendNotification {
-<<<<<<< HEAD
-            let title = NSLocalizedString("iAPS not active", comment: "iAPS not active")
-=======
             let title = NSLocalizedString("Trio Not Active", comment: "Trio Not Active")
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
             let body = NSLocalizedString("Last loop was more than %d min ago", comment: "Last loop was more than %d min ago")
 
             let firstInterval = 20 // min
@@ -257,11 +253,7 @@ final class BaseUserNotificationsManager: NSObject, UserNotificationsManager, In
         }
     }
 
-<<<<<<< HEAD
     private func glucoseText(glucoseValue: Int, delta: Int?, direction: String?) -> String {
-=======
-    private func glucoseText(glucoseValue: Int, delta: Int?, direction: BloodGlucose.Direction?) -> String {
->>>>>>> 9672da256c317a314acc76d6e4f6e82cc174d133
         let units = settingsManager.settings.units
         let glucoseText = glucoseFormatter
             .string(from: Double(