NightscoutConfigStateModel.swift 16 KB

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