| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148 |
- import Combine
- import CoreData
- import Foundation
- import LoopKitUI
- import Swinject
- import UIKit
- protocol NightscoutManager: GlucoseSource {
- func fetchGlucose(since date: Date) async -> [BloodGlucose]
- func fetchCarbs() -> AnyPublisher<[CarbsEntry], Never>
- func fetchTempTargets() -> AnyPublisher<[TempTarget], Never>
- func fetchAnnouncements() -> AnyPublisher<[Announcement], Never>
- func deleteCarbs(withID id: String) async
- func deleteInsulin(withID id: String) async
- func deleteManualGlucose(withID id: String) async
- func uploadStatus()
- func uploadGlucose() async
- func uploadManualGlucose() async
- 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 overridesStorage: OverrideStorage!
- @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 backgroundContext = CoreDataStack.shared.newTaskContext()
- 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.newTaskContext()
- private var lastTwoDeterminations: [OrefDetermination]?
- init(resolver: Resolver) {
- injectServices(resolver)
- subscribe()
- }
- private func subscribe() {
- setupNotification()
- _ = 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) async -> [BloodGlucose] {
- let useLocal = settingsManager.settings.useLocalGlucoseSource
- ping = nil
- if !useLocal {
- guard isNetworkReachable else {
- return []
- }
- }
- let maybeNightscout = useLocal
- ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
- : nightscoutAPI
- guard let nightscout = maybeNightscout else {
- return []
- }
- let startDate = Date()
- do {
- let glucose = try await nightscout.fetchLastGlucose(sinceDate: date)
- if glucose.isNotEmpty {
- ping = Date().timeIntervalSince(startDate)
- }
- return glucose
- } catch {
- print(error.localizedDescription)
- return []
- }
- }
- // MARK: - GlucoseSource
- var glucoseManager: FetchGlucoseManager?
- var cgmManager: CGMManagerUI?
- var cgmType: CGMType = .nightscout
- func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
- Future { promise in
- Task {
- let glucoseData = await self.fetchGlucose(since: self.glucoseStorage.syncDate())
- promise(.success(glucoseData))
- }
- }
- .eraseToAnyPublisher()
- }
- 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(withID id: String) async {
- guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
- // TODO: - healthkit rewrite, deletion of FPUs
- // healthkitManager.deleteCarbs(syncID: arg1, fpuID: arg2)
- do {
- try await nightscout.deleteCarbs(withId: id)
- debug(.nightscout, "Carbs deleted")
- } catch {
- debug(
- .nightscout,
- "\(DebuggingIdentifiers.failed) Failed to delete Carbs from Nightscout with error: \(error.localizedDescription)"
- )
- }
- }
- func deleteInsulin(withID id: String) async {
- guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
- do {
- try await nightscout.deleteInsulin(withId: id)
- debug(.nightscout, "Insulin deleted")
- } catch {
- debug(
- .nightscout,
- "\(DebuggingIdentifiers.failed) Failed to delete Insulin from Nightscout with error: \(error.localizedDescription)"
- )
- }
- }
- func deleteManualGlucose(withID id: String) async {
- guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
- do {
- try await nightscout.deleteManualGlucose(withId: id)
- } catch {
- debug(
- .nightscout,
- "\(DebuggingIdentifiers.failed) Failed to delete Manual Glucose from Nightscout with error: \(error.localizedDescription)"
- )
- }
- }
- 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 {
- context.performAndWait {
- 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
- context.performAndWait {
- 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: lastDetermination.duration?.decimalValue,
- 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: lastDetermination.duration?.decimalValue,
- 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: lastDetermination.duration?.decimalValue,
- 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: lastDetermination.duration?.decimalValue,
- 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: lastDetermination.duration?.decimalValue,
- 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: NightscoutTreatment.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)
- }
- Task {
- await uploadPodAge()
- }
- }
- func uploadPodAge() async {
- let uploadedPodAge = storage.retrieve(OpenAPS.Nightscout.uploadedPodAge, as: [NightscoutTreatment].self) ?? []
- if let podAge = storage.retrieve(OpenAPS.Monitor.podAge, as: Date.self),
- uploadedPodAge.last?.createdAt == nil || podAge != uploadedPodAge.last!.createdAt!
- {
- let siteTreatment = NightscoutTreatment(
- duration: nil,
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: .nsSiteChange,
- createdAt: podAge,
- enteredBy: NightscoutTreatment.local,
- bolus: nil,
- insulin: nil,
- notes: nil,
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- await 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: NightscoutTreatment.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() async {
- await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToNightscout())
- await uploadTreatments(
- glucoseStorage.getCGMStateNotYetUploadedToNightscout(),
- fileToSave: OpenAPS.Nightscout.uploadedCGMState
- )
- }
- func uploadManualGlucose() async {
- await uploadManualGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToNightscout())
- }
- private func uploadPumpHistory() async {
- await uploadTreatments(
- pumpHistoryStorage.getPumpHistoryNotYetUploadedToNightscout(),
- fileToSave: OpenAPS.Nightscout.uploadedPumphistory
- )
- }
- private func uploadCarbs() async {
- await uploadCarbs(carbsStorage.getCarbsNotYetUploadedToNightscout())
- await uploadCarbs(carbsStorage.getFPUsNotYetUploadedToNightscout())
- }
- private func uploadOverrides() async {
- await uploadOverrides(overridesStorage.getOverridesNotYetUploadedToNightscout())
- await uploadOverrideRuns(overridesStorage.getOverrideRunsNotYetUploadedToNightscout())
- }
- private func uploadTempTargets() async {
- await uploadTreatments(
- tempTargetsStorage.nightscoutTreatmentsNotUploaded(),
- fileToSave: OpenAPS.Nightscout.uploadedTempTargets
- )
- }
- private func uploadGlucose(_ glucose: [BloodGlucose]) async {
- guard !glucose.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled, isUploadGlucoseEnabled else {
- return
- }
- do {
- // Upload in Batches of 100
- for chunk in glucose.chunks(ofCount: 100) {
- try await nightscout.uploadGlucose(Array(chunk))
- }
- // If successful, update the isUploadedToNS property of the GlucoseStored objects
- await updateGlucoseAsUploaded(glucose)
- debug(.nightscout, "Glucose uploaded")
- } catch {
- debug(.nightscout, "Upload of glucose failed: \(error.localizedDescription)")
- }
- }
- 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
- }
- guard self.backgroundContext.hasChanges else { return }
- try self.backgroundContext.save()
- } catch let error as NSError {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
- )
- }
- }
- }
- private func uploadTreatments(_ treatments: [NightscoutTreatment], fileToSave _: String) async {
- guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- do {
- for chunk in treatments.chunks(ofCount: 100) {
- try await nightscout.uploadTreatments(Array(chunk))
- }
- // If successful, update the isUploadedToNS property of the PumpEventStored objects
- await updateTreatmentsAsUploaded(treatments)
- debug(.nightscout, "Treatments uploaded")
- } catch {
- debug(.nightscout, error.localizedDescription)
- }
- }
- 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
- }
- guard self.backgroundContext.hasChanges else { return }
- try self.backgroundContext.save()
- } catch let error as NSError {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
- )
- }
- }
- }
- private func uploadManualGlucose(_ treatments: [NightscoutTreatment]) async {
- guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- do {
- for chunk in treatments.chunks(ofCount: 100) {
- try await nightscout.uploadTreatments(Array(chunk))
- }
- // If successful, update the isUploadedToNS property of the GlucoseStored objects
- await updateManualGlucoseAsUploaded(treatments)
- debug(.nightscout, "Treatments uploaded")
- } catch {
- debug(.nightscout, error.localizedDescription)
- }
- }
- 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
- }
- guard self.backgroundContext.hasChanges else { return }
- try self.backgroundContext.save()
- } catch let error as NSError {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
- )
- }
- }
- }
- private func uploadCarbs(_ treatments: [NightscoutTreatment]) async {
- guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- do {
- for chunk in treatments.chunks(ofCount: 100) {
- try await nightscout.uploadTreatments(Array(chunk))
- }
- // If successful, update the isUploadedToNS property of the CarbEntryStored objects
- await updateCarbsAsUploaded(treatments)
- debug(.nightscout, "Treatments uploaded")
- } catch {
- debug(.nightscout, error.localizedDescription)
- }
- }
- 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
- }
- guard self.backgroundContext.hasChanges else { return }
- try self.backgroundContext.save()
- } catch let error as NSError {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
- )
- }
- }
- }
- private func uploadOverrides(_ overrides: [NightscoutExercise]) async {
- guard !overrides.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- do {
- for chunk in overrides.chunks(ofCount: 100) {
- try await nightscout.uploadOverrides(Array(chunk))
- }
- // If successful, update the isUploadedToNS property of the OverrideStored objects
- await updateOverridesAsUploaded(overrides)
- debug(.nightscout, "Overrides uploaded")
- } catch {
- debug(.nightscout, error.localizedDescription)
- }
- }
- 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
- }
- guard self.backgroundContext.hasChanges else { return }
- try self.backgroundContext.save()
- } catch let error as NSError {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
- )
- }
- }
- }
- private func uploadOverrideRuns(_ overrideRuns: [NightscoutExercise]) async {
- guard !overrideRuns.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
- return
- }
- do {
- for chunk in overrideRuns.chunks(ofCount: 100) {
- try await nightscout.uploadOverrides(Array(chunk))
- }
- // If successful, update the isUploadedToNS property of the OverrideRunStored objects
- await updateOverrideRunsAsUploaded(overrideRuns)
- debug(.nightscout, "Overrides uploaded")
- } catch {
- debug(.nightscout, error.localizedDescription)
- }
- }
- 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
- }
- guard self.backgroundContext.hasChanges else { return }
- try self.backgroundContext.save()
- } catch let error as NSError {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
- )
- }
- }
- }
- }
- extension Array {
- func chunks(ofCount count: Int) -> [[Element]] {
- stride(from: 0, to: self.count, by: count).map {
- Array(self[$0 ..< Swift.min($0 + count, self.count)])
- }
- }
- }
- extension BaseNightscoutManager {
- /// listens for the notifications sent when the managedObjectContext has saved!
- func setupNotification() {
- Foundation.NotificationCenter.default.addObserver(
- self,
- selector: #selector(contextDidSave(_:)),
- name: Notification.Name.NSManagedObjectContextDidSave,
- object: nil
- )
- }
- /// determine the actions when the context has changed
- ///
- /// its done on a background thread and after that the UI gets updated on the main thread
- @objc private func contextDidSave(_ notification: Notification) {
- guard let userInfo = notification.userInfo else {
- return
- }
- Task { [weak self] in
- await self?.processUpdates(userInfo: userInfo)
- }
- }
- private func processUpdates(userInfo: [AnyHashable: Any]) async {
- var objects = Set((userInfo[NSInsertedObjectsKey] as? Set<NSManagedObject>) ?? [])
- objects.formUnion((userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [])
- objects.formUnion((userInfo[NSDeletedObjectsKey] as? Set<NSManagedObject>) ?? [])
- let manualGlucoseUpdates = objects.filter { $0 is GlucoseStored }
- let carbUpdates = objects.filter { $0 is CarbEntryStored }
- let pumpHistoryUpdates = objects.filter { $0 is PumpEventStored }
- let overrideUpdates = objects.filter { $0 is OverrideStored || $0 is OverrideRunStored }
- if manualGlucoseUpdates.isNotEmpty {
- Task.detached {
- await self.uploadManualGlucose()
- }
- }
- if carbUpdates.isNotEmpty {
- Task.detached {
- await self.uploadCarbs()
- }
- }
- if pumpHistoryUpdates.isNotEmpty {
- Task.detached {
- await self.uploadPumpHistory()
- }
- }
- if overrideUpdates.isNotEmpty {
- Task.detached {
- await self.uploadOverrides()
- }
- }
- }
- }
|