NightscoutManager.swift 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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() -> AnyPublisher<[CarbsEntry], Never>
  10. func fetchTempTargets() -> AnyPublisher<[TempTarget], Never>
  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()
  16. func uploadGlucose() async
  17. func uploadManualGlucose() async
  18. func uploadStatistics(dailystat: Statistics)
  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() -> AnyPublisher<[CarbsEntry], Never> {
  129. guard let nightscout = nightscoutAPI, isNetworkReachable else {
  130. return Just([]).eraseToAnyPublisher()
  131. }
  132. let since = carbsStorage.syncDate()
  133. return nightscout.fetchCarbs(sinceDate: since)
  134. .replaceError(with: [])
  135. .eraseToAnyPublisher()
  136. }
  137. func fetchTempTargets() -> AnyPublisher<[TempTarget], Never> {
  138. guard let nightscout = nightscoutAPI, isNetworkReachable else {
  139. return Just([]).eraseToAnyPublisher()
  140. }
  141. let since = tempTargetsStorage.syncDate()
  142. return nightscout.fetchTempTargets(sinceDate: since)
  143. .replaceError(with: [])
  144. .eraseToAnyPublisher()
  145. }
  146. func fetchAnnouncements() -> AnyPublisher<[Announcement], Never> {
  147. guard let nightscout = nightscoutAPI, isNetworkReachable else {
  148. return Just([]).eraseToAnyPublisher()
  149. }
  150. let since = announcementsStorage.syncDate()
  151. return nightscout.fetchAnnouncement(sinceDate: since)
  152. .replaceError(with: [])
  153. .eraseToAnyPublisher()
  154. }
  155. func deleteCarbs(withID id: String) async {
  156. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  157. // TODO: - healthkit rewrite, deletion of FPUs
  158. // healthkitManager.deleteCarbs(syncID: arg1, fpuID: arg2)
  159. do {
  160. try await nightscout.deleteCarbs(withId: id)
  161. debug(.nightscout, "Carbs deleted")
  162. } catch {
  163. debug(
  164. .nightscout,
  165. "\(DebuggingIdentifiers.failed) Failed to delete Carbs from Nightscout with error: \(error.localizedDescription)"
  166. )
  167. }
  168. }
  169. func deleteInsulin(withID id: String) async {
  170. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  171. do {
  172. try await nightscout.deleteInsulin(withId: id)
  173. debug(.nightscout, "Insulin deleted")
  174. } catch {
  175. debug(
  176. .nightscout,
  177. "\(DebuggingIdentifiers.failed) Failed to delete Insulin from Nightscout with error: \(error.localizedDescription)"
  178. )
  179. }
  180. }
  181. func deleteManualGlucose(withID id: String) async {
  182. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  183. do {
  184. try await nightscout.deleteManualGlucose(withId: id)
  185. } catch {
  186. debug(
  187. .nightscout,
  188. "\(DebuggingIdentifiers.failed) Failed to delete Manual Glucose from Nightscout with error: \(error.localizedDescription)"
  189. )
  190. }
  191. }
  192. func uploadStatistics(dailystat: Statistics) {
  193. let stats = NightscoutStatistics(
  194. dailystats: dailystat
  195. )
  196. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  197. return
  198. }
  199. processQueue.async {
  200. nightscout.uploadStats(stats)
  201. .sink { completion in
  202. switch completion {
  203. case .finished:
  204. debug(.nightscout, "Statistics uploaded")
  205. case let .failure(error):
  206. debug(.nightscout, error.localizedDescription)
  207. }
  208. } receiveValue: {}
  209. .store(in: &self.lifetime)
  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. private func fetchDeterminations() {
  285. let fetchRequest: NSFetchRequest<OrefDetermination> = OrefDetermination.fetchRequest()
  286. fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \OrefDetermination.deliverAt, ascending: false)]
  287. fetchRequest.predicate = NSPredicate.predicateFor30MinAgoForDetermination
  288. fetchRequest.fetchLimit = 2
  289. context.performAndWait {
  290. do {
  291. lastTwoDeterminations = try context.fetch(fetchRequest)
  292. debugPrint(
  293. "Home State Model: \(#function) \(DebuggingIdentifiers.succeeded) fetched determinations from core data"
  294. )
  295. } catch {
  296. debugPrint(
  297. "Home State Model: \(#function) \(DebuggingIdentifiers.failed) failed to fetch determinations from core data"
  298. )
  299. }
  300. }
  301. }
  302. func uploadStatus() {
  303. let iob = storage.retrieve(OpenAPS.Monitor.iob, as: [IOBEntry].self)
  304. let penultimateDetermination = lastTwoDeterminations?.last
  305. let lastDetermination = lastTwoDeterminations?.first
  306. var suggested: Determination?
  307. var enacted: Determination?
  308. if let lastDetermination = lastDetermination, let penultimateDetermination = penultimateDetermination {
  309. if lastDetermination.enacted, penultimateDetermination.enacted {
  310. suggested = Determination(
  311. reason: lastDetermination.reason ?? "",
  312. units: lastDetermination.smbToDeliver?.decimalValue,
  313. insulinReq: lastDetermination.insulinReq?.decimalValue,
  314. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  315. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  316. rate: lastDetermination.rate?.decimalValue,
  317. duration: lastDetermination.duration?.decimalValue,
  318. iob: lastDetermination.iob?.decimalValue,
  319. cob: Decimal(lastDetermination.cob),
  320. predictions: nil,
  321. deliverAt: lastDetermination.deliverAt ?? Date(),
  322. carbsReq: Decimal(lastDetermination.carbsRequired),
  323. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  324. bg: lastDetermination.glucose?.decimalValue,
  325. reservoir: lastDetermination.reservoir?.decimalValue,
  326. isf: lastDetermination.insulinSensitivity?.decimalValue,
  327. timestamp: lastDetermination.timestamp,
  328. recieved: lastDetermination.received,
  329. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  330. insulin: Insulin(
  331. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  332. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  333. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  334. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  335. ),
  336. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  337. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  338. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  339. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  340. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  341. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  342. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  343. )
  344. enacted = Determination(
  345. reason: lastDetermination.reason ?? "",
  346. units: lastDetermination.smbToDeliver?.decimalValue,
  347. insulinReq: lastDetermination.insulinReq?.decimalValue,
  348. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  349. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  350. rate: lastDetermination.rate?.decimalValue,
  351. duration: lastDetermination.duration?.decimalValue,
  352. iob: lastDetermination.iob?.decimalValue,
  353. cob: Decimal(lastDetermination.cob),
  354. predictions: nil,
  355. deliverAt: lastDetermination.deliverAt ?? Date(),
  356. carbsReq: Decimal(lastDetermination.carbsRequired),
  357. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  358. bg: lastDetermination.glucose?.decimalValue,
  359. reservoir: lastDetermination.reservoir?.decimalValue,
  360. isf: lastDetermination.insulinSensitivity?.decimalValue,
  361. timestamp: lastDetermination.timestamp,
  362. recieved: lastDetermination.received,
  363. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  364. insulin: Insulin(
  365. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  366. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  367. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  368. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  369. ),
  370. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  371. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  372. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  373. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  374. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  375. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  376. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  377. )
  378. } else if !lastDetermination.enacted, penultimateDetermination.enacted {
  379. suggested = Determination(
  380. reason: lastDetermination.reason ?? "",
  381. units: lastDetermination.smbToDeliver?.decimalValue,
  382. insulinReq: lastDetermination.insulinReq?.decimalValue,
  383. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  384. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  385. rate: lastDetermination.rate?.decimalValue,
  386. duration: lastDetermination.duration?.decimalValue,
  387. iob: lastDetermination.iob?.decimalValue,
  388. cob: Decimal(lastDetermination.cob),
  389. predictions: nil,
  390. deliverAt: lastDetermination.deliverAt ?? Date(),
  391. carbsReq: Decimal(lastDetermination.carbsRequired),
  392. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  393. bg: lastDetermination.glucose?.decimalValue,
  394. reservoir: lastDetermination.reservoir?.decimalValue,
  395. isf: lastDetermination.insulinSensitivity?.decimalValue,
  396. timestamp: lastDetermination.timestamp,
  397. recieved: lastDetermination.received,
  398. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  399. insulin: Insulin(
  400. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  401. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  402. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  403. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  404. ),
  405. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  406. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  407. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  408. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  409. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  410. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  411. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  412. )
  413. enacted = Determination(
  414. reason: penultimateDetermination.reason ?? "",
  415. units: penultimateDetermination.smbToDeliver?.decimalValue,
  416. insulinReq: penultimateDetermination.insulinReq?.decimalValue,
  417. eventualBG: Int(truncating: penultimateDetermination.eventualBG ?? 0),
  418. sensitivityRatio: penultimateDetermination.sensitivityRatio?.decimalValue,
  419. rate: penultimateDetermination.rate?.decimalValue,
  420. duration: lastDetermination.duration?.decimalValue,
  421. iob: penultimateDetermination.iob?.decimalValue,
  422. cob: Decimal(penultimateDetermination.cob),
  423. predictions: nil,
  424. deliverAt: penultimateDetermination.deliverAt ?? Date(),
  425. carbsReq: Decimal(penultimateDetermination.carbsRequired),
  426. temp: TempType(rawValue: penultimateDetermination.temp ?? ""),
  427. bg: penultimateDetermination.glucose?.decimalValue,
  428. reservoir: penultimateDetermination.reservoir?.decimalValue,
  429. isf: penultimateDetermination.insulinSensitivity?.decimalValue,
  430. timestamp: penultimateDetermination.timestamp,
  431. recieved: penultimateDetermination.received,
  432. tdd: penultimateDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  433. insulin: Insulin(
  434. TDD: penultimateDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  435. bolus: penultimateDetermination.bolus?.decimalValue ?? Decimal(0),
  436. temp_basal: penultimateDetermination.tempBasal?.decimalValue ?? Decimal(0),
  437. scheduled_basal: penultimateDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  438. ),
  439. current_target: penultimateDetermination.currentTarget?.decimalValue ?? Decimal(0),
  440. insulinForManualBolus: penultimateDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  441. manualBolusErrorString: penultimateDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  442. minDelta: penultimateDetermination.minDelta?.decimalValue ?? Decimal(0),
  443. expectedDelta: penultimateDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  444. minGuardBG: nil,
  445. minPredBG: nil,
  446. threshold: penultimateDetermination.threshold?.decimalValue ?? Decimal(0),
  447. carbRatio: penultimateDetermination.carbRatio?.decimalValue ?? Decimal(0)
  448. )
  449. } else if !lastDetermination.enacted, !penultimateDetermination.enacted {
  450. suggested = Determination(
  451. reason: lastDetermination.reason ?? "",
  452. units: lastDetermination.smbToDeliver?.decimalValue,
  453. insulinReq: lastDetermination.insulinReq?.decimalValue,
  454. eventualBG: Int(truncating: lastDetermination.eventualBG ?? 0),
  455. sensitivityRatio: lastDetermination.sensitivityRatio?.decimalValue,
  456. rate: lastDetermination.rate?.decimalValue,
  457. duration: lastDetermination.duration?.decimalValue,
  458. iob: lastDetermination.iob?.decimalValue,
  459. cob: Decimal(lastDetermination.cob),
  460. predictions: nil,
  461. deliverAt: lastDetermination.deliverAt ?? Date(),
  462. carbsReq: Decimal(lastDetermination.carbsRequired),
  463. temp: TempType(rawValue: lastDetermination.temp ?? ""),
  464. bg: lastDetermination.glucose?.decimalValue,
  465. reservoir: lastDetermination.reservoir?.decimalValue,
  466. isf: lastDetermination.insulinSensitivity?.decimalValue,
  467. timestamp: lastDetermination.timestamp,
  468. recieved: lastDetermination.received,
  469. tdd: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  470. insulin: Insulin(
  471. TDD: lastDetermination.totalDailyDose?.decimalValue ?? Decimal(0),
  472. bolus: lastDetermination.bolus?.decimalValue ?? Decimal(0),
  473. temp_basal: lastDetermination.tempBasal?.decimalValue ?? Decimal(0),
  474. scheduled_basal: lastDetermination.scheduledBasal?.decimalValue ?? Decimal(0)
  475. ),
  476. current_target: lastDetermination.currentTarget?.decimalValue ?? Decimal(0),
  477. insulinForManualBolus: lastDetermination.insulinForManualBolus?.decimalValue ?? Decimal(0),
  478. manualBolusErrorString: lastDetermination.manualBolusErrorString?.decimalValue ?? Decimal(0),
  479. minDelta: lastDetermination.minDelta?.decimalValue ?? Decimal(0),
  480. expectedDelta: lastDetermination.expectedDelta?.decimalValue ?? Decimal(0),
  481. minGuardBG: nil, minPredBG: nil, threshold: lastDetermination.threshold?.decimalValue ?? Decimal(0),
  482. carbRatio: lastDetermination.carbRatio?.decimalValue ?? Decimal(0)
  483. )
  484. }
  485. }
  486. let loopIsClosed = settingsManager.settings.closedLoop
  487. var openapsStatus: OpenAPSStatus
  488. // Only upload suggested in Open Loop Mode. Only upload enacted in Closed Loop Mode.
  489. if loopIsClosed {
  490. openapsStatus = OpenAPSStatus(
  491. iob: iob?.first,
  492. suggested: nil,
  493. enacted: enacted,
  494. version: "0.7.1"
  495. )
  496. } else {
  497. openapsStatus = OpenAPSStatus(
  498. iob: iob?.first,
  499. suggested: suggested,
  500. enacted: nil,
  501. version: "0.7.1"
  502. )
  503. }
  504. let battery = fetchBattery()
  505. var reservoir = Decimal(from: storage.retrieveRaw(OpenAPS.Monitor.reservoir) ?? "0")
  506. if reservoir == 0xDEAD_BEEF {
  507. reservoir = nil
  508. }
  509. let pumpStatus = storage.retrieve(OpenAPS.Monitor.status, as: PumpStatus.self)
  510. let pump = NSPumpStatus(clock: Date(), battery: battery, reservoir: reservoir, status: pumpStatus)
  511. let device = UIDevice.current
  512. let uploader = Uploader(batteryVoltage: nil, battery: Int(device.batteryLevel * 100))
  513. var status: NightscoutStatus
  514. status = NightscoutStatus(
  515. device: NightscoutTreatment.local,
  516. openaps: openapsStatus,
  517. pump: pump,
  518. uploader: uploader
  519. )
  520. storage.save(status, as: OpenAPS.Upload.nsStatus)
  521. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  522. return
  523. }
  524. processQueue.async {
  525. nightscout.uploadStatus(status)
  526. .sink { completion in
  527. switch completion {
  528. case .finished:
  529. debug(.nightscout, "Status uploaded")
  530. case let .failure(error):
  531. debug(.nightscout, error.localizedDescription)
  532. }
  533. } receiveValue: {}
  534. .store(in: &self.lifetime)
  535. }
  536. Task {
  537. await uploadPodAge()
  538. }
  539. }
  540. func uploadPodAge() async {
  541. let uploadedPodAge = storage.retrieve(OpenAPS.Nightscout.uploadedPodAge, as: [NightscoutTreatment].self) ?? []
  542. if let podAge = storage.retrieve(OpenAPS.Monitor.podAge, as: Date.self),
  543. uploadedPodAge.last?.createdAt == nil || podAge != uploadedPodAge.last!.createdAt!
  544. {
  545. let siteTreatment = NightscoutTreatment(
  546. duration: nil,
  547. rawDuration: nil,
  548. rawRate: nil,
  549. absolute: nil,
  550. rate: nil,
  551. eventType: .nsSiteChange,
  552. createdAt: podAge,
  553. enteredBy: NightscoutTreatment.local,
  554. bolus: nil,
  555. insulin: nil,
  556. notes: nil,
  557. carbs: nil,
  558. fat: nil,
  559. protein: nil,
  560. targetTop: nil,
  561. targetBottom: nil
  562. )
  563. await uploadTreatments([siteTreatment], fileToSave: OpenAPS.Nightscout.uploadedPodAge)
  564. }
  565. }
  566. func uploadProfileAndSettings(_ force: Bool) {
  567. guard let sensitivities = storage.retrieve(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self) else {
  568. debug(.nightscout, "NightscoutManager uploadProfile: error loading insulinSensitivities")
  569. return
  570. }
  571. guard let settings = storage.retrieve(OpenAPS.FreeAPS.settings, as: FreeAPSSettings.self) else {
  572. debug(.nightscout, "NightscoutManager uploadProfile: error loading settings")
  573. return
  574. }
  575. guard let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) else {
  576. debug(.nightscout, "NightscoutManager uploadProfile: error loading preferences")
  577. return
  578. }
  579. guard let targets = storage.retrieve(OpenAPS.Settings.bgTargets, as: BGTargets.self) else {
  580. debug(.nightscout, "NightscoutManager uploadProfile: error loading bgTargets")
  581. return
  582. }
  583. guard let carbRatios = storage.retrieve(OpenAPS.Settings.carbRatios, as: CarbRatios.self) else {
  584. debug(.nightscout, "NightscoutManager uploadProfile: error loading carbRatios")
  585. return
  586. }
  587. guard let basalProfile = storage.retrieve(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self) else {
  588. debug(.nightscout, "NightscoutManager uploadProfile: error loading basalProfile")
  589. return
  590. }
  591. let sens = sensitivities.sensitivities.map { item -> NightscoutTimevalue in
  592. NightscoutTimevalue(
  593. time: String(item.start.prefix(5)),
  594. value: item.sensitivity,
  595. timeAsSeconds: item.offset * 60
  596. )
  597. }
  598. let target_low = targets.targets.map { item -> NightscoutTimevalue in
  599. NightscoutTimevalue(
  600. time: String(item.start.prefix(5)),
  601. value: item.low,
  602. timeAsSeconds: item.offset * 60
  603. )
  604. }
  605. let target_high = targets.targets.map { item -> NightscoutTimevalue in
  606. NightscoutTimevalue(
  607. time: String(item.start.prefix(5)),
  608. value: item.high,
  609. timeAsSeconds: item.offset * 60
  610. )
  611. }
  612. let cr = carbRatios.schedule.map { item -> NightscoutTimevalue in
  613. NightscoutTimevalue(
  614. time: String(item.start.prefix(5)),
  615. value: item.ratio,
  616. timeAsSeconds: item.offset * 60
  617. )
  618. }
  619. let basal = basalProfile.map { item -> NightscoutTimevalue in
  620. NightscoutTimevalue(
  621. time: String(item.start.prefix(5)),
  622. value: item.rate,
  623. timeAsSeconds: item.minutes * 60
  624. )
  625. }
  626. var nsUnits = ""
  627. switch settingsManager.settings.units {
  628. case .mgdL:
  629. nsUnits = "mg/dl"
  630. case .mmolL:
  631. nsUnits = "mmol"
  632. }
  633. var carbs_hr: Decimal = 0
  634. if let isf = sensitivities.sensitivities.map(\.sensitivity).first,
  635. let cr = carbRatios.schedule.map(\.ratio).first,
  636. isf > 0, cr > 0
  637. {
  638. // CarbImpact -> Carbs/hr = CI [mg/dl/5min] * 12 / ISF [mg/dl/U] * CR [g/U]
  639. carbs_hr = settingsManager.preferences.min5mCarbimpact * 12 / isf * cr
  640. if settingsManager.settings.units == .mmolL {
  641. carbs_hr = carbs_hr * GlucoseUnits.exchangeRate
  642. }
  643. // No, Decimal has no rounding function.
  644. carbs_hr = Decimal(round(Double(carbs_hr) * 10.0)) / 10
  645. }
  646. let ps = ScheduledNightscoutProfile(
  647. dia: settingsManager.pumpSettings.insulinActionCurve,
  648. carbs_hr: Int(carbs_hr),
  649. delay: 0,
  650. timezone: TimeZone.current.identifier,
  651. target_low: target_low,
  652. target_high: target_high,
  653. sens: sens,
  654. basal: basal,
  655. carbratio: cr,
  656. units: nsUnits
  657. )
  658. let defaultProfile = "default"
  659. let now = Date()
  660. let p = NightscoutProfileStore(
  661. defaultProfile: defaultProfile,
  662. startDate: now,
  663. mills: Int(now.timeIntervalSince1970) * 1000,
  664. units: nsUnits,
  665. enteredBy: NightscoutTreatment.local,
  666. store: [defaultProfile: ps]
  667. )
  668. guard let nightscout = nightscoutAPI, isNetworkReachable, isUploadEnabled else {
  669. return
  670. }
  671. // UPLOAD PREFERNCES WHEN CHANGED
  672. if let uploadedPreferences = storage.retrieve(OpenAPS.Nightscout.uploadedPreferences, as: Preferences.self),
  673. uploadedPreferences.rawJSON.sorted() == preferences.rawJSON.sorted(), !force
  674. {
  675. NSLog("NightscoutManager Preferences, preferences unchanged")
  676. } else { uploadPreferences(preferences) }
  677. // UPLOAD FreeAPS Settings WHEN CHANGED
  678. if let uploadedSettings = storage.retrieve(OpenAPS.Nightscout.uploadedSettings, as: FreeAPSSettings.self),
  679. uploadedSettings.rawJSON.sorted() == settings.rawJSON.sorted(), !force
  680. {
  681. NSLog("NightscoutManager Settings, settings unchanged")
  682. } else { uploadSettings(settings) }
  683. // UPLOAD Profiles WHEN CHANGED
  684. if let uploadedProfile = storage.retrieve(OpenAPS.Nightscout.uploadedProfile, as: NightscoutProfileStore.self),
  685. (uploadedProfile.store["default"]?.rawJSON ?? "").sorted() == ps.rawJSON.sorted(), !force
  686. {
  687. NSLog("NightscoutManager uploadProfile, no profile change")
  688. } else {
  689. processQueue.async {
  690. nightscout.uploadProfile(p)
  691. .sink { completion in
  692. switch completion {
  693. case .finished:
  694. self.storage.save(p, as: OpenAPS.Nightscout.uploadedProfile)
  695. debug(.nightscout, "Profile uploaded")
  696. case let .failure(error):
  697. debug(.nightscout, error.localizedDescription)
  698. }
  699. } receiveValue: {}
  700. .store(in: &self.lifetime)
  701. }
  702. }
  703. }
  704. func uploadGlucose() async {
  705. await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToNightscout())
  706. await uploadTreatments(
  707. glucoseStorage.getCGMStateNotYetUploadedToNightscout(),
  708. fileToSave: OpenAPS.Nightscout.uploadedCGMState
  709. )
  710. }
  711. func uploadManualGlucose() async {
  712. await uploadManualGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToNightscout())
  713. }
  714. private func uploadPumpHistory() async {
  715. await uploadTreatments(
  716. pumpHistoryStorage.getPumpHistoryNotYetUploadedToNightscout(),
  717. fileToSave: OpenAPS.Nightscout.uploadedPumphistory
  718. )
  719. }
  720. private func uploadCarbs() async {
  721. await uploadCarbs(carbsStorage.getCarbsNotYetUploadedToNightscout())
  722. await uploadCarbs(carbsStorage.getFPUsNotYetUploadedToNightscout())
  723. }
  724. private func uploadOverrides() async {
  725. await uploadOverrides(overridesStorage.getOverridesNotYetUploadedToNightscout())
  726. await uploadOverrideRuns(overridesStorage.getOverrideRunsNotYetUploadedToNightscout())
  727. }
  728. private func uploadTempTargets() async {
  729. await uploadTreatments(
  730. tempTargetsStorage.nightscoutTreatmentsNotUploaded(),
  731. fileToSave: OpenAPS.Nightscout.uploadedTempTargets
  732. )
  733. }
  734. private func uploadGlucose(_ glucose: [BloodGlucose]) async {
  735. guard !glucose.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled, isUploadGlucoseEnabled else {
  736. return
  737. }
  738. do {
  739. // Upload in Batches of 100
  740. for chunk in glucose.chunks(ofCount: 100) {
  741. try await nightscout.uploadGlucose(Array(chunk))
  742. }
  743. // If successful, update the isUploadedToNS property of the GlucoseStored objects
  744. await updateGlucoseAsUploaded(glucose)
  745. debug(.nightscout, "Glucose uploaded")
  746. } catch {
  747. debug(.nightscout, "Upload of glucose failed: \(error.localizedDescription)")
  748. }
  749. }
  750. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  751. await backgroundContext.perform {
  752. let ids = glucose.map(\.id) as NSArray
  753. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  754. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  755. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  756. do {
  757. let results = try self.backgroundContext.fetch(fetchRequest)
  758. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  759. for result in results {
  760. result.isUploadedToNS = true
  761. }
  762. guard self.backgroundContext.hasChanges else { return }
  763. try self.backgroundContext.save()
  764. } catch let error as NSError {
  765. debugPrint(
  766. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  767. )
  768. }
  769. }
  770. }
  771. private func uploadTreatments(_ treatments: [NightscoutTreatment], fileToSave _: String) async {
  772. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  773. return
  774. }
  775. do {
  776. for chunk in treatments.chunks(ofCount: 100) {
  777. try await nightscout.uploadTreatments(Array(chunk))
  778. }
  779. // If successful, update the isUploadedToNS property of the PumpEventStored objects
  780. await updateTreatmentsAsUploaded(treatments)
  781. debug(.nightscout, "Treatments uploaded")
  782. } catch {
  783. debug(.nightscout, error.localizedDescription)
  784. }
  785. }
  786. private func updateTreatmentsAsUploaded(_ treatments: [NightscoutTreatment]) async {
  787. await backgroundContext.perform {
  788. let ids = treatments.map(\.id) as NSArray
  789. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  790. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  791. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  792. do {
  793. let results = try self.backgroundContext.fetch(fetchRequest)
  794. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  795. for result in results {
  796. result.isUploadedToNS = true
  797. }
  798. guard self.backgroundContext.hasChanges else { return }
  799. try self.backgroundContext.save()
  800. } catch let error as NSError {
  801. debugPrint(
  802. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  803. )
  804. }
  805. }
  806. }
  807. private func uploadManualGlucose(_ treatments: [NightscoutTreatment]) async {
  808. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  809. return
  810. }
  811. do {
  812. for chunk in treatments.chunks(ofCount: 100) {
  813. try await nightscout.uploadTreatments(Array(chunk))
  814. }
  815. // If successful, update the isUploadedToNS property of the GlucoseStored objects
  816. await updateManualGlucoseAsUploaded(treatments)
  817. debug(.nightscout, "Treatments uploaded")
  818. } catch {
  819. debug(.nightscout, error.localizedDescription)
  820. }
  821. }
  822. private func updateManualGlucoseAsUploaded(_ treatments: [NightscoutTreatment]) async {
  823. await backgroundContext.perform {
  824. let ids = treatments.map(\.id) as NSArray
  825. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  826. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  827. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  828. do {
  829. let results = try self.backgroundContext.fetch(fetchRequest)
  830. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  831. for result in results {
  832. result.isUploadedToNS = true
  833. }
  834. guard self.backgroundContext.hasChanges else { return }
  835. try self.backgroundContext.save()
  836. } catch let error as NSError {
  837. debugPrint(
  838. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  839. )
  840. }
  841. }
  842. }
  843. private func uploadCarbs(_ treatments: [NightscoutTreatment]) async {
  844. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  845. return
  846. }
  847. do {
  848. for chunk in treatments.chunks(ofCount: 100) {
  849. try await nightscout.uploadTreatments(Array(chunk))
  850. }
  851. // If successful, update the isUploadedToNS property of the CarbEntryStored objects
  852. await updateCarbsAsUploaded(treatments)
  853. debug(.nightscout, "Treatments uploaded")
  854. } catch {
  855. debug(.nightscout, error.localizedDescription)
  856. }
  857. }
  858. private func updateCarbsAsUploaded(_ treatments: [NightscoutTreatment]) async {
  859. await backgroundContext.perform {
  860. let ids = treatments.map(\.id) as NSArray
  861. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  862. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  863. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  864. do {
  865. let results = try self.backgroundContext.fetch(fetchRequest)
  866. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  867. for result in results {
  868. result.isUploadedToNS = true
  869. }
  870. guard self.backgroundContext.hasChanges else { return }
  871. try self.backgroundContext.save()
  872. } catch let error as NSError {
  873. debugPrint(
  874. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  875. )
  876. }
  877. }
  878. }
  879. private func uploadOverrides(_ overrides: [NightscoutExercise]) async {
  880. guard !overrides.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  881. return
  882. }
  883. do {
  884. for chunk in overrides.chunks(ofCount: 100) {
  885. try await nightscout.uploadOverrides(Array(chunk))
  886. }
  887. // If successful, update the isUploadedToNS property of the OverrideStored objects
  888. await updateOverridesAsUploaded(overrides)
  889. debug(.nightscout, "Overrides uploaded")
  890. } catch {
  891. debug(.nightscout, error.localizedDescription)
  892. }
  893. }
  894. private func updateOverridesAsUploaded(_ overrides: [NightscoutExercise]) async {
  895. await backgroundContext.perform {
  896. let ids = overrides.map(\.id) as NSArray
  897. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  898. let fetchRequest: NSFetchRequest<OverrideStored> = OverrideStored.fetchRequest()
  899. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  900. do {
  901. let results = try self.backgroundContext.fetch(fetchRequest)
  902. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  903. for result in results {
  904. result.isUploadedToNS = true
  905. }
  906. guard self.backgroundContext.hasChanges else { return }
  907. try self.backgroundContext.save()
  908. } catch let error as NSError {
  909. debugPrint(
  910. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  911. )
  912. }
  913. }
  914. }
  915. private func uploadOverrideRuns(_ overrideRuns: [NightscoutExercise]) async {
  916. guard !overrideRuns.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  917. return
  918. }
  919. do {
  920. for chunk in overrideRuns.chunks(ofCount: 100) {
  921. try await nightscout.uploadOverrides(Array(chunk))
  922. }
  923. // If successful, update the isUploadedToNS property of the OverrideRunStored objects
  924. await updateOverrideRunsAsUploaded(overrideRuns)
  925. debug(.nightscout, "Overrides uploaded")
  926. } catch {
  927. debug(.nightscout, error.localizedDescription)
  928. }
  929. }
  930. private func updateOverrideRunsAsUploaded(_ overrideRuns: [NightscoutExercise]) async {
  931. await backgroundContext.perform {
  932. let ids = overrideRuns.map(\.id) as NSArray
  933. print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  934. let fetchRequest: NSFetchRequest<OverrideRunStored> = OverrideRunStored.fetchRequest()
  935. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  936. do {
  937. let results = try self.backgroundContext.fetch(fetchRequest)
  938. print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  939. for result in results {
  940. result.isUploadedToNS = true
  941. }
  942. guard self.backgroundContext.hasChanges else { return }
  943. try self.backgroundContext.save()
  944. } catch let error as NSError {
  945. debugPrint(
  946. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  947. )
  948. }
  949. }
  950. }
  951. }
  952. extension Array {
  953. func chunks(ofCount count: Int) -> [[Element]] {
  954. stride(from: 0, to: self.count, by: count).map {
  955. Array(self[$0 ..< Swift.min($0 + count, self.count)])
  956. }
  957. }
  958. }
  959. extension BaseNightscoutManager {
  960. /// listens for the notifications sent when the managedObjectContext has saved!
  961. func setupNotification() {
  962. Foundation.NotificationCenter.default.addObserver(
  963. self,
  964. selector: #selector(contextDidSave(_:)),
  965. name: Notification.Name.NSManagedObjectContextDidSave,
  966. object: nil
  967. )
  968. }
  969. /// determine the actions when the context has changed
  970. ///
  971. /// its done on a background thread and after that the UI gets updated on the main thread
  972. @objc private func contextDidSave(_ notification: Notification) {
  973. guard let userInfo = notification.userInfo else {
  974. return
  975. }
  976. Task { [weak self] in
  977. await self?.processUpdates(userInfo: userInfo)
  978. }
  979. }
  980. private func processUpdates(userInfo: [AnyHashable: Any]) async {
  981. var objects = Set((userInfo[NSInsertedObjectsKey] as? Set<NSManagedObject>) ?? [])
  982. objects.formUnion((userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [])
  983. objects.formUnion((userInfo[NSDeletedObjectsKey] as? Set<NSManagedObject>) ?? [])
  984. let manualGlucoseUpdates = objects.filter { $0 is GlucoseStored }
  985. let carbUpdates = objects.filter { $0 is CarbEntryStored }
  986. let pumpHistoryUpdates = objects.filter { $0 is PumpEventStored }
  987. let overrideUpdates = objects.filter { $0 is OverrideStored || $0 is OverrideRunStored }
  988. if manualGlucoseUpdates.isNotEmpty {
  989. Task.detached {
  990. await self.uploadManualGlucose()
  991. }
  992. }
  993. if carbUpdates.isNotEmpty {
  994. Task.detached {
  995. await self.uploadCarbs()
  996. }
  997. }
  998. if pumpHistoryUpdates.isNotEmpty {
  999. Task.detached {
  1000. await self.uploadPumpHistory()
  1001. }
  1002. }
  1003. if overrideUpdates.isNotEmpty {
  1004. Task.detached {
  1005. await self.uploadOverrides()
  1006. }
  1007. }
  1008. }
  1009. }