NightscoutConfigStateModel.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import Combine
  2. import CoreData
  3. import LoopKit
  4. import SwiftDate
  5. import SwiftUI
  6. extension NightscoutConfig {
  7. final class StateModel: BaseStateModel<Provider> {
  8. @Injected() private var keychain: Keychain!
  9. @Injected() private var nightscoutManager: NightscoutManager!
  10. @Injected() private var glucoseStorage: GlucoseStorage!
  11. @Injected() private var healthKitManager: HealthKitManager!
  12. @Injected() private var cgmManager: FetchGlucoseManager!
  13. @Injected() private var storage: FileStorage!
  14. @Injected() var apsManager: APSManager!
  15. let coredataContext = CoreDataStack.shared.persistentContainer.viewContext
  16. @Published var url = ""
  17. @Published var secret = ""
  18. @Published var message = ""
  19. @Published var connecting = false
  20. @Published var backfilling = false
  21. @Published var isUploadEnabled = false // Allow uploads
  22. @Published var isDownloadEnabled = false // Allow downloads
  23. @Published var uploadGlucose = true // Upload Glucose
  24. @Published var changeUploadGlucose = true // if plugin, need to be change in CGM configuration
  25. @Published var useLocalSource = false
  26. @Published var localPort: Decimal = 0
  27. @Published var units: GlucoseUnits = .mmolL
  28. @Published var dia: Decimal = 6
  29. @Published var maxBasal: Decimal = 2
  30. @Published var maxBolus: Decimal = 10
  31. @Published var allowAnnouncements: Bool = false
  32. override func subscribe() {
  33. url = keychain.getValue(String.self, forKey: Config.urlKey) ?? ""
  34. secret = keychain.getValue(String.self, forKey: Config.secretKey) ?? ""
  35. units = settingsManager.settings.units
  36. dia = settingsManager.pumpSettings.insulinActionCurve
  37. maxBasal = settingsManager.pumpSettings.maxBasal
  38. maxBolus = settingsManager.pumpSettings.maxBolus
  39. changeUploadGlucose = (cgmManager.cgmGlucoseSourceType != CGMType.plugin)
  40. subscribeSetting(\.allowAnnouncements, on: $allowAnnouncements) { allowAnnouncements = $0 }
  41. subscribeSetting(\.isUploadEnabled, on: $isUploadEnabled) { isUploadEnabled = $0 }
  42. subscribeSetting(\.isDownloadEnabled, on: $isDownloadEnabled) { isDownloadEnabled = $0 }
  43. subscribeSetting(\.useLocalGlucoseSource, on: $useLocalSource) { useLocalSource = $0 }
  44. subscribeSetting(\.localGlucosePort, on: $localPort.map(Int.init)) { localPort = Decimal($0) }
  45. subscribeSetting(\.uploadGlucose, on: $uploadGlucose, initial: { uploadGlucose = $0 })
  46. }
  47. func connect() {
  48. guard let url = URL(string: url) else {
  49. message = "Invalid URL"
  50. return
  51. }
  52. connecting = true
  53. message = ""
  54. provider.checkConnection(url: url, secret: secret.isEmpty ? nil : secret)
  55. .receive(on: DispatchQueue.main)
  56. .sink { completion in
  57. switch completion {
  58. case .finished: break
  59. case let .failure(error):
  60. self.message = "Error: \(error.localizedDescription)"
  61. }
  62. self.connecting = false
  63. } receiveValue: {
  64. self.message = "Connected!"
  65. self.keychain.setValue(self.url, forKey: Config.urlKey)
  66. self.keychain.setValue(self.secret, forKey: Config.secretKey)
  67. }
  68. .store(in: &lifetime)
  69. }
  70. private var nightscoutAPI: NightscoutAPI? {
  71. guard let urlString = keychain.getValue(String.self, forKey: NightscoutConfig.Config.urlKey),
  72. let url = URL(string: urlString),
  73. let secret = keychain.getValue(String.self, forKey: NightscoutConfig.Config.secretKey)
  74. else {
  75. return nil
  76. }
  77. return NightscoutAPI(url: url, secret: secret)
  78. }
  79. private func getMedianTarget(
  80. lowTargetValue: Decimal,
  81. lowTargetTime: String,
  82. highTarget: [NightscoutTimevalue],
  83. units: GlucoseUnits
  84. ) -> Decimal {
  85. if let idx = highTarget.firstIndex(where: { $0.time == lowTargetTime }) {
  86. let median = (lowTargetValue + highTarget[idx].value) / 2
  87. switch units {
  88. case .mgdL:
  89. return Decimal(round(Double(median)))
  90. case .mmolL:
  91. return Decimal(round(Double(median) * 10) / 10)
  92. }
  93. }
  94. return lowTargetValue
  95. }
  96. func importSettings() {
  97. guard let nightscout = nightscoutAPI else {
  98. saveError("Can't access nightscoutAPI")
  99. return
  100. }
  101. let group = DispatchGroup()
  102. group.enter()
  103. var error = ""
  104. let path = "/api/v1/profile.json"
  105. let timeout: TimeInterval = 60
  106. var components = URLComponents()
  107. components.scheme = nightscout.url.scheme
  108. components.host = nightscout.url.host
  109. components.port = nightscout.url.port
  110. components.path = path
  111. components.queryItems = [
  112. URLQueryItem(name: "count", value: "1")
  113. ]
  114. var url = URLRequest(url: components.url!)
  115. url.allowsConstrainedNetworkAccess = false
  116. url.timeoutInterval = timeout
  117. if let secret = nightscout.secret {
  118. url.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
  119. }
  120. let task = URLSession.shared.dataTask(with: url) { data, response, error_ in
  121. if let error_ = error_ {
  122. print("Error occured: " + error_.localizedDescription)
  123. // handle error
  124. self.saveError("Error occured: " + error_.localizedDescription)
  125. error = error_.localizedDescription
  126. return
  127. }
  128. guard let httpResponse = response as? HTTPURLResponse,
  129. (200 ... 299).contains(httpResponse.statusCode)
  130. else {
  131. print("Error occured! " + error_.debugDescription)
  132. // handle error
  133. self.saveError(error_.debugDescription)
  134. return
  135. }
  136. let jsonDecoder = JSONCoding.decoder
  137. if let mimeType = httpResponse.mimeType, mimeType == "application/json",
  138. let data = data
  139. {
  140. do {
  141. let fetchedProfileStore = try jsonDecoder.decode([FetchedNightscoutProfileStore].self, from: data)
  142. let loop = fetchedProfileStore.first?.enteredBy.contains("Loop")
  143. guard let fetchedProfile: FetchedNightscoutProfile =
  144. (fetchedProfileStore.first?.store["default"] != nil) ?
  145. fetchedProfileStore.first?.store["default"] :
  146. fetchedProfileStore.first?.store["Default"]
  147. else {
  148. error = "\nCan't find the default Nightscout Profile."
  149. group.leave()
  150. return
  151. }
  152. guard fetchedProfile.units.contains(self.units.rawValue.prefix(4)) else {
  153. debug(
  154. .nightscout,
  155. "Mismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
  156. )
  157. error = "\nMismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
  158. group.leave()
  159. return
  160. }
  161. var areCRsOK = true
  162. let carbratios = fetchedProfile.carbratio
  163. .map { carbratio -> CarbRatioEntry in
  164. if carbratio.value <= 0 {
  165. error =
  166. "\nInvalid Carb Ratio settings in Nightscout.\n\nImport aborted. Please check your Nightscout Profile Carb Ratios Settings!"
  167. areCRsOK = false
  168. }
  169. return CarbRatioEntry(
  170. start: carbratio.time,
  171. offset: self.offset(carbratio.time) / 60,
  172. ratio: carbratio.value
  173. ) }
  174. let carbratiosProfile = CarbRatios(units: CarbUnit.grams, schedule: carbratios)
  175. guard areCRsOK else {
  176. group.leave()
  177. return
  178. }
  179. var areBasalsOK = true
  180. let pumpName = self.apsManager.pumpName.value
  181. let basals = fetchedProfile.basal
  182. .map { basal -> BasalProfileEntry in
  183. if pumpName != "Omnipod DASH", basal.value <= 0
  184. {
  185. error =
  186. "\nInvalid Nightcsout Basal Settings. Some or all of your basal settings are 0 U/h.\n\nImport aborted. Please check your Nightscout Profile Basal Settings before trying to import again. Import has been aborted.)"
  187. areBasalsOK = false
  188. }
  189. return BasalProfileEntry(
  190. start: basal.time,
  191. minutes: self.offset(basal.time) / 60,
  192. rate: basal.value
  193. ) }
  194. // DASH pumps can have 0U/h basal rates but don't import if total basals (24 hours) amount to 0 U.
  195. if pumpName == "Omnipod DASH", basals.map({ each in each.rate }).reduce(0, +) <= 0
  196. {
  197. error =
  198. "\nYour total Basal insulin amount to 0 U or lower in Nightscout Profile settings.\n\n Please check your Nightscout Profile Basal Settings before trying to import again. Import has been aborted.)"
  199. areBasalsOK = false
  200. }
  201. guard areBasalsOK else {
  202. group.leave()
  203. return
  204. }
  205. let sensitivities = fetchedProfile.sens.map { sensitivity -> InsulinSensitivityEntry in
  206. InsulinSensitivityEntry(
  207. sensitivity: sensitivity.value,
  208. offset: self.offset(sensitivity.time) / 60,
  209. start: sensitivity.time
  210. )
  211. }
  212. if sensitivities.filter({ $0.sensitivity <= 0 }).isNotEmpty {
  213. error =
  214. "\nInvalid Nightcsout Sensitivities Settings. \n\nImport aborted. Please check your Nightscout Profile Sensitivities Settings!"
  215. group.leave()
  216. return
  217. }
  218. let sensitivitiesProfile = InsulinSensitivities(
  219. units: self.units,
  220. userPrefferedUnits: self.units,
  221. sensitivities: sensitivities
  222. )
  223. let targets = fetchedProfile.target_low
  224. .map { target -> BGTargetEntry in
  225. let median = loop! ? self.getMedianTarget(
  226. lowTargetValue: target.value,
  227. lowTargetTime: target.time,
  228. highTarget: fetchedProfile.target_high,
  229. units: self.units
  230. ) : target.value
  231. return BGTargetEntry(
  232. low: median,
  233. high: median,
  234. start: target.time,
  235. offset: self.offset(target.time) / 60
  236. ) }
  237. let targetsProfile = BGTargets(
  238. units: self.units,
  239. userPrefferedUnits: self.units,
  240. targets: targets
  241. )
  242. // IS THERE A PUMP?
  243. guard let pump = self.apsManager.pumpManager else {
  244. self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  245. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  246. self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  247. self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  248. debug(
  249. .service,
  250. "Settings were imported but the Basals couldn't be saved to pump (No pump). Check your basal settings and tap ´Save on Pump´ to sync the new basal settings"
  251. )
  252. error =
  253. "\nSettings were imported but the Basals couldn't be saved to pump (No pump). Check your basal settings and tap ´Save on Pump´ to sync the new basal settings"
  254. group.leave()
  255. return
  256. }
  257. let syncValues = basals.map {
  258. RepeatingScheduleValue(startTime: TimeInterval($0.minutes * 60), value: Double($0.rate))
  259. }
  260. // SSAVE TO STORAGE. SAVE TO PUMP (LoopKit)
  261. pump.syncBasalRateSchedule(items: syncValues) { result in
  262. switch result {
  263. case .success:
  264. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  265. self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  266. self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  267. self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  268. debug(.service, "Settings have been imported and the Basals saved to pump!")
  269. // DIA. Save if changed.
  270. let dia = fetchedProfile.dia
  271. print("dia: " + dia.description)
  272. print("pump dia: " + self.dia.description)
  273. if dia != self.dia, dia >= 0 {
  274. let file = PumpSettings(
  275. insulinActionCurve: dia,
  276. maxBolus: self.maxBolus,
  277. maxBasal: self.maxBasal
  278. )
  279. self.storage.save(file, as: OpenAPS.Settings.settings)
  280. debug(.nightscout, "DIA setting updated to " + dia.description + " after a NS import.")
  281. }
  282. group.leave()
  283. case .failure:
  284. error =
  285. "\nSettings were imported but the Basals couldn't be saved to pump (communication error). Check your basal settings and tap ´Save on Pump´ to sync the new basal settings"
  286. debug(.service, "Basals couldn't be save to pump")
  287. group.leave()
  288. }
  289. }
  290. } catch let parsingError {
  291. print(parsingError)
  292. error = parsingError.localizedDescription
  293. group.leave()
  294. }
  295. }
  296. }
  297. task.resume()
  298. group.wait(wallTimeout: .now() + 5)
  299. group.notify(queue: .global(qos: .background)) {
  300. self.saveError(error)
  301. }
  302. }
  303. func offset(_ string: String) -> Int {
  304. let hours = Int(string.prefix(2)) ?? 0
  305. let minutes = Int(string.suffix(2)) ?? 0
  306. return ((hours * 60) + minutes) * 60
  307. }
  308. func saveError(_ string: String) {
  309. coredataContext.performAndWait {
  310. let saveToCoreData = ImportError(context: self.coredataContext)
  311. saveToCoreData.date = Date()
  312. saveToCoreData.error = string
  313. if coredataContext.hasChanges {
  314. try? coredataContext.save()
  315. }
  316. }
  317. }
  318. func backfillGlucose() {
  319. backfilling = true
  320. nightscoutManager.fetchGlucose(since: Date().addingTimeInterval(-1.days.timeInterval))
  321. .sink { [weak self] glucose in
  322. guard let self = self else { return }
  323. DispatchQueue.main.async {
  324. self.backfilling = false
  325. }
  326. guard glucose.isNotEmpty else { return }
  327. self.healthKitManager.saveIfNeeded(bloodGlucose: glucose)
  328. self.glucoseStorage.storeGlucose(glucose)
  329. }
  330. .store(in: &lifetime)
  331. }
  332. func delete() {
  333. keychain.removeObject(forKey: Config.urlKey)
  334. keychain.removeObject(forKey: Config.secretKey)
  335. url = ""
  336. secret = ""
  337. }
  338. }
  339. }