| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972 |
- import Combine
- import CoreData
- import Foundation
- import LoopKitUI
- import Swinject
- import UIKit
- protocol NightscoutManager: GlucoseSource {
- func fetchGlucose(since date: Date) -> AnyPublisher<[BloodGlucose], Never>
- func fetchCarbs() -> AnyPublisher<[CarbsEntry], Never>
- func fetchTempTargets() -> AnyPublisher<[TempTarget], Never>
- func fetchAnnouncements() -> AnyPublisher<[Announcement], Never>
- func deleteCarbs(_ treatment: DataTable.Treatment, complexMeal: Bool)
- func deleteInsulin(at date: Date)
- func deleteManualGlucose(at: Date)
- func uploadStatus()
- func uploadGlucose()
- func uploadManualGlucose()
- func uploadStatistics(dailystat: Statistics)
- func uploadPreferences(_ preferences: Preferences)
- func uploadProfileAndSettings(_: Bool)
- var cgmURL: URL? { get }
- }
- final class BaseNightscoutManager: NightscoutManager, Injectable {
- @Injected() private var keychain: Keychain!
- @Injected() private var glucoseStorage: GlucoseStorage!
- @Injected() private var tempTargetsStorage: TempTargetsStorage!
- @Injected() private var carbsStorage: CarbsStorage!
- @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
- @Injected() private var storage: FileStorage!
- @Injected() private var announcementsStorage: AnnouncementsStorage!
- @Injected() private var settingsManager: SettingsManager!
- @Injected() private var broadcaster: Broadcaster!
- @Injected() private var reachabilityManager: ReachabilityManager!
- @Injected() var healthkitManager: HealthKitManager!
- private let processQueue = DispatchQueue(label: "BaseNetworkManager.processQueue")
- private var ping: TimeInterval?
- private var lifetime = Lifetime()
- private var isNetworkReachable: Bool {
- reachabilityManager.isReachable
- }
- private var isUploadEnabled: Bool {
- settingsManager.settings.isUploadEnabled
- }
- private var isUploadGlucoseEnabled: Bool {
- settingsManager.settings.uploadGlucose
- }
- private var nightscoutAPI: NightscoutAPI? {
- guard let urlString = keychain.getValue(String.self, forKey: NightscoutConfig.Config.urlKey),
- let url = URL(string: urlString),
- let secret = keychain.getValue(String.self, forKey: NightscoutConfig.Config.secretKey)
- else {
- return nil
- }
- return NightscoutAPI(url: url, secret: secret)
- }
- private let context = CoreDataStack.shared.persistentContainer.newBackgroundContext()
- private var lastTwoDeterminations: [OrefDetermination]?
- init(resolver: Resolver) {
- injectServices(resolver)
- subscribe()
- }
- private func subscribe() {
- broadcaster.register(PumpHistoryObserver.self, observer: self)
- broadcaster.register(CarbsObserver.self, observer: self)
- broadcaster.register(TempTargetsObserver.self, observer: self)
- broadcaster.register(GlucoseObserver.self, observer: self)
- _ = reachabilityManager.startListening(onQueue: processQueue) { status in
- debug(.nightscout, "Network status: \(status)")
- }
- }
- func sourceInfo() -> [String: Any]? {
- if let ping = ping {
- return [GlucoseSourceKey.nightscoutPing.rawValue: ping]
- }
- return nil
- }
- var cgmURL: URL? {
- if let url = settingsManager.settings.cgm.appURL {
- return url
- }
- let useLocal = settingsManager.settings.useLocalGlucoseSource
- let maybeNightscout = useLocal
- ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
- : nightscoutAPI
- return maybeNightscout?.url
- }
- func fetchGlucose(since date: Date) -> AnyPublisher<[BloodGlucose], Never> {
- let useLocal = settingsManager.settings.useLocalGlucoseSource
- ping = nil
- if !useLocal {
- guard isNetworkReachable else {
- return Just([]).eraseToAnyPublisher()
- }
- }
- let maybeNightscout = useLocal
- ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
- : nightscoutAPI
- guard let nightscout = maybeNightscout else {
- return Just([]).eraseToAnyPublisher()
- }
- let startDate = Date()
- return nightscout.fetchLastGlucose(sinceDate: date)
- .tryCatch({ (error) -> AnyPublisher<[BloodGlucose], Error> in
- print(error.localizedDescription)
- return Just([]).setFailureType(to: Error.self).eraseToAnyPublisher()
- })
- .replaceError(with: [])
- .handleEvents(receiveOutput: { value in
- guard value.isNotEmpty else { return }
- self.ping = Date().timeIntervalSince(startDate)
- })
- .eraseToAnyPublisher()
- }
- // MARK: - GlucoseSource
- var glucoseManager: FetchGlucoseManager?
- var cgmManager: CGMManagerUI?
- var cgmType: CGMType = .nightscout
- func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
- fetchGlucose(since: glucoseStorage.syncDate())
- }
- func fetchIfNeeded() -> AnyPublisher<[BloodGlucose], Never> {
- fetch(nil)
- }
- func fetchCarbs() -> AnyPublisher<[CarbsEntry], Never> {
- guard let nightscout = nightscoutAPI, isNetworkReachable else {
- return Just([]).eraseToAnyPublisher()
- }
- let since = carbsStorage.syncDate()
- return nightscout.fetchCarbs(sinceDate: since)
- .replaceError(with: [])
- .eraseToAnyPublisher()
- }
- func fetchTempTargets() -> AnyPublisher<[TempTarget], Never> {
- guard let nightscout = nightscoutAPI, isNetworkReachable else {
- return Just([]).eraseToAnyPublisher()
- }
- let since = tempTargetsStorage.syncDate()
- return nightscout.fetchTempTargets(sinceDate: since)
- .replaceError(with: [])
- .eraseToAnyPublisher()
- }
- func fetchAnnouncements() -> AnyPublisher<[Announcement], Never> {
- guard let nightscout = nightscoutAPI, isNetworkReachable else {
- return Just([]).eraseToAnyPublisher()
- }
- let since = announcementsStorage.syncDate()
- return nightscout.fetchAnnouncement(sinceDate: since)
- .replaceError(with: [])
- .eraseToAnyPublisher()
- }
- func deleteCarbs(_ treatment: DataTable.Treatment, complexMeal: Bool) {
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- carbsStorage.deleteCarbs(at: treatment.id, fpuID: treatment.fpuID ?? "", complex: complexMeal)
- return
- }
- print("meals 3: ID: " + (treatment.id ?? "").description + " FPU ID: " + (treatment.fpuID ?? "").description)
- var arg1 = ""
- var arg2 = ""
- if complexMeal {
- arg1 = treatment.id ?? ""
- arg2 = treatment.fpuID ?? ""
- } else if treatment.isFPU ?? false {
- arg1 = ""
- arg2 = treatment.fpuID ?? ""
- } else {
- arg1 = treatment.id
- arg2 = ""
- }
- healthkitManager.deleteCarbs(syncID: arg1, fpuID: arg2)
- if complexMeal {
- nightscout.deleteCarbs(treatment)
- .collect()
- .sink { completion in
- self.carbsStorage.deleteCarbs(at: treatment.id ?? "", fpuID: treatment.fpuID ?? "", complex: true)
- switch completion {
- case .finished:
- debug(.nightscout, "Carbs deleted")
- case let .failure(error):
- info(
- .nightscout,
- "Deletion of carbs in NightScout not done \n \(error.localizedDescription)",
- type: MessageType.warning
- )
- }
- } receiveValue: { _ in }
- .store(in: &lifetime)
- if (treatment.fpuID ?? "") != "" {
- nightscout.deleteCarbs(treatment)
- .collect()
- .sink { completion in
- switch completion {
- case .finished:
- debug(.nightscout, "Carb equivalents deleted from NS")
- case let .failure(error):
- info(
- .nightscout,
- "Deletion of carb equivalents in NightScout not done \n \(error.localizedDescription)",
- type: MessageType.warning
- )
- }
- } receiveValue: { _ in }
- .store(in: &lifetime)
- }
- } else if treatment.isFPU ?? false {
- nightscout.deleteCarbs(treatment)
- .collect()
- .sink { completion in
- self.carbsStorage.deleteCarbs(at: "", fpuID: treatment.fpuID ?? "", complex: false)
- switch completion {
- case .finished:
- debug(.nightscout, "Carb equivalents deleted")
- case let .failure(error):
- info(
- .nightscout,
- "Deletion of carb equivalents in NightScout not done \n \(error.localizedDescription)",
- type: MessageType.warning
- )
- }
- } receiveValue: { _ in }
- .store(in: &lifetime)
- } else {
- nightscout.deleteCarbs(treatment)
- .collect()
- .sink { completion in
- self.carbsStorage.deleteCarbs(at: treatment.id, fpuID: "", complex: false)
- switch completion {
- case .finished:
- debug(.nightscout, "Carbs deleted")
- case let .failure(error):
- info(
- .nightscout,
- "Deletion of carbs in NightScout not done \n \(error.localizedDescription)",
- type: MessageType.warning
- )
- }
- } receiveValue: { _ in }
- .store(in: &lifetime)
- }
- }
- func deleteInsulin(at date: Date) {
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- pumpHistoryStorage.deleteInsulin(at: date)
- return
- }
- nightscout.deleteInsulin(at: date)
- .sink { completion in
- switch completion {
- case .finished:
- self.pumpHistoryStorage.deleteInsulin(at: date)
- debug(.nightscout, "Carbs deleted")
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &lifetime)
- }
- func deleteManualGlucose(at date: Date) {
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- nightscout.deleteManualGlucose(at: date)
- .sink { completion in
- switch completion {
- case .finished:
- debug(.nightscout, "Manual Glucose entry deleted")
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &lifetime)
- }
- func uploadStatistics(dailystat: Statistics) {
- let stats = NightscoutStatistics(
- dailystats: dailystat
- )
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- processQueue.async {
- nightscout.uploadStats(stats)
- .sink { completion in
- switch completion {
- case .finished:
- debug(.nightscout, "Statistics uploaded")
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- }
- func uploadPreferences(_ preferences: Preferences) {
- let prefs = NightscoutPreferences(
- preferences: settingsManager.preferences
- )
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- processQueue.async {
- nightscout.uploadPrefs(prefs)
- .sink { completion in
- switch completion {
- case .finished:
- debug(.nightscout, "Preferences uploaded")
- self.storage.save(preferences, as: OpenAPS.Nightscout.uploadedPreferences)
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- }
- func uploadSettings(_ settings: FreeAPSSettings) {
- let sets = NightscoutSettings(
- settings: settingsManager.settings
- )
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- processQueue.async {
- nightscout.uploadSettings(sets)
- .sink { completion in
- switch completion {
- case .finished:
- debug(.nightscout, "Settings uploaded")
- self.storage.save(settings, as: OpenAPS.Nightscout.uploadedSettings)
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- }
- private func fetchBattery() -> Battery {
- do {
- let results = try context.fetch(OpenAPS_Battery.fetch(NSPredicate.predicateFor30MinAgo))
- if let last = results.first {
- let percent: Int? = Int(last.percent)
- let voltage: Decimal? = last.voltage as Decimal?
- let status: String? = last.status
- let display: Bool? = last.display
- if let percent = percent, let voltage = voltage, let status = status, let display = display {
- debugPrint(
- "Home State Model: \(#function) \(DebuggingIdentifiers.succeeded) setup battery from core data successfully"
- )
- return Battery(
- percent: percent,
- voltage: voltage,
- string: BatteryState(rawValue: status) ?? BatteryState.normal,
- display: display
- )
- }
- }
- return Battery(percent: 100, voltage: 100, string: BatteryState.normal, display: false)
- } catch {
- debugPrint(
- "Home State Model: \(#function) \(DebuggingIdentifiers.failed) failed to setup battery from core data"
- )
- return Battery(percent: 100, voltage: 100, string: BatteryState.normal, display: false)
- }
- }
- private func fetchDeterminations() {
- let fetchRequest: NSFetchRequest<OrefDetermination> = OrefDetermination.fetchRequest()
- fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \OrefDetermination.deliverAt, ascending: false)]
- fetchRequest.predicate = NSPredicate.predicateFor30MinAgoForDetermination
- fetchRequest.fetchLimit = 2
- do {
- lastTwoDeterminations = try context.fetch(fetchRequest)
- debugPrint(
- "Home State Model: \(#function) \(DebuggingIdentifiers.succeeded) fetched determinations from core data"
- )
- } catch {
- debugPrint(
- "Home State Model: \(#function) \(DebuggingIdentifiers.failed) failed to fetch determinations from core data"
- )
- }
- }
- func uploadStatus() {
- let iob = storage.retrieve(OpenAPS.Monitor.iob, as: [IOBEntry].self)
- let penultimateDetermination = lastTwoDeterminations?.last
- let lastDetermination = lastTwoDeterminations?.first
- var suggested: Determination?
- var enacted: Determination?
- if let lastDetermination = lastDetermination, let penultimateDetermination = penultimateDetermination {
- if lastDetermination.enacted, penultimateDetermination.enacted {
- suggested = Determination(
- reason: lastDetermination.reason ?? "",
- units: lastDetermination.smbToDeliver?.decimalValue,
- insulinReq: lastDetermination.insulinReq?.decimalValue,
- eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
- sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
- rate: lastDetermination.rate?.decimalValue,
- duration: Int(lastDetermination.duration),
- iob: lastDetermination.iob?.decimalValue,
- cob: Decimal(lastDetermination.cob),
- predictions: nil,
- deliverAt: lastDetermination.deliverAt ?? Date(),
- carbsReq: Decimal(lastDetermination.carbsRequired),
- temp: TempType(rawValue: lastDetermination.temp ?? ""),
- bg: lastDetermination.glucose?.decimalValue,
- reservoir: lastDetermination.reservoir?.decimalValue,
- isf: lastDetermination.insulinSensitivity?.decimalValue,
- timestamp: lastDetermination.timestamp,
- recieved: lastDetermination.received,
- tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- insulin: Insulin(
- TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
- temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
- scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
- ),
- current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
- insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
- manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
- minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
- expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
- minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
- carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
- )
- enacted = Determination(
- reason: lastDetermination.reason ?? "",
- units: lastDetermination.smbToDeliver?.decimalValue,
- insulinReq: lastDetermination.insulinReq?.decimalValue,
- eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
- sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
- rate: lastDetermination.rate?.decimalValue,
- duration: Int(lastDetermination.duration),
- iob: lastDetermination.iob?.decimalValue,
- cob: Decimal(lastDetermination.cob),
- predictions: nil,
- deliverAt: lastDetermination.deliverAt ?? Date(),
- carbsReq: Decimal(lastDetermination.carbsRequired),
- temp: TempType(rawValue: lastDetermination.temp ?? ""),
- bg: lastDetermination.glucose?.decimalValue,
- reservoir: lastDetermination.reservoir?.decimalValue,
- isf: lastDetermination.insulinSensitivity?.decimalValue,
- timestamp: lastDetermination.timestamp,
- recieved: lastDetermination.received,
- tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- insulin: Insulin(
- TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
- temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
- scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
- ),
- current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
- insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
- manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
- minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
- expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
- minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
- carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
- )
- } else if !lastDetermination.enacted, penultimateDetermination.enacted {
- suggested = Determination(
- reason: lastDetermination.reason ?? "",
- units: lastDetermination.smbToDeliver?.decimalValue,
- insulinReq: lastDetermination.insulinReq?.decimalValue,
- eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
- sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
- rate: lastDetermination.rate?.decimalValue,
- duration: Int(lastDetermination.duration),
- iob: lastDetermination.iob?.decimalValue,
- cob: Decimal(lastDetermination.cob),
- predictions: nil,
- deliverAt: lastDetermination.deliverAt ?? Date(),
- carbsReq: Decimal(lastDetermination.carbsRequired),
- temp: TempType(rawValue: lastDetermination.temp ?? ""),
- bg: lastDetermination.glucose?.decimalValue,
- reservoir: lastDetermination.reservoir?.decimalValue,
- isf: lastDetermination.insulinSensitivity?.decimalValue,
- timestamp: lastDetermination.timestamp,
- recieved: lastDetermination.received,
- tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- insulin: Insulin(
- TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
- temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
- scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
- ),
- current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
- insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
- manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
- minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
- expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
- minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
- carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
- )
- enacted = Determination(
- reason: penultimateDetermination.reason ?? "",
- units: penultimateDetermination.smbToDeliver?.decimalValue,
- insulinReq: penultimateDetermination.insulinReq?.decimalValue,
- eventualBG: Int(truncating: penultimateDetermination.eventualBG ?? 0),
- sensitivityRatio: penultimateDetermination.sensitivityRatio?.decimalValue,
- rate: penultimateDetermination.rate?.decimalValue,
- duration: Int(penultimateDetermination.duration),
- iob: penultimateDetermination.iob?.decimalValue,
- cob: Decimal(penultimateDetermination.cob),
- predictions: nil,
- deliverAt: penultimateDetermination.deliverAt ?? Date(),
- carbsReq: Decimal(penultimateDetermination.carbsRequired),
- temp: TempType(rawValue: penultimateDetermination.temp ?? ""),
- bg: penultimateDetermination.glucose?.decimalValue,
- reservoir: penultimateDetermination.reservoir?.decimalValue,
- isf: penultimateDetermination.insulinSensitivity?.decimalValue,
- timestamp: penultimateDetermination.timestamp,
- recieved: penultimateDetermination.received,
- tdd: penultimateDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- insulin: Insulin(
- TDD: penultimateDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- bolus: penultimateDetermination.bolus?.decimalValue ?? Decimal(0),
- temp_basal: penultimateDetermination.tempBasal?.decimalValue ?? Decimal(0),
- scheduled_basal: penultimateDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
- ),
- current_target: penultimateDetermination.currentTarget?.decimalValue ?? Decimal(0),
- insulinForManualBolus: penultimateDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
- manualBolusErrorString: penultimateDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
- minDelta: penultimateDetermination.minDelta?.decimalValue ?? Decimal(0),
- expectedDelta: penultimateDetermination.expectedDelta?.decimalValue ?? Decimal(0),
- minGuardBG: nil,
- minPredBG: nil,
- threshold: penultimateDetermination.threshold?.decimalValue ?? Decimal(0),
- carbRatio: penultimateDetermination.carbRatio?.decimalValue ?? Decimal(0)
- )
- } else if !lastDetermination.enacted, !penultimateDetermination.enacted {
- suggested = Determination(
- reason: lastDetermination.reason ?? "",
- units: lastDetermination.smbToDeliver?.decimalValue,
- insulinReq: lastDetermination.insulinReq?.decimalValue,
- eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
- sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
- rate: lastDetermination.rate?.decimalValue,
- duration: Int(lastDetermination.duration),
- iob: lastDetermination.iob?.decimalValue,
- cob: Decimal(lastDetermination.cob),
- predictions: nil,
- deliverAt: lastDetermination.deliverAt ?? Date(),
- carbsReq: Decimal(lastDetermination.carbsRequired),
- temp: TempType(rawValue: lastDetermination.temp ?? ""),
- bg: lastDetermination.glucose?.decimalValue,
- reservoir: lastDetermination.reservoir?.decimalValue,
- isf: lastDetermination.insulinSensitivity?.decimalValue,
- timestamp: lastDetermination.timestamp,
- recieved: lastDetermination.received,
- tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- insulin: Insulin(
- TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
- bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
- temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
- scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
- ),
- current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
- insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
- manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
- minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
- expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
- minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
- carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
- )
- }
- }
- let loopIsClosed = settingsManager.settings.closedLoop
- var openapsStatus: OpenAPSStatus
- // Only upload suggested in Open Loop Mode. Only upload enacted in Closed Loop Mode.
- if loopIsClosed {
- openapsStatus = OpenAPSStatus(
- iob: iob?.first,
- suggested: nil,
- enacted: enacted,
- version: "0.7.1"
- )
- } else {
- openapsStatus = OpenAPSStatus(
- iob: iob?.first,
- suggested: suggested,
- enacted: nil,
- version: "0.7.1"
- )
- }
- let battery = fetchBattery()
- var reservoir = Decimal(from: storage.retrieveRaw(OpenAPS.Monitor.reservoir) ?? "0")
- if reservoir == 0xDEAD_BEEF {
- reservoir = nil
- }
- let pumpStatus = storage.retrieve(OpenAPS.Monitor.status, as: PumpStatus.self)
- let pump = NSPumpStatus(clock: Date(), battery: battery, reservoir: reservoir, status: pumpStatus)
- let device = UIDevice.current
- let uploader = Uploader(batteryVoltage: nil, battery: Int(device.batteryLevel * 100))
- var status: NightscoutStatus
- status = NightscoutStatus(
- device: NigtscoutTreatment.local,
- openaps: openapsStatus,
- pump: pump,
- uploader: uploader
- )
- storage.save(status, as: OpenAPS.Upload.nsStatus)
- guard let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- processQueue.async {
- nightscout.uploadStatus(status)
- .sink { completion in
- switch completion {
- case .finished:
- debug(.nightscout, "Status uploaded")
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- uploadPodAge()
- }
- func uploadPodAge() {
- let uploadedPodAge = storage.retrieve(OpenAPS.Nightscout.uploadedPodAge, as: [NigtscoutTreatment].self) ?? []
- if let podAge = storage.retrieve(OpenAPS.Monitor.podAge, as: Date.self),
- uploadedPodAge.last?.createdAt == nil || podAge != uploadedPodAge.last!.createdAt!
- {
- let siteTreatment = NigtscoutTreatment(
- duration: nil,
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: .nsSiteChange,
- createdAt: podAge,
- enteredBy: NigtscoutTreatment.local,
- bolus: nil,
- insulin: nil,
- notes: nil,
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- uploadTreatments([siteTreatment], fileToSave: OpenAPS.Nightscout.uploadedPodAge)
- }
- }
- func uploadProfileAndSettings(_ force: Bool) {
- guard let sensitivities = storage.retrieve(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self) else {
- debug(.nightscout, "NightscoutManager uploadProfile: error loading insulinSensitivities")
- return
- }
- guard let settings = storage.retrieve(OpenAPS.FreeAPS.settings, as: FreeAPSSettings.self) else {
- debug(.nightscout, "NightscoutManager uploadProfile: error loading settings")
- return
- }
- guard let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) else {
- debug(.nightscout, "NightscoutManager uploadProfile: error loading preferences")
- return
- }
- guard let targets = storage.retrieve(OpenAPS.Settings.bgTargets, as: BGTargets.self) else {
- debug(.nightscout, "NightscoutManager uploadProfile: error loading bgTargets")
- return
- }
- guard let carbRatios = storage.retrieve(OpenAPS.Settings.carbRatios, as: CarbRatios.self) else {
- debug(.nightscout, "NightscoutManager uploadProfile: error loading carbRatios")
- return
- }
- guard let basalProfile = storage.retrieve(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self) else {
- debug(.nightscout, "NightscoutManager uploadProfile: error loading basalProfile")
- return
- }
- let sens = sensitivities.sensitivities.map { item -> NightscoutTimevalue in
- NightscoutTimevalue(
- time: String(item.start.prefix(5)),
- value: item.sensitivity,
- timeAsSeconds: item.offset * 60
- )
- }
- let target_low = targets.targets.map { item -> NightscoutTimevalue in
- NightscoutTimevalue(
- time: String(item.start.prefix(5)),
- value: item.low,
- timeAsSeconds: item.offset * 60
- )
- }
- let target_high = targets.targets.map { item -> NightscoutTimevalue in
- NightscoutTimevalue(
- time: String(item.start.prefix(5)),
- value: item.high,
- timeAsSeconds: item.offset * 60
- )
- }
- let cr = carbRatios.schedule.map { item -> NightscoutTimevalue in
- NightscoutTimevalue(
- time: String(item.start.prefix(5)),
- value: item.ratio,
- timeAsSeconds: item.offset * 60
- )
- }
- let basal = basalProfile.map { item -> NightscoutTimevalue in
- NightscoutTimevalue(
- time: String(item.start.prefix(5)),
- value: item.rate,
- timeAsSeconds: item.minutes * 60
- )
- }
- var nsUnits = ""
- switch settingsManager.settings.units {
- case .mgdL:
- nsUnits = "mg/dl"
- case .mmolL:
- nsUnits = "mmol"
- }
- var carbs_hr: Decimal = 0
- if let isf = sensitivities.sensitivities.map(\.sensitivity).first,
- let cr = carbRatios.schedule.map(\.ratio).first,
- isf > 0, cr > 0
- {
- // CarbImpact -> Carbs/hr = CI [mg/dl/5min] * 12 / ISF [mg/dl/U] * CR [g/U]
- carbs_hr = settingsManager.preferences.min5mCarbimpact * 12 / isf * cr
- if settingsManager.settings.units == .mmolL {
- carbs_hr = carbs_hr * GlucoseUnits.exchangeRate
- }
- // No, Decimal has no rounding function.
- carbs_hr = Decimal(round(Double(carbs_hr) * 10.0)) / 10
- }
- let ps = ScheduledNightscoutProfile(
- dia: settingsManager.pumpSettings.insulinActionCurve,
- carbs_hr: Int(carbs_hr),
- delay: 0,
- timezone: TimeZone.current.identifier,
- target_low: target_low,
- target_high: target_high,
- sens: sens,
- basal: basal,
- carbratio: cr,
- units: nsUnits
- )
- let defaultProfile = "default"
- let now = Date()
- let p = NightscoutProfileStore(
- defaultProfile: defaultProfile,
- startDate: now,
- mills: Int(now.timeIntervalSince1970) * 1000,
- units: nsUnits,
- enteredBy: NigtscoutTreatment.local,
- store: [defaultProfile: ps]
- )
- guard let nightscout = nightscoutAPI, isNetworkReachable, isUploadEnabled else {
- return
- }
- // UPLOAD PREFERNCES WHEN CHANGED
- if let uploadedPreferences = storage.retrieve(OpenAPS.Nightscout.uploadedPreferences, as: Preferences.self),
- uploadedPreferences.rawJSON.sorted() == preferences.rawJSON.sorted(), !force
- {
- NSLog("NightscoutManager Preferences, preferences unchanged")
- } else { uploadPreferences(preferences) }
- // UPLOAD FreeAPS Settings WHEN CHANGED
- if let uploadedSettings = storage.retrieve(OpenAPS.Nightscout.uploadedSettings, as: FreeAPSSettings.self),
- uploadedSettings.rawJSON.sorted() == settings.rawJSON.sorted(), !force
- {
- NSLog("NightscoutManager Settings, settings unchanged")
- } else { uploadSettings(settings) }
- // UPLOAD Profiles WHEN CHANGED
- if let uploadedProfile = storage.retrieve(OpenAPS.Nightscout.uploadedProfile, as: NightscoutProfileStore.self),
- (uploadedProfile.store["default"]?.rawJSON ?? "").sorted() == ps.rawJSON.sorted(), !force
- {
- NSLog("NightscoutManager uploadProfile, no profile change")
- } else {
- processQueue.async {
- nightscout.uploadProfile(p)
- .sink { completion in
- switch completion {
- case .finished:
- self.storage.save(p, as: OpenAPS.Nightscout.uploadedProfile)
- debug(.nightscout, "Profile uploaded")
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- }
- }
- func uploadGlucose() {
- uploadGlucose(glucoseStorage.nightscoutGlucoseNotUploaded(), fileToSave: OpenAPS.Nightscout.uploadedGlucose)
- uploadTreatments(glucoseStorage.nightscoutCGMStateNotUploaded(), fileToSave: OpenAPS.Nightscout.uploadedCGMState)
- }
- func uploadManualGlucose() {
- uploadTreatments(
- glucoseStorage.nightscoutManualGlucoseNotUploaded(),
- fileToSave: OpenAPS.Nightscout.uploadedManualGlucose
- )
- }
- private func uploadPumpHistory() {
- uploadTreatments(pumpHistoryStorage.nightscoutTretmentsNotUploaded(), fileToSave: OpenAPS.Nightscout.uploadedPumphistory)
- }
- private func uploadCarbs() {
- uploadTreatments(carbsStorage.nightscoutTretmentsNotUploaded(), fileToSave: OpenAPS.Nightscout.uploadedCarbs)
- }
- private func uploadTempTargets() {
- uploadTreatments(tempTargetsStorage.nightscoutTretmentsNotUploaded(), fileToSave: OpenAPS.Nightscout.uploadedTempTargets)
- }
- private func uploadGlucose(_ glucose: [BloodGlucose], fileToSave: String) {
- guard !glucose.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled, isUploadGlucoseEnabled else {
- return
- }
- // check if unique code
- // var uuid = UUID(uuidString: yourString) This will return nil if yourString is not a valid UUID
- let glucoseWithoutCorrectID = glucose.filter { UUID(uuidString: $0._id) != nil }
- processQueue.async {
- glucoseWithoutCorrectID.chunks(ofCount: 100)
- .map { chunk -> AnyPublisher<Void, Error> in
- nightscout.uploadGlucose(Array(chunk))
- }
- .reduce(
- Just(()).setFailureType(to: Error.self)
- .eraseToAnyPublisher()
- ) { (result, next) -> AnyPublisher<Void, Error> in
- Publishers.Concatenate(prefix: result, suffix: next).eraseToAnyPublisher()
- }
- .dropFirst()
- .sink { completion in
- switch completion {
- case .finished:
- self.storage.save(glucose, as: fileToSave)
- debug(.nightscout, "Glucose uploaded")
- case let .failure(error):
- debug(.nightscout, "Upload of glucose failed: " + error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- }
- private func uploadTreatments(_ treatments: [NigtscoutTreatment], fileToSave: String) {
- guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- processQueue.async {
- treatments.chunks(ofCount: 100)
- .map { chunk -> AnyPublisher<Void, Error> in
- nightscout.uploadTreatments(Array(chunk))
- }
- .reduce(
- Just(()).setFailureType(to: Error.self)
- .eraseToAnyPublisher()
- ) { (result, next) -> AnyPublisher<Void, Error> in
- Publishers.Concatenate(prefix: result, suffix: next).eraseToAnyPublisher()
- }
- .dropFirst()
- .sink { completion in
- switch completion {
- case .finished:
- self.storage.save(treatments, as: fileToSave)
- debug(.nightscout, "Treatments uploaded")
- case let .failure(error):
- debug(.nightscout, error.localizedDescription)
- }
- } receiveValue: {}
- .store(in: &self.lifetime)
- }
- }
- }
- extension BaseNightscoutManager: PumpHistoryObserver {
- func pumpHistoryDidUpdate(_: [PumpHistoryEvent]) {
- uploadPumpHistory()
- }
- }
- extension BaseNightscoutManager: CarbsObserver {
- func carbsDidUpdate(_: [CarbsEntry]) {
- uploadCarbs()
- }
- }
- extension BaseNightscoutManager: TempTargetsObserver {
- func tempTargetsDidUpdate(_: [TempTarget]) {
- uploadTempTargets()
- }
- }
- extension BaseNightscoutManager: GlucoseObserver {
- func glucoseDidUpdate(_: [BloodGlucose]) {
- uploadManualGlucose()
- }
- }
|