NightscoutManager.swift 41 KB

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