NightscoutConfigStateModel.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. await self.nightscoutManager.uploadProfiles()
  68. }
  69. } else {
  70. debug(.nightscout, "Upload has been disabled by the user.")
  71. }
  72. }
  73. .store(in: &lifetime)
  74. }
  75. func connect() {
  76. if let CheckURL = url.last, CheckURL == "/" {
  77. let fixedURL = url.dropLast()
  78. url = String(fixedURL)
  79. }
  80. guard let url = URL(string: url), self.url.hasPrefix("https://") else {
  81. message = "Invalid URL"
  82. isValidURL = false
  83. return
  84. }
  85. connecting = true
  86. isValidURL = true
  87. message = ""
  88. provider.checkConnection(url: url, secret: secret.isEmpty ? nil : secret)
  89. .receive(on: DispatchQueue.main)
  90. .sink { completion in
  91. switch completion {
  92. case .finished: break
  93. case let .failure(error):
  94. self.message = "Error: \(error.localizedDescription)"
  95. }
  96. self.connecting = false
  97. } receiveValue: {
  98. self.message = "Connected!"
  99. self.keychain.setValue(self.url, forKey: Config.urlKey)
  100. self.keychain.setValue(self.secret, forKey: Config.secretKey)
  101. self.connecting = true
  102. self.isConnectedToNS = self.nightscoutAPI != nil
  103. }
  104. .store(in: &lifetime)
  105. }
  106. private var nightscoutAPI: NightscoutAPI? {
  107. guard let urlString = keychain.getValue(String.self, forKey: NightscoutConfig.Config.urlKey),
  108. let url = URL(string: urlString),
  109. let secret = keychain.getValue(String.self, forKey: NightscoutConfig.Config.secretKey)
  110. else {
  111. return nil
  112. }
  113. return NightscoutAPI(url: url, secret: secret)
  114. }
  115. private func getMedianTarget(
  116. lowTargetValue: Decimal,
  117. lowTargetTime: String,
  118. highTarget: [NightscoutTimevalue],
  119. units: GlucoseUnits
  120. ) -> Decimal {
  121. if let idx = highTarget.firstIndex(where: { $0.time == lowTargetTime }) {
  122. let median = (lowTargetValue + highTarget[idx].value) / 2
  123. switch units {
  124. case .mgdL:
  125. return Decimal(round(Double(median)))
  126. case .mmolL:
  127. return Decimal(round(Double(median) * 10) / 10)
  128. }
  129. }
  130. return lowTargetValue
  131. }
  132. func correctUnitParsingOffsets(_ parsedValue: Decimal) -> Decimal {
  133. Int(parsedValue) % 2 == 0 ? parsedValue : parsedValue + 1
  134. }
  135. func importSettings() async {
  136. importStatus = .running
  137. do {
  138. guard let fetchedProfile = await nightscoutManager.importSettings() else {
  139. importStatus = .failed
  140. throw NSError(
  141. domain: "ImportError",
  142. code: 1,
  143. userInfo: [NSLocalizedDescriptionKey: "Cannot find the default Nightscout Profile."]
  144. )
  145. }
  146. // determine, i.e. guesstimate, whether fetched values are mmol/L or mg/dL values
  147. let shouldConvertToMgdL = fetchedProfile.units.contains("mmol") || fetchedProfile.target_low
  148. .contains(where: { $0.value <= 39 }) || fetchedProfile.target_high.contains(where: { $0.value <= 39 })
  149. // Carb Ratios
  150. let carbratios = fetchedProfile.carbratio.map { carbratio in
  151. CarbRatioEntry(
  152. start: carbratio.time,
  153. offset: offset(carbratio.time) / 60,
  154. ratio: carbratio.value
  155. )
  156. }
  157. if carbratios.contains(where: { $0.ratio <= 0 }) {
  158. importStatus = .failed
  159. throw NSError(
  160. domain: "ImportError",
  161. code: 2,
  162. userInfo: [NSLocalizedDescriptionKey: "Invalid Carb Ratio settings in Nightscout. Import aborted."]
  163. )
  164. }
  165. let carbratiosProfile = CarbRatios(units: .grams, schedule: carbratios)
  166. // Basal Profile
  167. let pumpName = apsManager.pumpName.value
  168. let basals = fetchedProfile.basal.map { basal in
  169. BasalProfileEntry(
  170. start: basal.time,
  171. minutes: offset(basal.time) / 60,
  172. rate: basal.value
  173. )
  174. }
  175. if pumpName != "Omnipod DASH", basals.contains(where: { $0.rate <= 0 }) {
  176. importStatus = .failed
  177. throw NSError(
  178. domain: "ImportError",
  179. code: 3,
  180. userInfo: [NSLocalizedDescriptionKey: "Invalid Nightscout basal rates found. Import aborted."]
  181. )
  182. }
  183. if pumpName == "Omnipod DASH", basals.reduce(0, { $0 + $1.rate }) <= 0 {
  184. importStatus = .failed
  185. throw NSError(
  186. domain: "ImportError",
  187. code: 4,
  188. userInfo: [
  189. NSLocalizedDescriptionKey: "Invalid Nightscout basal rates found. Basal rate total cannot be 0 U/hr. Import aborted."
  190. ]
  191. )
  192. }
  193. // Sensitivities
  194. let sensitivities = fetchedProfile.sens.map { sensitivity in
  195. InsulinSensitivityEntry(
  196. sensitivity: shouldConvertToMgdL ? correctUnitParsingOffsets(sensitivity.value.asMgdL) : sensitivity
  197. .value,
  198. offset: offset(sensitivity.time) / 60,
  199. start: sensitivity.time
  200. )
  201. }
  202. if sensitivities.contains(where: { $0.sensitivity <= 0 }) {
  203. importStatus = .failed
  204. throw NSError(
  205. domain: "ImportError",
  206. code: 5,
  207. userInfo: [NSLocalizedDescriptionKey: "Invalid Nightscout insulin sensitivity profile. Import aborted."]
  208. )
  209. }
  210. let sensitivitiesProfile = InsulinSensitivities(
  211. units: .mgdL,
  212. userPreferredUnits: .mgdL,
  213. sensitivities: sensitivities
  214. )
  215. // Targets
  216. let targets = fetchedProfile.target_low.map { target in
  217. BGTargetEntry(
  218. low: shouldConvertToMgdL ? correctUnitParsingOffsets(target.value.asMgdL) : target.value,
  219. high: shouldConvertToMgdL ? correctUnitParsingOffsets(target.value.asMgdL) : target.value,
  220. start: target.time,
  221. offset: offset(target.time) / 60
  222. )
  223. }
  224. let targetsProfile = BGTargets(units: .mgdL, userPreferredUnits: .mgdL, targets: targets)
  225. // Save to storage and pump
  226. if let pump = apsManager.pumpManager {
  227. let syncValues = basals.map {
  228. RepeatingScheduleValue(startTime: TimeInterval($0.minutes * 60), value: Double($0.rate))
  229. }
  230. pump.syncBasalRateSchedule(items: syncValues) { result in
  231. switch result {
  232. case .success:
  233. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  234. self.finalizeImport(
  235. carbratiosProfile: carbratiosProfile,
  236. sensitivitiesProfile: sensitivitiesProfile,
  237. targetsProfile: targetsProfile,
  238. dia: fetchedProfile.dia
  239. )
  240. case .failure:
  241. self.importErrors.append(
  242. "Settings were imported but the basal rates could not be saved to pump (communication error)."
  243. )
  244. self.importStatus = .failed
  245. }
  246. }
  247. if importErrors.isNotEmpty, importStatus == .failed {
  248. throw NSError(
  249. domain: "ImportError",
  250. code: 6,
  251. userInfo: [
  252. NSLocalizedDescriptionKey: "Settings were imported but the basal rates could not be saved to pump (communication error)."
  253. ]
  254. )
  255. }
  256. } else {
  257. storage.save(basals, as: OpenAPS.Settings.basalProfile)
  258. finalizeImport(
  259. carbratiosProfile: carbratiosProfile,
  260. sensitivitiesProfile: sensitivitiesProfile,
  261. targetsProfile: targetsProfile,
  262. dia: fetchedProfile.dia
  263. )
  264. }
  265. } catch {
  266. DispatchQueue.main.async {
  267. self.importErrors.append(error.localizedDescription)
  268. debug(.service, "Settings import failed with error: \(error.localizedDescription)")
  269. }
  270. }
  271. }
  272. private func finalizeImport(
  273. carbratiosProfile: CarbRatios,
  274. sensitivitiesProfile: InsulinSensitivities,
  275. targetsProfile: BGTargets,
  276. dia: Decimal
  277. ) {
  278. storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  279. storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  280. storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  281. // Save DIA if different
  282. if dia != self.dia, dia >= 0 {
  283. let file = PumpSettings(insulinActionCurve: dia, maxBolus: maxBolus, maxBasal: maxBasal)
  284. storage.save(file, as: OpenAPS.Settings.settings)
  285. debug(.nightscout, "DIA setting updated to \(dia) after a NS import.")
  286. }
  287. debug(.service, "Settings imported successfully.")
  288. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  289. // stop blur
  290. self.importStatus = .finished
  291. // display next import rewview step
  292. self.isImportResultReviewPresented = true
  293. }
  294. }
  295. func offset(_ string: String) -> Int {
  296. let hours = Int(string.prefix(2)) ?? 0
  297. let minutes = Int(string.suffix(2)) ?? 0
  298. return ((hours * 60) + minutes) * 60
  299. }
  300. func backfillGlucose() async {
  301. backfilling = true
  302. let glucose = await nightscoutManager.fetchGlucose(since: Date().addingTimeInterval(-1.days.timeInterval))
  303. if glucose.isNotEmpty {
  304. await MainActor.run {
  305. self.backfilling = false
  306. }
  307. glucoseStorage.storeGlucose(glucose)
  308. Task.detached {
  309. await self.healthKitManager.uploadGlucose()
  310. }
  311. } else {
  312. await MainActor.run {
  313. self.backfilling = false
  314. debug(.nightscout, "No glucose values found or fetched to backfill.")
  315. }
  316. }
  317. }
  318. func delete() {
  319. keychain.removeObject(forKey: Config.urlKey)
  320. keychain.removeObject(forKey: Config.secretKey)
  321. url = ""
  322. secret = ""
  323. isConnectedToNS = false
  324. }
  325. func saveReviewedInsulinAction() {
  326. if !isPumpSettingUnchanged {
  327. let settings = PumpSettings(
  328. insulinActionCurve: importedInsulinActionCurve,
  329. maxBolus: pumpSettings.maxBolus,
  330. maxBasal: pumpSettings.maxBasal
  331. )
  332. provider.savePumpSettings(settings: settings)
  333. .receive(on: DispatchQueue.main)
  334. .sink { _ in
  335. let settings = self.provider.getPumpSettings()
  336. self.importedInsulinActionCurve = settings.insulinActionCurve
  337. Task.detached(priority: .low) {
  338. debug(.nightscout, "Attempting to upload DIA to Nightscout after import review")
  339. await self.nightscoutManager.uploadProfiles()
  340. }
  341. } receiveValue: {}
  342. .store(in: &lifetime)
  343. }
  344. }
  345. }
  346. }
  347. extension NightscoutConfig.StateModel: SettingsObserver {
  348. func settingsDidChange(_: FreeAPSSettings) {
  349. units = settingsManager.settings.units
  350. }
  351. }
  352. extension NightscoutConfig.StateModel {
  353. enum ImportStatus {
  354. case running
  355. case finished
  356. case failed
  357. case noPumpConnected
  358. }
  359. }