NightscoutConfigStateModel.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import Combine
  2. import CoreData
  3. import G7SensorKit
  4. import LoopKit
  5. import SwiftDate
  6. import SwiftUI
  7. extension NightscoutConfig {
  8. final class StateModel: BaseStateModel<Provider> {
  9. @Injected() private var keychain: Keychain!
  10. @Injected() private var nightscoutManager: NightscoutManager!
  11. @Injected() private var glucoseStorage: GlucoseStorage!
  12. @Injected() private var healthKitManager: HealthKitManager!
  13. @Injected() private var cgmManager: FetchGlucoseManager!
  14. @Injected() private var storage: FileStorage!
  15. @Injected() var apsManager: APSManager!
  16. let coredataContext = CoreDataStack.shared.newTaskContext()
  17. @Published var url = ""
  18. @Published var secret = ""
  19. @Published var message = ""
  20. @Published var isValidURL: Bool = false
  21. @Published var connecting = false
  22. @Published var backfilling = false
  23. @Published var isUploadEnabled = false // Allow uploads
  24. @Published var isDownloadEnabled = false // Allow downloads
  25. @Published var uploadGlucose = true // Upload Glucose
  26. @Published var changeUploadGlucose = true // if plugin, need to be change in CGM configuration
  27. @Published var useLocalSource = false
  28. @Published var localPort: Decimal = 0
  29. @Published var units: GlucoseUnits = .mgdL
  30. @Published var dia: Decimal = 6
  31. @Published var maxBasal: Decimal = 2
  32. @Published var maxBolus: Decimal = 10
  33. @Published var isConnectedToNS: Bool = false
  34. @Published var isImportResultReviewPresented: Bool = false
  35. @Published var importErrors: [String] = []
  36. @Published var importStatus: ImportStatus = .finished
  37. @Published var importedInsulinActionCurve: Decimal = 6
  38. var pumpSettings: PumpSettings {
  39. provider.getPumpSettings()
  40. }
  41. var isPumpSettingUnchanged: Bool {
  42. pumpSettings.insulinActionCurve == importedInsulinActionCurve
  43. }
  44. override func subscribe() {
  45. url = keychain.getValue(String.self, forKey: Config.urlKey) ?? ""
  46. secret = keychain.getValue(String.self, forKey: Config.secretKey) ?? ""
  47. units = settingsManager.settings.units
  48. dia = settingsManager.pumpSettings.insulinActionCurve
  49. maxBasal = settingsManager.pumpSettings.maxBasal
  50. maxBolus = settingsManager.pumpSettings.maxBolus
  51. changeUploadGlucose = (cgmManager.cgmGlucoseSourceType != CGMType.plugin)
  52. subscribeSetting(\.isUploadEnabled, on: $isUploadEnabled) { isUploadEnabled = $0 }
  53. subscribeSetting(\.isDownloadEnabled, on: $isDownloadEnabled) { isDownloadEnabled = $0 }
  54. subscribeSetting(\.useLocalGlucoseSource, on: $useLocalSource) { useLocalSource = $0 }
  55. subscribeSetting(\.localGlucosePort, on: $localPort.map(Int.init)) { localPort = Decimal($0) }
  56. subscribeSetting(\.uploadGlucose, on: $uploadGlucose, initial: { uploadGlucose = $0 })
  57. importedInsulinActionCurve = pumpSettings.insulinActionCurve
  58. isConnectedToNS = nightscoutAPI != nil
  59. $isUploadEnabled
  60. .dropFirst()
  61. .removeDuplicates()
  62. .sink { [weak self] enabled in
  63. guard let self = self else { return }
  64. if enabled {
  65. debug(.nightscout, "Upload has been enabled by the user.")
  66. Task {
  67. do {
  68. try await self.nightscoutManager.uploadProfiles()
  69. } catch {
  70. debug(
  71. .default,
  72. "\(DebuggingIdentifiers.failed) failed to upload profiles: \(error.localizedDescription)"
  73. )
  74. }
  75. }
  76. } else {
  77. debug(.nightscout, "Upload has been disabled by the user.")
  78. }
  79. }
  80. .store(in: &lifetime)
  81. }
  82. func connect() {
  83. if let CheckURL = url.last, CheckURL == "/" {
  84. let fixedURL = url.dropLast()
  85. url = String(fixedURL)
  86. }
  87. guard let url = URL(string: url), self.url.hasPrefix("https://") else {
  88. message = "Invalid URL"
  89. isValidURL = false
  90. return
  91. }
  92. connecting = true
  93. isValidURL = true
  94. message = ""
  95. provider.checkConnection(url: url, secret: secret.isEmpty ? nil : secret)
  96. .receive(on: DispatchQueue.main)
  97. .sink { completion in
  98. switch completion {
  99. case .finished: break
  100. case let .failure(error):
  101. self.message = "Error: \(error.localizedDescription)"
  102. }
  103. self.connecting = false
  104. } receiveValue: {
  105. self.message = "Connected!"
  106. self.keychain.setValue(self.url, forKey: Config.urlKey)
  107. self.keychain.setValue(self.secret, forKey: Config.secretKey)
  108. self.connecting = true
  109. self.isConnectedToNS = self.nightscoutAPI != nil
  110. }
  111. .store(in: &lifetime)
  112. }
  113. private var nightscoutAPI: NightscoutAPI? {
  114. guard let urlString = keychain.getValue(String.self, forKey: NightscoutConfig.Config.urlKey),
  115. let url = URL(string: urlString),
  116. let secret = keychain.getValue(String.self, forKey: NightscoutConfig.Config.secretKey)
  117. else {
  118. return nil
  119. }
  120. return NightscoutAPI(url: url, secret: secret)
  121. }
  122. private func getMedianTarget(
  123. lowTargetValue: Decimal,
  124. lowTargetTime: String,
  125. highTarget: [NightscoutTimevalue],
  126. units: GlucoseUnits
  127. ) -> Decimal {
  128. if let idx = highTarget.firstIndex(where: { $0.time == lowTargetTime }) {
  129. let median = (lowTargetValue + highTarget[idx].value) / 2
  130. switch units {
  131. case .mgdL:
  132. return Decimal(round(Double(median)))
  133. case .mmolL:
  134. return Decimal(round(Double(median) * 10) / 10)
  135. }
  136. }
  137. return lowTargetValue
  138. }
  139. func correctUnitParsingOffsets(_ parsedValue: Decimal) -> Decimal {
  140. Int(parsedValue) % 2 == 0 ? parsedValue : parsedValue + 1
  141. }
  142. func importSettings() async {
  143. importStatus = .running
  144. do {
  145. guard let fetchedProfile = await nightscoutManager.importSettings() else {
  146. await MainActor.run {
  147. importStatus = .failed
  148. }
  149. throw NSError(
  150. domain: "ImportError",
  151. code: 1,
  152. userInfo: [NSLocalizedDescriptionKey: "Cannot find the default Nightscout Profile."]
  153. )
  154. }
  155. // determine, i.e. guesstimate, whether fetched values are mmol/L or mg/dL values
  156. let shouldConvertToMgdL = fetchedProfile.units.contains("mmol") || fetchedProfile.target_low
  157. .contains(where: { $0.value <= 39 }) || fetchedProfile.target_high.contains(where: { $0.value <= 39 })
  158. // Carb Ratios
  159. let carbratios = fetchedProfile.carbratio.map { carbratio in
  160. CarbRatioEntry(
  161. start: carbratio.time,
  162. offset: offset(carbratio.time) / 60,
  163. ratio: carbratio.value
  164. )
  165. }
  166. if carbratios.contains(where: { $0.ratio <= 0 }) {
  167. await MainActor.run {
  168. importStatus = .failed
  169. }
  170. throw NSError(
  171. domain: "ImportError",
  172. code: 2,
  173. userInfo: [NSLocalizedDescriptionKey: "Invalid Carb Ratio settings in Nightscout. Import aborted."]
  174. )
  175. }
  176. let carbratiosProfile = CarbRatios(units: .grams, schedule: carbratios)
  177. // Basal Profile
  178. let pumpName = apsManager.pumpName.value
  179. let basals = fetchedProfile.basal.map { basal in
  180. BasalProfileEntry(
  181. start: basal.time,
  182. minutes: offset(basal.time) / 60,
  183. rate: basal.value
  184. )
  185. }
  186. if pumpName != "Omnipod DASH", basals.contains(where: { $0.rate <= 0 }) {
  187. await MainActor.run {
  188. importStatus = .failed
  189. }
  190. throw NSError(
  191. domain: "ImportError",
  192. code: 3,
  193. userInfo: [NSLocalizedDescriptionKey: "Invalid Nightscout basal rates found. Import aborted."]
  194. )
  195. }
  196. if pumpName == "Omnipod DASH", basals.reduce(0, { $0 + $1.rate }) <= 0 {
  197. await MainActor.run {
  198. importStatus = .failed
  199. }
  200. throw NSError(
  201. domain: "ImportError",
  202. code: 4,
  203. userInfo: [
  204. NSLocalizedDescriptionKey: "Invalid Nightscout basal rates found. Basal rate total cannot be 0 U/hr. Import aborted."
  205. ]
  206. )
  207. }
  208. // Sensitivities
  209. let sensitivities = fetchedProfile.sens.map { sensitivity in
  210. InsulinSensitivityEntry(
  211. sensitivity: shouldConvertToMgdL ? correctUnitParsingOffsets(sensitivity.value.asMgdL) : sensitivity
  212. .value,
  213. offset: offset(sensitivity.time) / 60,
  214. start: sensitivity.time
  215. )
  216. }
  217. if sensitivities.contains(where: { $0.sensitivity <= 0 }) {
  218. await MainActor.run {
  219. importStatus = .failed
  220. }
  221. throw NSError(
  222. domain: "ImportError",
  223. code: 5,
  224. userInfo: [NSLocalizedDescriptionKey: "Invalid Nightscout insulin sensitivity profile. Import aborted."]
  225. )
  226. }
  227. let sensitivitiesProfile = InsulinSensitivities(
  228. units: .mgdL,
  229. userPreferredUnits: .mgdL,
  230. sensitivities: sensitivities
  231. )
  232. // Targets
  233. let targets = fetchedProfile.target_low.map { target in
  234. BGTargetEntry(
  235. low: shouldConvertToMgdL ? correctUnitParsingOffsets(target.value.asMgdL) : target.value,
  236. high: shouldConvertToMgdL ? correctUnitParsingOffsets(target.value.asMgdL) : target.value,
  237. start: target.time,
  238. offset: offset(target.time) / 60
  239. )
  240. }
  241. let targetsProfile = BGTargets(units: .mgdL, userPreferredUnits: .mgdL, targets: targets)
  242. // Save to storage and pump
  243. if let pump = apsManager.pumpManager {
  244. let syncValues = basals.map {
  245. RepeatingScheduleValue(startTime: TimeInterval($0.minutes * 60), value: Double($0.rate))
  246. }
  247. await withCheckedContinuation { continuation in
  248. pump.syncBasalRateSchedule(items: syncValues) { [weak self] result in
  249. guard let self else {
  250. continuation.resume()
  251. return
  252. }
  253. switch result {
  254. case .success:
  255. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  256. self.finalizeImport(
  257. carbratiosProfile: carbratiosProfile,
  258. sensitivitiesProfile: sensitivitiesProfile,
  259. targetsProfile: targetsProfile,
  260. dia: fetchedProfile.dia
  261. )
  262. case .failure:
  263. Task { @MainActor in
  264. self.importErrors.append(
  265. "Settings were imported but the basal rates could not be saved to pump (communication error)."
  266. )
  267. self.importStatus = .failed
  268. }
  269. }
  270. continuation.resume()
  271. }
  272. }
  273. if await MainActor.run(body: { importErrors.isNotEmpty && importStatus == .failed }) {
  274. throw NSError(
  275. domain: "ImportError",
  276. code: 6,
  277. userInfo: [
  278. NSLocalizedDescriptionKey: "Settings were imported but the basal rates could not be saved to pump (communication error)."
  279. ]
  280. )
  281. }
  282. } else {
  283. storage.save(basals, as: OpenAPS.Settings.basalProfile)
  284. finalizeImport(
  285. carbratiosProfile: carbratiosProfile,
  286. sensitivitiesProfile: sensitivitiesProfile,
  287. targetsProfile: targetsProfile,
  288. dia: fetchedProfile.dia
  289. )
  290. }
  291. } catch {
  292. await MainActor.run {
  293. self.importErrors.append(error.localizedDescription)
  294. debug(.service, "Settings import failed with error: \(error.localizedDescription)")
  295. }
  296. }
  297. }
  298. private func finalizeImport(
  299. carbratiosProfile: CarbRatios,
  300. sensitivitiesProfile: InsulinSensitivities,
  301. targetsProfile: BGTargets,
  302. dia: Decimal
  303. ) {
  304. storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  305. storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  306. storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  307. // Save DIA if different
  308. if dia != self.dia, dia >= 0 {
  309. let file = PumpSettings(insulinActionCurve: dia, maxBolus: maxBolus, maxBasal: maxBasal)
  310. storage.save(file, as: OpenAPS.Settings.settings)
  311. debug(.nightscout, "DIA setting updated to \(dia) after a NS import.")
  312. }
  313. debug(.service, "Settings imported successfully.")
  314. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  315. // stop blur
  316. self.importStatus = .finished
  317. // display next import rewview step
  318. self.isImportResultReviewPresented = true
  319. }
  320. }
  321. func offset(_ string: String) -> Int {
  322. let hours = Int(string.prefix(2)) ?? 0
  323. let minutes = Int(string.suffix(2)) ?? 0
  324. return ((hours * 60) + minutes) * 60
  325. }
  326. func backfillGlucose() async {
  327. backfilling = true
  328. let glucose = await nightscoutManager.fetchGlucose(since: Date().addingTimeInterval(-1.days.timeInterval))
  329. if glucose.isNotEmpty {
  330. do {
  331. try await glucoseStorage.storeGlucose(glucose)
  332. Task.detached {
  333. await self.healthKitManager.uploadGlucose()
  334. }
  335. } catch let error as CoreDataError {
  336. debug(.nightscout, "Core Data error while storing backfilled glucose: \(error.localizedDescription)")
  337. message = "Error: \(error.localizedDescription)"
  338. } catch {
  339. debug(.nightscout, "Unexpected error while storing backfilled glucose: \(error.localizedDescription)")
  340. message = "Error: \(error.localizedDescription)"
  341. }
  342. } else {
  343. debug(.nightscout, "No glucose values found or fetched to backfill.")
  344. }
  345. await MainActor.run {
  346. self.backfilling = false
  347. }
  348. }
  349. func delete() {
  350. keychain.removeObject(forKey: Config.urlKey)
  351. keychain.removeObject(forKey: Config.secretKey)
  352. url = ""
  353. secret = ""
  354. isConnectedToNS = false
  355. }
  356. func saveReviewedInsulinAction() {
  357. if !isPumpSettingUnchanged {
  358. let settings = PumpSettings(
  359. insulinActionCurve: importedInsulinActionCurve,
  360. maxBolus: pumpSettings.maxBolus,
  361. maxBasal: pumpSettings.maxBasal
  362. )
  363. provider.savePumpSettings(settings: settings)
  364. .receive(on: DispatchQueue.main)
  365. .sink { _ in
  366. let settings = self.provider.getPumpSettings()
  367. self.importedInsulinActionCurve = settings.insulinActionCurve
  368. Task.detached(priority: .low) {
  369. do {
  370. debug(.nightscout, "Attempting to upload DIA to Nightscout after import review")
  371. try await self.nightscoutManager.uploadProfiles()
  372. } catch {
  373. debug(
  374. .default,
  375. "\(DebuggingIdentifiers.failed) failed to upload DIA to Nightscout: \(error.localizedDescription)"
  376. )
  377. }
  378. }
  379. } receiveValue: {}
  380. .store(in: &lifetime)
  381. }
  382. }
  383. }
  384. }
  385. extension NightscoutConfig.StateModel: SettingsObserver {
  386. func settingsDidChange(_: TrioSettings) {
  387. units = settingsManager.settings.units
  388. }
  389. }
  390. extension NightscoutConfig.StateModel {
  391. enum ImportStatus {
  392. case running
  393. case finished
  394. case failed
  395. case noPumpConnected
  396. }
  397. }