NightscoutConfigStateModel.swift 17 KB

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