NightscoutManager.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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 determinationStorage: DeterminationStorage!
  26. @Injected() private var glucoseStorage: GlucoseStorage!
  27. @Injected() private var tempTargetsStorage: TempTargetsStorage!
  28. @Injected() private var overridesStorage: OverrideStorage!
  29. @Injected() private var carbsStorage: CarbsStorage!
  30. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  31. @Injected() private var storage: FileStorage!
  32. @Injected() private var announcementsStorage: AnnouncementsStorage!
  33. @Injected() private var settingsManager: SettingsManager!
  34. @Injected() private var broadcaster: Broadcaster!
  35. @Injected() private var reachabilityManager: ReachabilityManager!
  36. @Injected() var healthkitManager: HealthKitManager!
  37. private let processQueue = DispatchQueue(label: "BaseNetworkManager.processQueue")
  38. private var ping: TimeInterval?
  39. private var backgroundContext = CoreDataStack.shared.newTaskContext()
  40. private var lifetime = Lifetime()
  41. private var isNetworkReachable: Bool {
  42. reachabilityManager.isReachable
  43. }
  44. private var isUploadEnabled: Bool {
  45. settingsManager.settings.isUploadEnabled
  46. }
  47. private var isDownloadEnabled: Bool {
  48. settingsManager.settings.isDownloadEnabled
  49. }
  50. private var isUploadGlucoseEnabled: Bool {
  51. settingsManager.settings.uploadGlucose
  52. }
  53. private var nightscoutAPI: NightscoutAPI? {
  54. guard let urlString = keychain.getValue(String.self, forKey: NightscoutConfig.Config.urlKey),
  55. let url = URL(string: urlString),
  56. let secret = keychain.getValue(String.self, forKey: NightscoutConfig.Config.secretKey)
  57. else {
  58. return nil
  59. }
  60. return NightscoutAPI(url: url, secret: secret)
  61. }
  62. private var lastEnactedDetermination: Determination?
  63. private var lastSuggestedDetermination: Determination?
  64. private var coreDataObserver: CoreDataObserver?
  65. init(resolver: Resolver) {
  66. injectServices(resolver)
  67. subscribe()
  68. coreDataObserver = CoreDataObserver()
  69. registerHandlers()
  70. }
  71. private func subscribe() {
  72. _ = reachabilityManager.startListening(onQueue: processQueue) { status in
  73. debug(.nightscout, "Network status: \(status)")
  74. }
  75. }
  76. private func registerHandlers() {
  77. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  78. guard let self = self else { return }
  79. Task.detached {
  80. await self.uploadStatus()
  81. }
  82. }
  83. coreDataObserver?.registerHandler(for: "OverrideStored") { [weak self] in
  84. guard let self = self else { return }
  85. Task.detached {
  86. await self.uploadOverrides()
  87. }
  88. }
  89. coreDataObserver?.registerHandler(for: "OverrideRunStored") { [weak self] in
  90. guard let self = self else { return }
  91. Task.detached {
  92. await self.uploadOverrides()
  93. }
  94. }
  95. coreDataObserver?.registerHandler(for: "PumpEventStored") { [weak self] in
  96. guard let self = self else { return }
  97. Task.detached {
  98. await self.uploadPumpHistory()
  99. }
  100. }
  101. coreDataObserver?.registerHandler(for: "CarbEntryStored") { [weak self] in
  102. guard let self = self else { return }
  103. Task.detached {
  104. await self.uploadCarbs()
  105. }
  106. }
  107. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  108. guard let self = self else { return }
  109. Task.detached {
  110. await self.uploadManualGlucose()
  111. }
  112. }
  113. }
  114. func sourceInfo() -> [String: Any]? {
  115. if let ping = ping {
  116. return [GlucoseSourceKey.nightscoutPing.rawValue: ping]
  117. }
  118. return nil
  119. }
  120. var cgmURL: URL? {
  121. if let url = settingsManager.settings.cgm.appURL {
  122. return url
  123. }
  124. let useLocal = settingsManager.settings.useLocalGlucoseSource
  125. let maybeNightscout = useLocal
  126. ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
  127. : nightscoutAPI
  128. return maybeNightscout?.url
  129. }
  130. func fetchGlucose(since date: Date) async -> [BloodGlucose] {
  131. let useLocal = settingsManager.settings.useLocalGlucoseSource
  132. ping = nil
  133. if !useLocal {
  134. guard isNetworkReachable else {
  135. return []
  136. }
  137. }
  138. let maybeNightscout = useLocal
  139. ? NightscoutAPI(url: URL(string: "http://127.0.0.1:\(settingsManager.settings.localGlucosePort)")!)
  140. : nightscoutAPI
  141. guard let nightscout = maybeNightscout else {
  142. return []
  143. }
  144. let startDate = Date()
  145. do {
  146. let glucose = try await nightscout.fetchLastGlucose(sinceDate: date)
  147. if glucose.isNotEmpty {
  148. ping = Date().timeIntervalSince(startDate)
  149. }
  150. return glucose
  151. } catch {
  152. print(error.localizedDescription)
  153. return []
  154. }
  155. }
  156. // MARK: - GlucoseSource
  157. var glucoseManager: FetchGlucoseManager?
  158. var cgmManager: CGMManagerUI?
  159. func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
  160. Future { promise in
  161. Task {
  162. let glucoseData = await self.fetchGlucose(since: self.glucoseStorage.syncDate())
  163. promise(.success(glucoseData))
  164. }
  165. }
  166. .eraseToAnyPublisher()
  167. }
  168. func fetchIfNeeded() -> AnyPublisher<[BloodGlucose], Never> {
  169. fetch(nil)
  170. }
  171. func fetchCarbs() async -> [CarbsEntry] {
  172. guard let nightscout = nightscoutAPI, isNetworkReachable, isDownloadEnabled else {
  173. return []
  174. }
  175. let since = carbsStorage.syncDate()
  176. do {
  177. let carbs = try await nightscout.fetchCarbs(sinceDate: since)
  178. return carbs
  179. } catch {
  180. debug(.nightscout, "Error fetching carbs: \(error.localizedDescription)")
  181. return []
  182. }
  183. }
  184. func fetchTempTargets() async -> [TempTarget] {
  185. guard let nightscout = nightscoutAPI, isNetworkReachable, isDownloadEnabled else {
  186. return []
  187. }
  188. let since = tempTargetsStorage.syncDate()
  189. do {
  190. let tempTargets = try await nightscout.fetchTempTargets(sinceDate: since)
  191. return tempTargets
  192. } catch {
  193. debug(.nightscout, "Error fetching temp targets: \(error.localizedDescription)")
  194. return []
  195. }
  196. }
  197. func fetchAnnouncements() -> AnyPublisher<[Announcement], Never> {
  198. guard let nightscout = nightscoutAPI, isNetworkReachable, isDownloadEnabled else {
  199. return Just([]).eraseToAnyPublisher()
  200. }
  201. let since = announcementsStorage.syncDate()
  202. return nightscout.fetchAnnouncement(sinceDate: since)
  203. .replaceError(with: [])
  204. .eraseToAnyPublisher()
  205. }
  206. func deleteCarbs(withID id: String) async {
  207. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  208. // TODO: - healthkit rewrite, deletion of FPUs
  209. // healthkitManager.deleteCarbs(syncID: arg1, fpuID: arg2)
  210. do {
  211. try await nightscout.deleteCarbs(withId: id)
  212. debug(.nightscout, "Carbs deleted")
  213. } catch {
  214. debug(
  215. .nightscout,
  216. "\(DebuggingIdentifiers.failed) Failed to delete Carbs from Nightscout with error: \(error.localizedDescription)"
  217. )
  218. }
  219. }
  220. func deleteInsulin(withID id: String) async {
  221. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  222. do {
  223. try await nightscout.deleteInsulin(withId: id)
  224. debug(.nightscout, "Insulin deleted")
  225. } catch {
  226. debug(
  227. .nightscout,
  228. "\(DebuggingIdentifiers.failed) Failed to delete Insulin from Nightscout with error: \(error.localizedDescription)"
  229. )
  230. }
  231. }
  232. func deleteManualGlucose(withID id: String) async {
  233. guard let nightscout = nightscoutAPI, isUploadEnabled else { return }
  234. do {
  235. try await nightscout.deleteManualGlucose(withId: id)
  236. } catch {
  237. debug(
  238. .nightscout,
  239. "\(DebuggingIdentifiers.failed) Failed to delete Manual Glucose from Nightscout with error: \(error.localizedDescription)"
  240. )
  241. }
  242. }
  243. func uploadStatistics(dailystat: Statistics) async {
  244. let stats = NightscoutStatistics(dailystats: dailystat)
  245. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  246. return
  247. }
  248. do {
  249. try await nightscout.uploadStats(stats)
  250. debug(.nightscout, "Statistics uploaded")
  251. } catch {
  252. debug(.nightscout, error.localizedDescription)
  253. }
  254. }
  255. func uploadPreferences(_ preferences: Preferences) {
  256. let prefs = NightscoutPreferences(
  257. preferences: settingsManager.preferences
  258. )
  259. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  260. return
  261. }
  262. processQueue.async {
  263. nightscout.uploadPrefs(prefs)
  264. .sink { completion in
  265. switch completion {
  266. case .finished:
  267. debug(.nightscout, "Preferences uploaded")
  268. self.storage.save(preferences, as: OpenAPS.Nightscout.uploadedPreferences)
  269. case let .failure(error):
  270. debug(.nightscout, error.localizedDescription)
  271. }
  272. } receiveValue: {}
  273. .store(in: &self.lifetime)
  274. }
  275. }
  276. func uploadSettings(_ settings: FreeAPSSettings) {
  277. let sets = NightscoutSettings(
  278. settings: settingsManager.settings
  279. )
  280. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  281. return
  282. }
  283. processQueue.async {
  284. nightscout.uploadSettings(sets)
  285. .sink { completion in
  286. switch completion {
  287. case .finished:
  288. debug(.nightscout, "Settings uploaded")
  289. self.storage.save(settings, as: OpenAPS.Nightscout.uploadedSettings)
  290. case let .failure(error):
  291. debug(.nightscout, error.localizedDescription)
  292. }
  293. } receiveValue: {}
  294. .store(in: &self.lifetime)
  295. }
  296. }
  297. private func fetchBattery() async -> Battery {
  298. await backgroundContext.perform {
  299. do {
  300. let results = try self.backgroundContext.fetch(OpenAPS_Battery.fetch(NSPredicate.predicateFor30MinAgo))
  301. if let last = results.first {
  302. let percent: Int? = Int(last.percent)
  303. let voltage: Decimal? = last.voltage as Decimal?
  304. let status: String? = last.status
  305. let display: Bool? = last.display
  306. if let percent = percent, let voltage = voltage, let status = status, let display = display {
  307. debugPrint(
  308. "Home State Model: \(#function) \(DebuggingIdentifiers.succeeded) setup battery from core data successfully"
  309. )
  310. return Battery(
  311. percent: percent,
  312. voltage: voltage,
  313. string: BatteryState(rawValue: status) ?? BatteryState.normal,
  314. display: display
  315. )
  316. }
  317. }
  318. return Battery(percent: 100, voltage: 100, string: BatteryState.normal, display: false)
  319. } catch {
  320. debugPrint(
  321. "Home State Model: \(#function) \(DebuggingIdentifiers.failed) failed to setup battery from core data"
  322. )
  323. return Battery(percent: 100, voltage: 100, string: BatteryState.normal, display: false)
  324. }
  325. }
  326. }
  327. func uploadStatus() async {
  328. guard let nightscout = nightscoutAPI, isUploadEnabled else {
  329. debug(.nightscout, "NS API not available or upload disabled. Aborting NS Status upload.")
  330. return
  331. }
  332. // Suggested/ Enacted
  333. async let enactedDeterminationID = determinationStorage
  334. .fetchLastDeterminationObjectID(predicate: NSPredicate.enactedDeterminationsNotYetUploadedToNightscout)
  335. async let suggestedDeterminationID = determinationStorage
  336. .fetchLastDeterminationObjectID(predicate: NSPredicate.suggestedDeterminationsNotYetUploadedToNightscout)
  337. // OpenAPS Status
  338. async let fetchedBattery = fetchBattery()
  339. async let fetchedReservoir = Decimal(from: storage.retrieveRawAsync(OpenAPS.Monitor.reservoir) ?? "0")
  340. async let fetchedIOBEntry = storage.retrieveAsync(OpenAPS.Monitor.iob, as: [IOBEntry].self)
  341. async let fetchedPumpStatus = storage.retrieveAsync(OpenAPS.Monitor.status, as: PumpStatus.self)
  342. let (fetchedEnactedDetermination, fetchedSuggestedDetermination) = await (
  343. determinationStorage.getOrefDeterminationNotYetUploadedToNightscout(enactedDeterminationID),
  344. determinationStorage.getOrefDeterminationNotYetUploadedToNightscout(suggestedDeterminationID)
  345. )
  346. // Guard to ensure both determinations are not nil
  347. guard fetchedEnactedDetermination != nil || fetchedSuggestedDetermination != nil else {
  348. debug(
  349. .nightscout,
  350. "Both fetchedEnactedDetermination and fetchedSuggestedDetermination are nil. Aborting NS Status upload."
  351. )
  352. return
  353. }
  354. // Unwrap fetchedSuggestedDetermination and manipulate the timestamp field to ensure deliverAt and timestamp for a suggestion truly match!
  355. var modifiedSuggestedDetermination = fetchedSuggestedDetermination
  356. if var suggestion = fetchedSuggestedDetermination {
  357. suggestion.timestamp = suggestion.deliverAt
  358. // Check whether the last suggestion that was uploaded is the same that is fetched again when we are attempting to upload the enacted determination
  359. // Apparently we are too fast; so the flag update is not fast enough to have the predicate filter last suggestion out
  360. // If this check is truthy, set suggestion to nil so it's not uploaded again
  361. if let lastSuggested = lastSuggestedDetermination, lastSuggested.deliverAt == suggestion.deliverAt {
  362. modifiedSuggestedDetermination = nil
  363. } else {
  364. modifiedSuggestedDetermination = suggestion
  365. }
  366. }
  367. // Gather all relevant data for OpenAPS Status
  368. let iob = await fetchedIOBEntry
  369. let openapsStatus = OpenAPSStatus(
  370. iob: iob?.first,
  371. suggested: modifiedSuggestedDetermination,
  372. enacted: settingsManager.settings.closedLoop ? fetchedEnactedDetermination : nil,
  373. version: "0.7.1"
  374. )
  375. // Gather all relevant data for NS Status
  376. let battery = await fetchedBattery
  377. let reservoir = await fetchedReservoir
  378. let pumpStatus = await fetchedPumpStatus
  379. let pump = NSPumpStatus(
  380. clock: Date(),
  381. battery: battery,
  382. reservoir: reservoir != 0xDEAD_BEEF ? reservoir : nil,
  383. status: pumpStatus
  384. )
  385. let device = await UIDevice.current
  386. let uploader = await Uploader(batteryVoltage: nil, battery: Int(device.batteryLevel * 100))
  387. let status = NightscoutStatus(
  388. device: NightscoutTreatment.local,
  389. openaps: openapsStatus,
  390. pump: pump,
  391. uploader: uploader
  392. )
  393. do {
  394. try await nightscout.uploadStatus(status)
  395. debug(.nightscout, "Status uploaded")
  396. if let enacted = fetchedEnactedDetermination {
  397. await updateOrefDeterminationAsUploaded([enacted])
  398. }
  399. if let suggested = fetchedSuggestedDetermination {
  400. await updateOrefDeterminationAsUploaded([suggested])
  401. }
  402. lastEnactedDetermination = fetchedEnactedDetermination
  403. lastSuggestedDetermination = fetchedSuggestedDetermination
  404. debug(.nightscout, "NSDeviceStatus with Determination uploaded")
  405. } catch {
  406. debug(.nightscout, error.localizedDescription)
  407. }
  408. Task.detached {
  409. await self.uploadPodAge()
  410. }
  411. }
  412. private func updateOrefDeterminationAsUploaded(_ determination: [Determination]) async {
  413. await backgroundContext.perform {
  414. let ids = determination.map(\.id) as NSArray
  415. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  416. let fetchRequest: NSFetchRequest<OrefDetermination> = OrefDetermination.fetchRequest()
  417. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  418. do {
  419. let results = try self.backgroundContext.fetch(fetchRequest)
  420. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  421. for result in results {
  422. result.isUploadedToNS = true
  423. }
  424. guard self.backgroundContext.hasChanges else { return }
  425. try self.backgroundContext.save()
  426. } catch let error as NSError {
  427. debugPrint(
  428. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  429. )
  430. }
  431. }
  432. }
  433. func uploadPodAge() async {
  434. let uploadedPodAge = storage.retrieve(OpenAPS.Nightscout.uploadedPodAge, as: [NightscoutTreatment].self) ?? []
  435. if let podAge = storage.retrieve(OpenAPS.Monitor.podAge, as: Date.self),
  436. uploadedPodAge.last?.createdAt == nil || podAge != uploadedPodAge.last!.createdAt!
  437. {
  438. let siteTreatment = NightscoutTreatment(
  439. duration: nil,
  440. rawDuration: nil,
  441. rawRate: nil,
  442. absolute: nil,
  443. rate: nil,
  444. eventType: .nsSiteChange,
  445. createdAt: podAge,
  446. enteredBy: NightscoutTreatment.local,
  447. bolus: nil,
  448. insulin: nil,
  449. notes: nil,
  450. carbs: nil,
  451. fat: nil,
  452. protein: nil,
  453. targetTop: nil,
  454. targetBottom: nil
  455. )
  456. await uploadTreatments([siteTreatment], fileToSave: OpenAPS.Nightscout.uploadedPodAge)
  457. }
  458. }
  459. func uploadProfileAndSettings(_ force: Bool) {
  460. guard let sensitivities = storage.retrieve(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self) else {
  461. debug(.nightscout, "NightscoutManager uploadProfile: error loading insulinSensitivities")
  462. return
  463. }
  464. guard let settings = storage.retrieve(OpenAPS.FreeAPS.settings, as: FreeAPSSettings.self) else {
  465. debug(.nightscout, "NightscoutManager uploadProfile: error loading settings")
  466. return
  467. }
  468. guard let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) else {
  469. debug(.nightscout, "NightscoutManager uploadProfile: error loading preferences")
  470. return
  471. }
  472. guard let targets = storage.retrieve(OpenAPS.Settings.bgTargets, as: BGTargets.self) else {
  473. debug(.nightscout, "NightscoutManager uploadProfile: error loading bgTargets")
  474. return
  475. }
  476. guard let carbRatios = storage.retrieve(OpenAPS.Settings.carbRatios, as: CarbRatios.self) else {
  477. debug(.nightscout, "NightscoutManager uploadProfile: error loading carbRatios")
  478. return
  479. }
  480. guard let basalProfile = storage.retrieve(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self) else {
  481. debug(.nightscout, "NightscoutManager uploadProfile: error loading basalProfile")
  482. return
  483. }
  484. let sens = sensitivities.sensitivities.map { item -> NightscoutTimevalue in
  485. NightscoutTimevalue(
  486. time: String(item.start.prefix(5)),
  487. value: item.sensitivity,
  488. timeAsSeconds: item.offset * 60
  489. )
  490. }
  491. let target_low = targets.targets.map { item -> NightscoutTimevalue in
  492. NightscoutTimevalue(
  493. time: String(item.start.prefix(5)),
  494. value: item.low,
  495. timeAsSeconds: item.offset * 60
  496. )
  497. }
  498. let target_high = targets.targets.map { item -> NightscoutTimevalue in
  499. NightscoutTimevalue(
  500. time: String(item.start.prefix(5)),
  501. value: item.high,
  502. timeAsSeconds: item.offset * 60
  503. )
  504. }
  505. let cr = carbRatios.schedule.map { item -> NightscoutTimevalue in
  506. NightscoutTimevalue(
  507. time: String(item.start.prefix(5)),
  508. value: item.ratio,
  509. timeAsSeconds: item.offset * 60
  510. )
  511. }
  512. let basal = basalProfile.map { item -> NightscoutTimevalue in
  513. NightscoutTimevalue(
  514. time: String(item.start.prefix(5)),
  515. value: item.rate,
  516. timeAsSeconds: item.minutes * 60
  517. )
  518. }
  519. var nsUnits = ""
  520. switch settingsManager.settings.units {
  521. case .mgdL:
  522. nsUnits = "mg/dl"
  523. case .mmolL:
  524. nsUnits = "mmol"
  525. }
  526. var carbs_hr: Decimal = 0
  527. if let isf = sensitivities.sensitivities.map(\.sensitivity).first,
  528. let cr = carbRatios.schedule.map(\.ratio).first,
  529. isf > 0, cr > 0
  530. {
  531. // CarbImpact -> Carbs/hr = CI [mg/dl/5min] * 12 / ISF [mg/dl/U] * CR [g/U]
  532. carbs_hr = settingsManager.preferences.min5mCarbimpact * 12 / isf * cr
  533. if settingsManager.settings.units == .mmolL {
  534. carbs_hr = carbs_hr * GlucoseUnits.exchangeRate
  535. }
  536. // No, Decimal has no rounding function.
  537. carbs_hr = Decimal(round(Double(carbs_hr) * 10.0)) / 10
  538. }
  539. let ps = ScheduledNightscoutProfile(
  540. dia: settingsManager.pumpSettings.insulinActionCurve,
  541. carbs_hr: Int(carbs_hr),
  542. delay: 0,
  543. timezone: TimeZone.current.identifier,
  544. target_low: target_low,
  545. target_high: target_high,
  546. sens: sens,
  547. basal: basal,
  548. carbratio: cr,
  549. units: nsUnits
  550. )
  551. let defaultProfile = "default"
  552. let now = Date()
  553. let p = NightscoutProfileStore(
  554. defaultProfile: defaultProfile,
  555. startDate: now,
  556. mills: Int(now.timeIntervalSince1970) * 1000,
  557. units: nsUnits,
  558. enteredBy: NightscoutTreatment.local,
  559. store: [defaultProfile: ps]
  560. )
  561. guard let nightscout = nightscoutAPI, isNetworkReachable, isUploadEnabled else {
  562. return
  563. }
  564. // UPLOAD PREFERNCES WHEN CHANGED
  565. if let uploadedPreferences = storage.retrieve(OpenAPS.Nightscout.uploadedPreferences, as: Preferences.self),
  566. uploadedPreferences.rawJSON.sorted() == preferences.rawJSON.sorted(), !force
  567. {
  568. NSLog("NightscoutManager Preferences, preferences unchanged")
  569. } else { uploadPreferences(preferences) }
  570. // UPLOAD FreeAPS Settings WHEN CHANGED
  571. if let uploadedSettings = storage.retrieve(OpenAPS.Nightscout.uploadedSettings, as: FreeAPSSettings.self),
  572. uploadedSettings.rawJSON.sorted() == settings.rawJSON.sorted(), !force
  573. {
  574. NSLog("NightscoutManager Settings, settings unchanged")
  575. } else { uploadSettings(settings) }
  576. // UPLOAD Profiles WHEN CHANGED
  577. if let uploadedProfile = storage.retrieve(OpenAPS.Nightscout.uploadedProfile, as: NightscoutProfileStore.self),
  578. (uploadedProfile.store["default"]?.rawJSON ?? "").sorted() == ps.rawJSON.sorted(), !force
  579. {
  580. NSLog("NightscoutManager uploadProfile, no profile change")
  581. } else {
  582. processQueue.async {
  583. nightscout.uploadProfile(p)
  584. .sink { completion in
  585. switch completion {
  586. case .finished:
  587. self.storage.save(p, as: OpenAPS.Nightscout.uploadedProfile)
  588. debug(.nightscout, "Profile uploaded")
  589. case let .failure(error):
  590. debug(.nightscout, error.localizedDescription)
  591. }
  592. } receiveValue: {}
  593. .store(in: &self.lifetime)
  594. }
  595. }
  596. }
  597. func uploadGlucose() async {
  598. await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToNightscout())
  599. await uploadTreatments(
  600. glucoseStorage.getCGMStateNotYetUploadedToNightscout(),
  601. fileToSave: OpenAPS.Nightscout.uploadedCGMState
  602. )
  603. }
  604. func uploadManualGlucose() async {
  605. await uploadManualGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToNightscout())
  606. }
  607. private func uploadPumpHistory() async {
  608. await uploadTreatments(
  609. pumpHistoryStorage.getPumpHistoryNotYetUploadedToNightscout(),
  610. fileToSave: OpenAPS.Nightscout.uploadedPumphistory
  611. )
  612. }
  613. private func uploadCarbs() async {
  614. await uploadCarbs(carbsStorage.getCarbsNotYetUploadedToNightscout())
  615. await uploadCarbs(carbsStorage.getFPUsNotYetUploadedToNightscout())
  616. }
  617. private func uploadOverrides() async {
  618. await uploadOverrides(overridesStorage.getOverridesNotYetUploadedToNightscout())
  619. await uploadOverrideRuns(overridesStorage.getOverrideRunsNotYetUploadedToNightscout())
  620. }
  621. private func uploadTempTargets() async {
  622. await uploadTreatments(
  623. tempTargetsStorage.nightscoutTreatmentsNotUploaded(),
  624. fileToSave: OpenAPS.Nightscout.uploadedTempTargets
  625. )
  626. }
  627. private func uploadGlucose(_ glucose: [BloodGlucose]) async {
  628. guard !glucose.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled, isUploadGlucoseEnabled else {
  629. return
  630. }
  631. do {
  632. // Upload in Batches of 100
  633. for chunk in glucose.chunks(ofCount: 100) {
  634. try await nightscout.uploadGlucose(Array(chunk))
  635. }
  636. // If successful, update the isUploadedToNS property of the GlucoseStored objects
  637. await updateGlucoseAsUploaded(glucose)
  638. debug(.nightscout, "Glucose uploaded")
  639. } catch {
  640. debug(.nightscout, "Upload of glucose failed: \(error.localizedDescription)")
  641. }
  642. }
  643. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  644. await backgroundContext.perform {
  645. let ids = glucose.map(\.id) as NSArray
  646. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  647. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  648. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  649. do {
  650. let results = try self.backgroundContext.fetch(fetchRequest)
  651. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  652. for result in results {
  653. result.isUploadedToNS = true
  654. }
  655. guard self.backgroundContext.hasChanges else { return }
  656. try self.backgroundContext.save()
  657. } catch let error as NSError {
  658. debugPrint(
  659. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  660. )
  661. }
  662. }
  663. }
  664. private func uploadTreatments(_ treatments: [NightscoutTreatment], fileToSave _: String) async {
  665. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  666. return
  667. }
  668. do {
  669. for chunk in treatments.chunks(ofCount: 100) {
  670. try await nightscout.uploadTreatments(Array(chunk))
  671. }
  672. // If successful, update the isUploadedToNS property of the PumpEventStored objects
  673. await updateTreatmentsAsUploaded(treatments)
  674. debug(.nightscout, "Treatments uploaded")
  675. } catch {
  676. debug(.nightscout, error.localizedDescription)
  677. }
  678. }
  679. private func updateTreatmentsAsUploaded(_ treatments: [NightscoutTreatment]) async {
  680. await backgroundContext.perform {
  681. let ids = treatments.map(\.id) as NSArray
  682. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  683. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  684. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  685. do {
  686. let results = try self.backgroundContext.fetch(fetchRequest)
  687. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  688. for result in results {
  689. result.isUploadedToNS = true
  690. }
  691. guard self.backgroundContext.hasChanges else { return }
  692. try self.backgroundContext.save()
  693. } catch let error as NSError {
  694. debugPrint(
  695. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  696. )
  697. }
  698. }
  699. }
  700. private func uploadManualGlucose(_ treatments: [NightscoutTreatment]) async {
  701. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  702. return
  703. }
  704. do {
  705. for chunk in treatments.chunks(ofCount: 100) {
  706. try await nightscout.uploadTreatments(Array(chunk))
  707. }
  708. // If successful, update the isUploadedToNS property of the GlucoseStored objects
  709. await updateManualGlucoseAsUploaded(treatments)
  710. debug(.nightscout, "Treatments uploaded")
  711. } catch {
  712. debug(.nightscout, error.localizedDescription)
  713. }
  714. }
  715. private func updateManualGlucoseAsUploaded(_ treatments: [NightscoutTreatment]) async {
  716. await backgroundContext.perform {
  717. let ids = treatments.map(\.id) as NSArray
  718. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  719. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  720. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  721. do {
  722. let results = try self.backgroundContext.fetch(fetchRequest)
  723. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  724. for result in results {
  725. result.isUploadedToNS = true
  726. }
  727. guard self.backgroundContext.hasChanges else { return }
  728. try self.backgroundContext.save()
  729. } catch let error as NSError {
  730. debugPrint(
  731. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  732. )
  733. }
  734. }
  735. }
  736. private func uploadCarbs(_ treatments: [NightscoutTreatment]) async {
  737. guard !treatments.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  738. return
  739. }
  740. do {
  741. for chunk in treatments.chunks(ofCount: 100) {
  742. try await nightscout.uploadTreatments(Array(chunk))
  743. }
  744. // If successful, update the isUploadedToNS property of the CarbEntryStored objects
  745. await updateCarbsAsUploaded(treatments)
  746. debug(.nightscout, "Treatments uploaded")
  747. } catch {
  748. debug(.nightscout, error.localizedDescription)
  749. }
  750. }
  751. private func updateCarbsAsUploaded(_ treatments: [NightscoutTreatment]) async {
  752. await backgroundContext.perform {
  753. let ids = treatments.map(\.id) as NSArray
  754. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  755. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  756. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  757. do {
  758. let results = try self.backgroundContext.fetch(fetchRequest)
  759. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  760. for result in results {
  761. result.isUploadedToNS = true
  762. }
  763. guard self.backgroundContext.hasChanges else { return }
  764. try self.backgroundContext.save()
  765. } catch let error as NSError {
  766. debugPrint(
  767. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  768. )
  769. }
  770. }
  771. }
  772. private func uploadOverrides(_ overrides: [NightscoutExercise]) async {
  773. guard !overrides.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  774. return
  775. }
  776. do {
  777. for chunk in overrides.chunks(ofCount: 100) {
  778. try await nightscout.uploadOverrides(Array(chunk))
  779. }
  780. // If successful, update the isUploadedToNS property of the OverrideStored objects
  781. await updateOverridesAsUploaded(overrides)
  782. debug(.nightscout, "Overrides uploaded")
  783. } catch {
  784. debug(.nightscout, error.localizedDescription)
  785. }
  786. }
  787. private func updateOverridesAsUploaded(_ overrides: [NightscoutExercise]) async {
  788. await backgroundContext.perform {
  789. let ids = overrides.map(\.id) as NSArray
  790. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  791. let fetchRequest: NSFetchRequest<OverrideStored> = OverrideStored.fetchRequest()
  792. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  793. do {
  794. let results = try self.backgroundContext.fetch(fetchRequest)
  795. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  796. for result in results {
  797. result.isUploadedToNS = true
  798. }
  799. guard self.backgroundContext.hasChanges else { return }
  800. try self.backgroundContext.save()
  801. } catch let error as NSError {
  802. debugPrint(
  803. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  804. )
  805. }
  806. }
  807. }
  808. private func uploadOverrideRuns(_ overrideRuns: [NightscoutExercise]) async {
  809. guard !overrideRuns.isEmpty, let nightscout = nightscoutAPI, isUploadEnabled else {
  810. return
  811. }
  812. do {
  813. for chunk in overrideRuns.chunks(ofCount: 100) {
  814. try await nightscout.uploadOverrides(Array(chunk))
  815. }
  816. // If successful, update the isUploadedToNS property of the OverrideRunStored objects
  817. await updateOverrideRunsAsUploaded(overrideRuns)
  818. debug(.nightscout, "Overrides uploaded")
  819. } catch {
  820. debug(.nightscout, error.localizedDescription)
  821. }
  822. }
  823. private func updateOverrideRunsAsUploaded(_ overrideRuns: [NightscoutExercise]) async {
  824. await backgroundContext.perform {
  825. let ids = overrideRuns.map(\.id) as NSArray
  826. // print("\(DebuggingIdentifiers.inProgress) ids: \(ids)")
  827. let fetchRequest: NSFetchRequest<OverrideRunStored> = OverrideRunStored.fetchRequest()
  828. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  829. do {
  830. let results = try self.backgroundContext.fetch(fetchRequest)
  831. // print("\(DebuggingIdentifiers.inProgress) results: \(results)")
  832. for result in results {
  833. result.isUploadedToNS = true
  834. }
  835. guard self.backgroundContext.hasChanges else { return }
  836. try self.backgroundContext.save()
  837. } catch let error as NSError {
  838. debugPrint(
  839. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToNS: \(error.userInfo)"
  840. )
  841. }
  842. }
  843. }
  844. }
  845. extension Array {
  846. func chunks(ofCount count: Int) -> [[Element]] {
  847. stride(from: 0, to: self.count, by: count).map {
  848. Array(self[$0 ..< Swift.min($0 + count, self.count)])
  849. }
  850. }
  851. }