NightscoutManager.swift 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKitUI
  5. import Swinject
  6. import UIKit
  7. protocol NightscoutManager: GlucoseSource {
  8. func fetchGlucose(since date: Date) async -> [BloodGlucose]
  9. func fetchCarbs() async -> [CarbsEntry]
  10. func fetchTempTargets() async -> [TempTarget]
  11. func fetchAnnouncements() -> AnyPublisher<[Announcement], Never>
  12. func deleteCarbs(withID id: String) async
  13. func deleteInsulin(withID id: String) async
  14. func deleteManualGlucose(withID id: String) async
  15. func uploadStatus() async
  16. func uploadGlucose() async
  17. func uploadManualGlucose() async
  18. func uploadStatistics(dailystat: Statistics) async
  19. func uploadPreferences(_ preferences: Preferences)
  20. func uploadProfileAndSettings(_: Bool)
  21. var cgmURL: URL? { get }
  22. }
  23. final class BaseNightscoutManager: NightscoutManager, Injectable {
  24. @Injected() private var keychain: Keychain!
  25. @Injected() private var glucoseStorage: GlucoseStorage!
  26. @Injected() private var tempTargetsStorage: TempTargetsStorage!
  27. @Injected() private var overridesStorage: OverrideStorage!
  28. @Injected() private var carbsStorage: CarbsStorage!
  29. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  30. @Injected() private var storage: FileStorage!
  31. @Injected() private var announcementsStorage: AnnouncementsStorage!
  32. @Injected() private var settingsManager: SettingsManager!
  33. @Injected() private var broadcaster: Broadcaster!
  34. @Injected() private var reachabilityManager: ReachabilityManager!
  35. @Injected() var healthkitManager: HealthKitManager!
  36. private let processQueue = DispatchQueue(label: "BaseNetworkManager.processQueue")
  37. private var ping: TimeInterval?
  38. private var backgroundContext = CoreDataStack.shared.newTaskContext()
  39. private var lifetime = Lifetime()
  40. private var isNetworkReachable: Bool {
  41. reachabilityManager.isReachable
  42. }
  43. private var isUploadEnabled: Bool {
  44. settingsManager.settings.isUploadEnabled
  45. }
  46. private var isUploadGlucoseEnabled: Bool {
  47. settingsManager.settings.uploadGlucose
  48. }
  49. private var nightscoutAPI: NightscoutAPI? {
  50. guard let urlString = keychain.getValue(String.self, forKey: NightscoutConfig.Config.urlKey),
  51. let url = URL(string: urlString),
  52. let secret = keychain.getValue(String.self, forKey: NightscoutConfig.Config.secretKey)
  53. else {
  54. return nil
  55. }
  56. return NightscoutAPI(url: url, secret: secret)
  57. }
  58. private let context = CoreDataStack.shared.newTaskContext()
  59. private var lastTwoDeterminations: [OrefDetermination]?
  60. init(resolver: Resolver) {
  61. injectServices(resolver)
  62. subscribe()
  63. }
  64. private func subscribe() {
  65. setupNotification()
  66. _ = reachabilityManager.startListening(onQueue: processQueue) { status in
  67. debug(.nightscout, "Network status: \(status)")
  68. }
  69. }
  70. func sourceInfo() -> [String: Any]? {
  71. if let ping = ping {
  72. return [GlucoseSourceKey.nightscoutPing.rawValue: ping]
  73. }
  74. return nil
  75. }
  76. var cgmURL: URL? {
  77. if let url = settingsManager.settings.cgm.appURL {
  78. return url
  79. }
  80. let useLocal = settingsManager.settings.useLocalGlucoseSource
  81. let maybeNightscout = useLocal
  82. ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
  83. : nightscoutAPI
  84. return maybeNightscout?.url
  85. }
  86. func fetchGlucose(since date: Date) async -> [BloodGlucose] {
  87. let useLocal = settingsManager.settings.useLocalGlucoseSource
  88. ping = nil
  89. if !useLocal {
  90. guard isNetworkReachable else {
  91. return []
  92. }
  93. }
  94. let maybeNightscout = useLocal
  95. ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
  96. : nightscoutAPI
  97. guard let nightscout = maybeNightscout else {
  98. return []
  99. }
  100. let startDate = Date()
  101. do {
  102. let glucose = try await nightscout.fetchLastGlucose(sinceDate: date)
  103. if glucose.isNotEmpty {
  104. ping = Date().timeIntervalSince(startDate)
  105. }
  106. return glucose
  107. } catch {
  108. print(error.localizedDescription)
  109. return []
  110. }
  111. }
  112. // MARK: - GlucoseSource
  113. var glucoseManager: FetchGlucoseManager?
  114. var cgmManager: CGMManagerUI?
  115. var cgmType: CGMType = .nightscout
  116. func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
  117. Future { promise in
  118. Task {
  119. let glucoseData = await self.fetchGlucose(since: self.glucoseStorage.syncDate())
  120. promise(.success(glucoseData))
  121. }
  122. }
  123. .eraseToAnyPublisher()
  124. }
  125. func fetchIfNeeded() -> AnyPublisher<[BloodGlucose], Never> {
  126. fetch(nil)
  127. }
  128. func fetchCarbs() async -> [CarbsEntry] {
  129. guard let nightscout = nightscoutAPI, isNetworkReachable else {
  130. return []
  131. }
  132. let since = carbsStorage.syncDate()
  133. do {
  134. let carbs = try await nightscout.fetchCarbs(sinceDate: since)
  135. return carbs
  136. } catch {
  137. debug(.nightscout, "Error fetching carbs: \(error.localizedDescription)")
  138. return []
  139. }
  140. }
  141. func fetchTempTargets() async -> [TempTarget] {
  142. guard let nightscout = nightscoutAPI, isNetworkReachable else {
  143. return []
  144. }
  145. let since = tempTargetsStorage.syncDate()
  146. do {
  147. let tempTargets = try await nightscout.fetchTempTargets(sinceDate: since)
  148. return tempTargets
  149. } catch {
  150. debug(.nightscout, "Error fetching temp targets: \(error.localizedDescription)")
  151. return []
  152. }
  153. }
  154. func fetchAnnouncements() -> AnyPublisher<[Announcement], Never> {
  155. guard let nightscout = nightscoutAPI, isNetworkReachable else {
  156. return Just([]).eraseToAnyPublisher()
  157. }
  158. let since = announcementsStorage.syncDate()
  159. return nightscout.fetchAnnouncement(sinceDate: since)
  160. .replaceError(with: [])
  161. .eraseToAnyPublisher()
  162. }
  163. func deleteCarbs(withID id: String) async {
  164. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  165. // TODO: - healthkit rewrite, deletion of FPUs
  166. // healthkitManager.deleteCarbs(syncID: arg1, fpuID: arg2)
  167. do {
  168. try await nightscout.deleteCarbs(withId: id)
  169. debug(.nightscout, "Carbs deleted")
  170. } catch {
  171. debug(
  172. .nightscout,
  173. "\(DebuggingIdentifiers.failed) Failed to delete Carbs from Nightscout with error: \(error.localizedDescription)"
  174. )
  175. }
  176. }
  177. func deleteInsulin(withID id: String) async {
  178. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  179. do {
  180. try await nightscout.deleteInsulin(withId: id)
  181. debug(.nightscout, "Insulin deleted")
  182. } catch {
  183. debug(
  184. .nightscout,
  185. "\(DebuggingIdentifiers.failed) Failed to delete Insulin from Nightscout with error: \(error.localizedDescription)"
  186. )
  187. }
  188. }
  189. func deleteManualGlucose(withID id: String) async {
  190. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  191. do {
  192. try await nightscout.deleteManualGlucose(withId: id)
  193. } catch {
  194. debug(
  195. .nightscout,
  196. "\(DebuggingIdentifiers.failed) Failed to delete Manual Glucose from Nightscout with error: \(error.localizedDescription)"
  197. )
  198. }
  199. }
  200. func uploadStatistics(dailystat: Statistics) async {
  201. let stats = NightscoutStatistics(dailystats: dailystat)
  202. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  203. return
  204. }
  205. do {
  206. try await nightscout.uploadStats(stats)
  207. debug(.nightscout, "Statistics uploaded")
  208. } catch {
  209. debug(.nightscout, error.localizedDescription)
  210. }
  211. }
  212. func uploadPreferences(_ preferences: Preferences) {
  213. let prefs = NightscoutPreferences(
  214. preferences: settingsManager.preferences
  215. )
  216. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  217. return
  218. }
  219. processQueue.async {
  220. nightscout.uploadPrefs(prefs)
  221. .sink { completion in
  222. switch completion {
  223. case .finished:
  224. debug(.nightscout, "Preferences uploaded")
  225. self.storage.save(preferences, as: OpenAPS.Nightscout.uploadedPreferences)
  226. case let .failure(error):
  227. debug(.nightscout, error.localizedDescription)
  228. }
  229. } receiveValue: {}
  230. .store(in: &self.lifetime)
  231. }
  232. }
  233. func uploadSettings(_ settings: FreeAPSSettings) {
  234. let sets = NightscoutSettings(
  235. settings: settingsManager.settings
  236. )
  237. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  238. return
  239. }
  240. processQueue.async {
  241. nightscout.uploadSettings(sets)
  242. .sink { completion in
  243. switch completion {
  244. case .finished:
  245. debug(.nightscout, "Settings uploaded")
  246. self.storage.save(settings, as: OpenAPS.Nightscout.uploadedSettings)
  247. case let .failure(error):
  248. debug(.nightscout, error.localizedDescription)
  249. }
  250. } receiveValue: {}
  251. .store(in: &self.lifetime)
  252. }
  253. }
  254. private func fetchBattery() -> Battery {
  255. context.performAndWait {
  256. do {
  257. let results = try context.fetch(OpenAPS_Battery.fetch(NSPredicate.predicateFor30MinAgo))
  258. if let last = results.first {
  259. let percent: Int? = Int(last.percent)
  260. let voltage: Decimal? = last.voltage as Decimal?
  261. let status: String? = last.status
  262. let display: Bool? = last.display
  263. if let percent = percent, let voltage = voltage, let status = status, let display = display {
  264. debugPrint(
  265. "Home State Model: \(#function) \(DebuggingIdentifiers.succeeded) setup battery from core data successfully"
  266. )
  267. return Battery(
  268. percent: percent,
  269. voltage: voltage,
  270. string: BatteryState(rawValue: status) ?? BatteryState.normal,
  271. display: display
  272. )
  273. }
  274. }
  275. return Battery(percent: 100, voltage: 100, string: BatteryState.normal, display: false)
  276. } catch {
  277. debugPrint(
  278. "Home State Model: \(#function) \(DebuggingIdentifiers.failed) failed to setup battery from core data"
  279. )
  280. return Battery(percent: 100, voltage: 100, string: BatteryState.normal, display: false)
  281. }
  282. }
  283. }
  284. // TODO: - Fetch Determination here
  285. func uploadStatus() async {
  286. let iob = storage.retrieve(OpenAPS.Monitor.iob, as: [IOBEntry].self)
  287. let penultimateDetermination = lastTwoDeterminations?.last
  288. let lastDetermination = lastTwoDeterminations?.first
  289. var suggested: Determination?
  290. var enacted: Determination?
  291. if let lastDetermination = lastDetermination, let penultimateDetermination = penultimateDetermination {
  292. if lastDetermination.enacted, penultimateDetermination.enacted {
  293. suggested = Determination(
  294. reason: lastDetermination.reason ?? "",
  295. units: lastDetermination.smbToDeliver?.decimalValue,
  296. insulinReq: lastDetermination.insulinReq?.decimalValue,
  297. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  298. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  299. rate: lastDetermination.rate?.decimalValue,
  300. duration: lastDetermination.duration?.decimalValue,
  301. iob: lastDetermination.iob?.decimalValue,
  302. cob: Decimal(lastDetermination.cob),
  303. predictions: nil,
  304. deliverAt: lastDetermination.deliverAt ?? Date(),
  305. carbsReq: Decimal(lastDetermination.carbsRequired),
  306. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  307. bg: lastDetermination.glucose?.decimalValue,
  308. reservoir: lastDetermination.reservoir?.decimalValue,
  309. isf: lastDetermination.insulinSensitivity?.decimalValue,
  310. timestamp: lastDetermination.timestamp,
  311. recieved: lastDetermination.received,
  312. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  313. insulin: Insulin(
  314. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  315. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  316. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  317. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  318. ),
  319. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  320. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  321. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  322. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  323. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  324. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  325. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  326. )
  327. enacted = Determination(
  328. reason: lastDetermination.reason ?? "",
  329. units: lastDetermination.smbToDeliver?.decimalValue,
  330. insulinReq: lastDetermination.insulinReq?.decimalValue,
  331. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  332. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  333. rate: lastDetermination.rate?.decimalValue,
  334. duration: lastDetermination.duration?.decimalValue,
  335. iob: lastDetermination.iob?.decimalValue,
  336. cob: Decimal(lastDetermination.cob),
  337. predictions: nil,
  338. deliverAt: lastDetermination.deliverAt ?? Date(),
  339. carbsReq: Decimal(lastDetermination.carbsRequired),
  340. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  341. bg: lastDetermination.glucose?.decimalValue,
  342. reservoir: lastDetermination.reservoir?.decimalValue,
  343. isf: lastDetermination.insulinSensitivity?.decimalValue,
  344. timestamp: lastDetermination.timestamp,
  345. recieved: lastDetermination.received,
  346. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  347. insulin: Insulin(
  348. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  349. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  350. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  351. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  352. ),
  353. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  354. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  355. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  356. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  357. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  358. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  359. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  360. )
  361. } else if !lastDetermination.enacted, penultimateDetermination.enacted {
  362. suggested = Determination(
  363. reason: lastDetermination.reason ?? "",
  364. units: lastDetermination.smbToDeliver?.decimalValue,
  365. insulinReq: lastDetermination.insulinReq?.decimalValue,
  366. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  367. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  368. rate: lastDetermination.rate?.decimalValue,
  369. duration: lastDetermination.duration?.decimalValue,
  370. iob: lastDetermination.iob?.decimalValue,
  371. cob: Decimal(lastDetermination.cob),
  372. predictions: nil,
  373. deliverAt: lastDetermination.deliverAt ?? Date(),
  374. carbsReq: Decimal(lastDetermination.carbsRequired),
  375. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  376. bg: lastDetermination.glucose?.decimalValue,
  377. reservoir: lastDetermination.reservoir?.decimalValue,
  378. isf: lastDetermination.insulinSensitivity?.decimalValue,
  379. timestamp: lastDetermination.timestamp,
  380. recieved: lastDetermination.received,
  381. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  382. insulin: Insulin(
  383. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  384. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  385. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  386. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  387. ),
  388. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  389. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  390. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  391. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  392. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  393. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  394. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  395. )
  396. enacted = Determination(
  397. reason: penultimateDetermination.reason ?? "",
  398. units: penultimateDetermination.smbToDeliver?.decimalValue,
  399. insulinReq: penultimateDetermination.insulinReq?.decimalValue,
  400. eventualBG: Int(truncating: penultimateDetermination.eventualBG ?? 0),
  401. sensitivityRatio: penultimateDetermination.sensitivityRatio?.decimalValue,
  402. rate: penultimateDetermination.rate?.decimalValue,
  403. duration: lastDetermination.duration?.decimalValue,
  404. iob: penultimateDetermination.iob?.decimalValue,
  405. cob: Decimal(penultimateDetermination.cob),
  406. predictions: nil,
  407. deliverAt: penultimateDetermination.deliverAt ?? Date(),
  408. carbsReq: Decimal(penultimateDetermination.carbsRequired),
  409. temp: TempType(rawValue: penultimateDetermination.temp ?? ""),
  410. bg: penultimateDetermination.glucose?.decimalValue,
  411. reservoir: penultimateDetermination.reservoir?.decimalValue,
  412. isf: penultimateDetermination.insulinSensitivity?.decimalValue,
  413. timestamp: penultimateDetermination.timestamp,
  414. recieved: penultimateDetermination.received,
  415. tdd: penultimateDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  416. insulin: Insulin(
  417. TDD: penultimateDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  418. bolus: penultimateDetermination.bolus?.decimalValue ?? Decimal(0),
  419. temp_basal: penultimateDetermination.tempBasal?.decimalValue ?? Decimal(0),
  420. scheduled_basal: penultimateDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  421. ),
  422. current_target: penultimateDetermination.currentTarget?.decimalValue ?? Decimal(0),
  423. insulinForManualBolus: penultimateDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  424. manualBolusErrorString: penultimateDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  425. minDelta: penultimateDetermination.minDelta?.decimalValue ?? Decimal(0),
  426. expectedDelta: penultimateDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  427. minGuardBG: nil,
  428. minPredBG: nil,
  429. threshold: penultimateDetermination.threshold?.decimalValue ?? Decimal(0),
  430. carbRatio: penultimateDetermination.carbRatio?.decimalValue ?? Decimal(0)
  431. )
  432. } else if !lastDetermination.enacted, !penultimateDetermination.enacted {
  433. suggested = Determination(
  434. reason: lastDetermination.reason ?? "",
  435. units: lastDetermination.smbToDeliver?.decimalValue,
  436. insulinReq: lastDetermination.insulinReq?.decimalValue,
  437. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  438. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  439. rate: lastDetermination.rate?.decimalValue,
  440. duration: lastDetermination.duration?.decimalValue,
  441. iob: lastDetermination.iob?.decimalValue,
  442. cob: Decimal(lastDetermination.cob),
  443. predictions: nil,
  444. deliverAt: lastDetermination.deliverAt ?? Date(),
  445. carbsReq: Decimal(lastDetermination.carbsRequired),
  446. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  447. bg: lastDetermination.glucose?.decimalValue,
  448. reservoir: lastDetermination.reservoir?.decimalValue,
  449. isf: lastDetermination.insulinSensitivity?.decimalValue,
  450. timestamp: lastDetermination.timestamp,
  451. recieved: lastDetermination.received,
  452. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  453. insulin: Insulin(
  454. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  455. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  456. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  457. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  458. ),
  459. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  460. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  461. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  462. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  463. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  464. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  465. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  466. )
  467. }
  468. }
  469. let loopIsClosed = settingsManager.settings.closedLoop
  470. var openapsStatus: OpenAPSStatus
  471. // Only upload suggested in Open Loop Mode. Only upload enacted in Closed Loop Mode.
  472. if loopIsClosed {
  473. openapsStatus = OpenAPSStatus(
  474. iob: iob?.first,
  475. suggested: nil,
  476. enacted: enacted,
  477. version: "0.7.1"
  478. )
  479. } else {
  480. openapsStatus = OpenAPSStatus(
  481. iob: iob?.first,
  482. suggested: suggested,
  483. enacted: nil,
  484. version: "0.7.1"
  485. )
  486. }
  487. let battery = fetchBattery()
  488. var reservoir = Decimal(from: storage.retrieveRaw(OpenAPS.Monitor.reservoir) ?? "0")
  489. if reservoir == 0xDEAD_BEEF {
  490. reservoir = nil
  491. }
  492. let pumpStatus = storage.retrieve(OpenAPS.Monitor.status, as: PumpStatus.self)
  493. let pump = NSPumpStatus(clock: Date(), battery: battery, reservoir: reservoir, status: pumpStatus)
  494. let device = await UIDevice.current
  495. let uploader = await Uploader(batteryVoltage: nil, battery: Int(device.batteryLevel * 100))
  496. var status: NightscoutStatus
  497. status = NightscoutStatus(
  498. device: NightscoutTreatment.local,
  499. openaps: openapsStatus,
  500. pump: pump,
  501. uploader: uploader
  502. )
  503. storage.save(status, as: OpenAPS.Upload.nsStatus)
  504. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  505. return
  506. }
  507. do {
  508. try await nightscout.uploadStatus(status)
  509. debug(.nightscout, "Status uploaded")
  510. } catch {
  511. debug(.nightscout, error.localizedDescription)
  512. }
  513. Task.detached {
  514. await self.uploadPodAge()
  515. }
  516. }
  517. func uploadPodAge() async {
  518. let uploadedPodAge = storage.retrieve(OpenAPS.Nightscout.uploadedPodAge, as: [NightscoutTreatment].self) ?? []
  519. if let podAge = storage.retrieve(OpenAPS.Monitor.podAge, as: Date.self),
  520. uploadedPodAge.last?.createdAt == nil || podAge != uploadedPodAge.last!.createdAt!
  521. {
  522. let siteTreatment = NightscoutTreatment(
  523. duration: nil,
  524. rawDuration: nil,
  525. rawRate: nil,
  526. absolute: nil,
  527. rate: nil,
  528. eventType: .nsSiteChange,
  529. createdAt: podAge,
  530. enteredBy: NightscoutTreatment.local,
  531. bolus: nil,
  532. insulin: nil,
  533. notes: nil,
  534. carbs: nil,
  535. fat: nil,
  536. protein: nil,
  537. targetTop: nil,
  538. targetBottom: nil
  539. )
  540. await uploadTreatments([siteTreatment], fileToSave: OpenAPS.Nightscout.uploadedPodAge)
  541. }
  542. }
  543. func uploadProfileAndSettings(_ force: Bool) {
  544. guard let sensitivities = storage.retrieve(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self) else {
  545. debug(.nightscout, "NightscoutManager uploadProfile: error loading insulinSensitivities")
  546. return
  547. }
  548. guard let settings = storage.retrieve(OpenAPS.FreeAPS.settings, as: FreeAPSSettings.self) else {
  549. debug(.nightscout, "NightscoutManager uploadProfile: error loading settings")
  550. return
  551. }
  552. guard let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) else {
  553. debug(.nightscout, "NightscoutManager uploadProfile: error loading preferences")
  554. return
  555. }
  556. guard let targets = storage.retrieve(OpenAPS.Settings.bgTargets, as: BGTargets.self) else {
  557. debug(.nightscout, "NightscoutManager uploadProfile: error loading bgTargets")
  558. return
  559. }
  560. guard let carbRatios = storage.retrieve(OpenAPS.Settings.carbRatios, as: CarbRatios.self) else {
  561. debug(.nightscout, "NightscoutManager uploadProfile: error loading carbRatios")
  562. return
  563. }
  564. guard let basalProfile = storage.retrieve(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self) else {
  565. debug(.nightscout, "NightscoutManager uploadProfile: error loading basalProfile")
  566. return
  567. }
  568. let sens = sensitivities.sensitivities.map { item -> NightscoutTimevalue in
  569. NightscoutTimevalue(
  570. time: String(item.start.prefix(5)),
  571. value: item.sensitivity,
  572. timeAsSeconds: item.offset * 60
  573. )
  574. }
  575. let target_low = targets.targets.map { item -> NightscoutTimevalue in
  576. NightscoutTimevalue(
  577. time: String(item.start.prefix(5)),
  578. value: item.low,
  579. timeAsSeconds: item.offset * 60
  580. )
  581. }
  582. let target_high = targets.targets.map { item -> NightscoutTimevalue in
  583. NightscoutTimevalue(
  584. time: String(item.start.prefix(5)),
  585. value: item.high,
  586. timeAsSeconds: item.offset * 60
  587. )
  588. }
  589. let cr = carbRatios.schedule.map { item -> NightscoutTimevalue in
  590. NightscoutTimevalue(
  591. time: String(item.start.prefix(5)),
  592. value: item.ratio,
  593. timeAsSeconds: item.offset * 60
  594. )
  595. }
  596. let basal = basalProfile.map { item -> NightscoutTimevalue in
  597. NightscoutTimevalue(
  598. time: String(item.start.prefix(5)),
  599. value: item.rate,
  600. timeAsSeconds: item.minutes * 60
  601. )
  602. }
  603. var nsUnits = ""
  604. switch settingsManager.settings.units {
  605. case .mgdL:
  606. nsUnits = "mg/dl"
  607. case .mmolL:
  608. nsUnits = "mmol"
  609. }
  610. var carbs_hr: Decimal = 0
  611. if let isf = sensitivities.sensitivities.map(\.sensitivity).first,
  612. let cr = carbRatios.schedule.map(\.ratio).first,
  613. isf > 0, cr > 0
  614. {
  615. // CarbImpact -> Carbs/hr = CI [mg/dl/5min] * 12 / ISF [mg/dl/U] * CR [g/U]
  616. carbs_hr = settingsManager.preferences.min5mCarbimpact * 12 / isf * cr
  617. if settingsManager.settings.units == .mmolL {
  618. carbs_hr = carbs_hr * GlucoseUnits.exchangeRate
  619. }
  620. // No, Decimal has no rounding function.
  621. carbs_hr = Decimal(round(Double(carbs_hr) * 10.0)) / 10
  622. }
  623. let ps = ScheduledNightscoutProfile(
  624. dia: settingsManager.pumpSettings.insulinActionCurve,
  625. carbs_hr: Int(carbs_hr),
  626. delay: 0,
  627. timezone: TimeZone.current.identifier,
  628. target_low: target_low,
  629. target_high: target_high,
  630. sens: sens,
  631. basal: basal,
  632. carbratio: cr,
  633. units: nsUnits
  634. )
  635. let defaultProfile = "default"
  636. let now = Date()
  637. let p = NightscoutProfileStore(
  638. defaultProfile: defaultProfile,
  639. startDate: now,
  640. mills: Int(now.timeIntervalSince1970) * 1000,
  641. units: nsUnits,
  642. enteredBy: NightscoutTreatment.local,
  643. store: [defaultProfile: ps]
  644. )
  645. guard let nightscout = nightscoutAPI, isNetworkReachable, isUploadEnabled else {
  646. return
  647. }
  648. // UPLOAD PREFERNCES WHEN CHANGED
  649. if let uploadedPreferences = storage.retrieve(OpenAPS.Nightscout.uploadedPreferences, as: Preferences.self),
  650. uploadedPreferences.rawJSON.sorted() == preferences.rawJSON.sorted(), !force
  651. {
  652. NSLog("NightscoutManager Preferences, preferences unchanged")
  653. } else { uploadPreferences(preferences) }
  654. // UPLOAD FreeAPS Settings WHEN CHANGED
  655. if let uploadedSettings = storage.retrieve(OpenAPS.Nightscout.uploadedSettings, as: FreeAPSSettings.self),
  656. uploadedSettings.rawJSON.sorted() == settings.rawJSON.sorted(), !force
  657. {
  658. NSLog("NightscoutManager Settings, settings unchanged")
  659. } else { uploadSettings(settings) }
  660. // UPLOAD Profiles WHEN CHANGED
  661. if let uploadedProfile = storage.retrieve(OpenAPS.Nightscout.uploadedProfile, as: NightscoutProfileStore.self),
  662. (uploadedProfile.store["default"]?.rawJSON ?? "").sorted() == ps.rawJSON.sorted(), !force
  663. {
  664. NSLog("NightscoutManager uploadProfile, no profile change")
  665. } else {
  666. processQueue.async {
  667. nightscout.uploadProfile(p)
  668. .sink { completion in
  669. switch completion {
  670. case .finished:
  671. self.storage.save(p, as: OpenAPS.Nightscout.uploadedProfile)
  672. debug(.nightscout, "Profile uploaded")
  673. case let .failure(error):
  674. debug(.nightscout, error.localizedDescription)
  675. }
  676. } receiveValue: {}
  677. .store(in: &self.lifetime)
  678. }
  679. }
  680. }
  681. func uploadGlucose() async {
  682. await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToNightscout())
  683. await uploadTreatments(
  684. glucoseStorage.getCGMStateNotYetUploadedToNightscout(),
  685. fileToSave: OpenAPS.Nightscout.uploadedCGMState
  686. )
  687. }
  688. func uploadManualGlucose() async {
  689. await uploadManualGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToNightscout())
  690. }
  691. private func uploadPumpHistory() async {
  692. await uploadTreatments(
  693. pumpHistoryStorage.getPumpHistoryNotYetUploadedToNightscout(),
  694. fileToSave: OpenAPS.Nightscout.uploadedPumphistory
  695. )
  696. }
  697. private func uploadCarbs() async {
  698. await uploadCarbs(carbsStorage.getCarbsNotYetUploadedToNightscout())
  699. await uploadCarbs(carbsStorage.getFPUsNotYetUploadedToNightscout())
  700. }
  701. private func uploadOverrides() async {
  702. await uploadOverrides(overridesStorage.getOverridesNotYetUploadedToNightscout())
  703. await uploadOverrideRuns(overridesStorage.getOverrideRunsNotYetUploadedToNightscout())
  704. }
  705. private func uploadTempTargets() async {
  706. await uploadTreatments(
  707. tempTargetsStorage.nightscoutTreatmentsNotUploaded(),
  708. fileToSave: OpenAPS.Nightscout.uploadedTempTargets
  709. )
  710. }
  711. private func uploadGlucose(_ glucose: [BloodGlucose]) async {
  712. guard !glucose.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled, isUploadGlucoseEnabled else {
  713. return
  714. }
  715. do {
  716. // Upload in Batches of 100
  717. for chunk in glucose.chunks(ofCount: 100) {
  718. try await nightscout.uploadGlucose(Array(chunk))
  719. }
  720. // If successful, update the isUploadedToNS property of the GlucoseStored objects
  721. await updateGlucoseAsUploaded(glucose)
  722. debug(.nightscout, "Glucose uploaded")
  723. } catch {
  724. debug(.nightscout, "Upload of glucose failed: \(error.localizedDescription)")
  725. }
  726. }
  727. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  728. await backgroundContext.perform {
  729. let ids = glucose.map(\.id) as NSArray
  730. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  731. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  732. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  733. do {
  734. let results = try self.backgroundContext.fetch(fetchRequest)
  735. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  736. for result in results {
  737. result.isUploadedToNS = true
  738. }
  739. guard self.backgroundContext.hasChanges else { return }
  740. try self.backgroundContext.save()
  741. } catch let error as NSError {
  742. debugPrint(
  743. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  744. )
  745. }
  746. }
  747. }
  748. private func uploadTreatments(_ treatments: [NightscoutTreatment], fileToSave _: String) async {
  749. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  750. return
  751. }
  752. do {
  753. for chunk in treatments.chunks(ofCount: 100) {
  754. try await nightscout.uploadTreatments(Array(chunk))
  755. }
  756. // If successful, update the isUploadedToNS property of the PumpEventStored objects
  757. await updateTreatmentsAsUploaded(treatments)
  758. debug(.nightscout, "Treatments uploaded")
  759. } catch {
  760. debug(.nightscout, error.localizedDescription)
  761. }
  762. }
  763. private func updateTreatmentsAsUploaded(_ treatments: [NightscoutTreatment]) async {
  764. await backgroundContext.perform {
  765. let ids = treatments.map(\.id) as NSArray
  766. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  767. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  768. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  769. do {
  770. let results = try self.backgroundContext.fetch(fetchRequest)
  771. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  772. for result in results {
  773. result.isUploadedToNS = true
  774. }
  775. guard self.backgroundContext.hasChanges else { return }
  776. try self.backgroundContext.save()
  777. } catch let error as NSError {
  778. debugPrint(
  779. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  780. )
  781. }
  782. }
  783. }
  784. private func uploadManualGlucose(_ treatments: [NightscoutTreatment]) async {
  785. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  786. return
  787. }
  788. do {
  789. for chunk in treatments.chunks(ofCount: 100) {
  790. try await nightscout.uploadTreatments(Array(chunk))
  791. }
  792. // If successful, update the isUploadedToNS property of the GlucoseStored objects
  793. await updateManualGlucoseAsUploaded(treatments)
  794. debug(.nightscout, "Treatments uploaded")
  795. } catch {
  796. debug(.nightscout, error.localizedDescription)
  797. }
  798. }
  799. private func updateManualGlucoseAsUploaded(_ treatments: [NightscoutTreatment]) async {
  800. await backgroundContext.perform {
  801. let ids = treatments.map(\.id) as NSArray
  802. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  803. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  804. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  805. do {
  806. let results = try self.backgroundContext.fetch(fetchRequest)
  807. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  808. for result in results {
  809. result.isUploadedToNS = true
  810. }
  811. guard self.backgroundContext.hasChanges else { return }
  812. try self.backgroundContext.save()
  813. } catch let error as NSError {
  814. debugPrint(
  815. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  816. )
  817. }
  818. }
  819. }
  820. private func uploadCarbs(_ treatments: [NightscoutTreatment]) async {
  821. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  822. return
  823. }
  824. do {
  825. for chunk in treatments.chunks(ofCount: 100) {
  826. try await nightscout.uploadTreatments(Array(chunk))
  827. }
  828. // If successful, update the isUploadedToNS property of the CarbEntryStored objects
  829. await updateCarbsAsUploaded(treatments)
  830. debug(.nightscout, "Treatments uploaded")
  831. } catch {
  832. debug(.nightscout, error.localizedDescription)
  833. }
  834. }
  835. private func updateCarbsAsUploaded(_ treatments: [NightscoutTreatment]) async {
  836. await backgroundContext.perform {
  837. let ids = treatments.map(\.id) as NSArray
  838. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  839. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  840. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  841. do {
  842. let results = try self.backgroundContext.fetch(fetchRequest)
  843. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  844. for result in results {
  845. result.isUploadedToNS = true
  846. }
  847. guard self.backgroundContext.hasChanges else { return }
  848. try self.backgroundContext.save()
  849. } catch let error as NSError {
  850. debugPrint(
  851. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  852. )
  853. }
  854. }
  855. }
  856. private func uploadOverrides(_ overrides: [NightscoutExercise]) async {
  857. guard !overrides.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  858. return
  859. }
  860. do {
  861. for chunk in overrides.chunks(ofCount: 100) {
  862. try await nightscout.uploadOverrides(Array(chunk))
  863. }
  864. // If successful, update the isUploadedToNS property of the OverrideStored objects
  865. await updateOverridesAsUploaded(overrides)
  866. debug(.nightscout, "Overrides uploaded")
  867. } catch {
  868. debug(.nightscout, error.localizedDescription)
  869. }
  870. }
  871. private func updateOverridesAsUploaded(_ overrides: [NightscoutExercise]) async {
  872. await backgroundContext.perform {
  873. let ids = overrides.map(\.id) as NSArray
  874. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  875. let fetchRequest: NSFetchRequest<OverrideStored> = OverrideStored.fetchRequest()
  876. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  877. do {
  878. let results = try self.backgroundContext.fetch(fetchRequest)
  879. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  880. for result in results {
  881. result.isUploadedToNS = true
  882. }
  883. guard self.backgroundContext.hasChanges else { return }
  884. try self.backgroundContext.save()
  885. } catch let error as NSError {
  886. debugPrint(
  887. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  888. )
  889. }
  890. }
  891. }
  892. private func uploadOverrideRuns(_ overrideRuns: [NightscoutExercise]) async {
  893. guard !overrideRuns.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  894. return
  895. }
  896. do {
  897. for chunk in overrideRuns.chunks(ofCount: 100) {
  898. try await nightscout.uploadOverrides(Array(chunk))
  899. }
  900. // If successful, update the isUploadedToNS property of the OverrideRunStored objects
  901. await updateOverrideRunsAsUploaded(overrideRuns)
  902. debug(.nightscout, "Overrides uploaded")
  903. } catch {
  904. debug(.nightscout, error.localizedDescription)
  905. }
  906. }
  907. private func updateOverrideRunsAsUploaded(_ overrideRuns: [NightscoutExercise]) async {
  908. await backgroundContext.perform {
  909. let ids = overrideRuns.map(\.id) as NSArray
  910. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  911. let fetchRequest: NSFetchRequest<OverrideRunStored> = OverrideRunStored.fetchRequest()
  912. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  913. do {
  914. let results = try self.backgroundContext.fetch(fetchRequest)
  915. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  916. for result in results {
  917. result.isUploadedToNS = true
  918. }
  919. guard self.backgroundContext.hasChanges else { return }
  920. try self.backgroundContext.save()
  921. } catch let error as NSError {
  922. debugPrint(
  923. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  924. )
  925. }
  926. }
  927. }
  928. }
  929. extension Array {
  930. func chunks(ofCount count: Int) -> [[Element]] {
  931. stride(from: 0, to: self.count, by: count).map {
  932. Array(self[$0 ..< Swift.min($0 + count, self.count)])
  933. }
  934. }
  935. }
  936. extension BaseNightscoutManager {
  937. /// listens for the notifications sent when the managedObjectContext has saved!
  938. func setupNotification() {
  939. Foundation.NotificationCenter.default.addObserver(
  940. self,
  941. selector: #selector(contextDidSave(_:)),
  942. name: Notification.Name.NSManagedObjectContextDidSave,
  943. object: nil
  944. )
  945. }
  946. /// determine the actions when the context has changed
  947. ///
  948. /// its done on a background thread and after that the UI gets updated on the main thread
  949. @objc private func contextDidSave(_ notification: Notification) {
  950. guard let userInfo = notification.userInfo else {
  951. return
  952. }
  953. Task { [weak self] in
  954. await self?.processUpdates(userInfo: userInfo)
  955. }
  956. }
  957. private func processUpdates(userInfo: [AnyHashable: Any]) async {
  958. var objects = Set((userInfo[NSInsertedObjectsKey] as? Set<NSManagedObject>) ?? [])
  959. objects.formUnion((userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [])
  960. objects.formUnion((userInfo[NSDeletedObjectsKey] as? Set<NSManagedObject>) ?? [])
  961. let manualGlucoseUpdates = objects.filter { $0 is GlucoseStored }
  962. let carbUpdates = objects.filter { $0 is CarbEntryStored }
  963. let pumpHistoryUpdates = objects.filter { $0 is PumpEventStored }
  964. let overrideUpdates = objects.filter { $0 is OverrideStored || $0 is OverrideRunStored }
  965. if manualGlucoseUpdates.isNotEmpty {
  966. Task.detached {
  967. await self.uploadManualGlucose()
  968. }
  969. }
  970. if carbUpdates.isNotEmpty {
  971. Task.detached {
  972. await self.uploadCarbs()
  973. }
  974. }
  975. if pumpHistoryUpdates.isNotEmpty {
  976. Task.detached {
  977. await self.uploadPumpHistory()
  978. }
  979. }
  980. if overrideUpdates.isNotEmpty {
  981. Task.detached {
  982. await self.uploadOverrides()
  983. }
  984. }
  985. }
  986. }