NightscoutConfigStateModel.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 = fetchedProfileStore.first?
  144. .store[loop! ? "Default" : "default"]
  145. else {
  146. error = "\nCan't find the default Nightscout Profile."
  147. group.leave()
  148. return
  149. }
  150. guard fetchedProfile.units.contains(self.units.rawValue.prefix(4)) else {
  151. debug(
  152. .nightscout,
  153. "Mismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
  154. )
  155. error = "\nMismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
  156. group.leave()
  157. return
  158. }
  159. var areCRsOK = true
  160. let carbratios = fetchedProfile.carbratio
  161. .map { carbratio -> CarbRatioEntry in
  162. if carbratio.value <= 0 {
  163. error =
  164. "\nInvalid Carb Ratio settings in Nightscout.\n\nImport aborted. Please check your Nightscout Profile Carb Ratios Settings!"
  165. areCRsOK = false
  166. }
  167. return CarbRatioEntry(
  168. start: carbratio.time,
  169. offset: self.offset(carbratio.time) / 60,
  170. ratio: carbratio.value
  171. ) }
  172. let carbratiosProfile = CarbRatios(units: CarbUnit.grams, schedule: carbratios)
  173. guard areCRsOK else {
  174. group.leave()
  175. return
  176. }
  177. var areBasalsOK = true
  178. let pumpName = self.apsManager.pumpName.value
  179. let basals = fetchedProfile.basal
  180. .map { basal -> BasalProfileEntry in
  181. if pumpName != "Omnipod DASH", basal.value <= 0
  182. {
  183. error =
  184. "\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.)"
  185. areBasalsOK = false
  186. }
  187. return BasalProfileEntry(
  188. start: basal.time,
  189. minutes: self.offset(basal.time) / 60,
  190. rate: basal.value
  191. ) }
  192. // DASH pumps can have 0U/h basal rates but don't import if total basals (24 hours) amount to 0 U.
  193. if pumpName == "Omnipod DASH", basals.map({ each in each.rate }).reduce(0, +) <= 0
  194. {
  195. error =
  196. "\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.)"
  197. areBasalsOK = false
  198. }
  199. guard areBasalsOK else {
  200. group.leave()
  201. return
  202. }
  203. let sensitivities = fetchedProfile.sens.map { sensitivity -> InsulinSensitivityEntry in
  204. InsulinSensitivityEntry(
  205. sensitivity: sensitivity.value,
  206. offset: self.offset(sensitivity.time) / 60,
  207. start: sensitivity.time
  208. )
  209. }
  210. if sensitivities.filter({ $0.sensitivity <= 0 }).isNotEmpty {
  211. error =
  212. "\nInvalid Nightcsout Sensitivities Settings. \n\nImport aborted. Please check your Nightscout Profile Sensitivities Settings!"
  213. group.leave()
  214. return
  215. }
  216. let sensitivitiesProfile = InsulinSensitivities(
  217. units: self.units,
  218. userPrefferedUnits: self.units,
  219. sensitivities: sensitivities
  220. )
  221. let targets = fetchedProfile.target_low
  222. .map { target -> BGTargetEntry in
  223. let median = loop! ? self.getMedianTarget(
  224. lowTargetValue: target.value,
  225. lowTargetTime: target.time,
  226. highTarget: fetchedProfile.target_high,
  227. units: self.units
  228. ) : target.value
  229. return BGTargetEntry(
  230. low: median,
  231. high: median,
  232. start: target.time,
  233. offset: self.offset(target.time) / 60
  234. ) }
  235. let targetsProfile = BGTargets(
  236. units: self.units,
  237. userPrefferedUnits: self.units,
  238. targets: targets
  239. )
  240. // IS THERE A PUMP?
  241. guard let pump = self.apsManager.pumpManager else {
  242. self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  243. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  244. self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  245. self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  246. debug(
  247. .service,
  248. "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"
  249. )
  250. error =
  251. "\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"
  252. group.leave()
  253. return
  254. }
  255. let syncValues = basals.map {
  256. RepeatingScheduleValue(startTime: TimeInterval($0.minutes * 60), value: Double($0.rate))
  257. }
  258. // SSAVE TO STORAGE. SAVE TO PUMP (LoopKit)
  259. pump.syncBasalRateSchedule(items: syncValues) { result in
  260. switch result {
  261. case .success:
  262. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  263. self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  264. self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  265. self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  266. debug(.service, "Settings have been imported and the Basals saved to pump!")
  267. // DIA. Save if changed.
  268. let dia = fetchedProfile.dia
  269. print("dia: " + dia.description)
  270. print("pump dia: " + self.dia.description)
  271. if dia != self.dia, dia >= 0 {
  272. let file = PumpSettings(
  273. insulinActionCurve: dia,
  274. maxBolus: self.maxBolus,
  275. maxBasal: self.maxBasal
  276. )
  277. self.storage.save(file, as: OpenAPS.Settings.settings)
  278. debug(.nightscout, "DIA setting updated to " + dia.description + " after a NS import.")
  279. }
  280. group.leave()
  281. case .failure:
  282. error =
  283. "\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"
  284. debug(.service, "Basals couldn't be save to pump")
  285. group.leave()
  286. }
  287. }
  288. } catch let parsingError {
  289. print(parsingError)
  290. error = parsingError.localizedDescription
  291. group.leave()
  292. }
  293. }
  294. }
  295. task.resume()
  296. group.wait(wallTimeout: .now() + 5)
  297. group.notify(queue: .global(qos: .background)) {
  298. self.saveError(error)
  299. }
  300. }
  301. func offset(_ string: String) -> Int {
  302. let hours = Int(string.prefix(2)) ?? 0
  303. let minutes = Int(string.suffix(2)) ?? 0
  304. return ((hours * 60) + minutes) * 60
  305. }
  306. func saveError(_ string: String) {
  307. coredataContext.performAndWait {
  308. let saveToCoreData = ImportError(context: self.coredataContext)
  309. saveToCoreData.date = Date()
  310. saveToCoreData.error = string
  311. if coredataContext.hasChanges {
  312. try? coredataContext.save()
  313. }
  314. }
  315. }
  316. func backfillGlucose() {
  317. backfilling = true
  318. nightscoutManager.fetchGlucose(since: Date().addingTimeInterval(-1.days.timeInterval))
  319. .sink { [weak self] glucose in
  320. guard let self = self else { return }
  321. DispatchQueue.main.async {
  322. self.backfilling = false
  323. }
  324. guard glucose.isNotEmpty else { return }
  325. self.healthKitManager.saveIfNeeded(bloodGlucose: glucose)
  326. self.glucoseStorage.storeGlucose(glucose)
  327. }
  328. .store(in: &lifetime)
  329. }
  330. func delete() {
  331. keychain.removeObject(forKey: Config.urlKey)
  332. keychain.removeObject(forKey: Config.secretKey)
  333. url = ""
  334. secret = ""
  335. }
  336. }
  337. }