NightscoutConfigStateModel.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 uploadStats = false // Upload Statistics
  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(\.useLocalGlucoseSource, on: $useLocalSource) { useLocalSource = $0 }
  43. subscribeSetting(\.localGlucosePort, on: $localPort.map(Int.init)) { localPort = Decimal($0) }
  44. subscribeSetting(\.uploadStats, on: $uploadStats) { uploadStats = $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. func importSettings() {
  80. guard let nightscout = nightscoutAPI else {
  81. saveError("Can't access nightscoutAPI")
  82. return
  83. }
  84. let group = DispatchGroup()
  85. group.enter()
  86. var error = ""
  87. let path = "/api/v1/profile.json"
  88. let timeout: TimeInterval = 60
  89. var components = URLComponents()
  90. components.scheme = nightscout.url.scheme
  91. components.host = nightscout.url.host
  92. components.port = nightscout.url.port
  93. components.path = path
  94. components.queryItems = [
  95. URLQueryItem(name: "count", value: "1")
  96. ]
  97. var url = URLRequest(url: components.url!)
  98. url.allowsConstrainedNetworkAccess = false
  99. url.timeoutInterval = timeout
  100. if let secret = nightscout.secret {
  101. url.addValue(secret.sha1(), forHTTPHeaderField: "api-secret")
  102. }
  103. let task = URLSession.shared.dataTask(with: url) { data, response, error_ in
  104. if let error_ = error_ {
  105. print("Error occured: " + error_.localizedDescription)
  106. // handle error
  107. self.saveError("Error occured: " + error_.localizedDescription)
  108. error = error_.localizedDescription
  109. return
  110. }
  111. guard let httpResponse = response as? HTTPURLResponse,
  112. (200 ... 299).contains(httpResponse.statusCode)
  113. else {
  114. print("Error occured! " + error_.debugDescription)
  115. // handle error
  116. self.saveError(error_.debugDescription)
  117. return
  118. }
  119. let jsonDecoder = JSONCoding.decoder
  120. if let mimeType = httpResponse.mimeType, mimeType == "application/json",
  121. let data = data
  122. {
  123. do {
  124. let fetchedProfileStore = try jsonDecoder.decode([FetchedNightscoutProfileStore].self, from: data)
  125. guard let fetchedProfile: ScheduledNightscoutProfile = fetchedProfileStore.first?.store["default"]
  126. else {
  127. error = "\nCan't find the default Nightscout Profile."
  128. group.leave()
  129. return
  130. }
  131. guard fetchedProfile.units.contains(self.units.rawValue.prefix(4)) else {
  132. debug(
  133. .nightscout,
  134. "Mismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
  135. )
  136. error = "\nMismatching glucose units in Nightscout and Pump Settings. Import settings aborted."
  137. group.leave()
  138. return
  139. }
  140. var areCRsOK = true
  141. let carbratios = fetchedProfile.carbratio
  142. .map { carbratio -> CarbRatioEntry in
  143. if carbratio.value <= 0 {
  144. error =
  145. "\nInvalid Carb Ratio settings in Nightscout.\n\nImport aborted. Please check your Nightscout Profile Carb Ratios Settings!"
  146. areCRsOK = false
  147. }
  148. return CarbRatioEntry(
  149. start: carbratio.time,
  150. offset: self.offset(carbratio.time) / 60,
  151. ratio: carbratio.value
  152. ) }
  153. let carbratiosProfile = CarbRatios(units: CarbUnit.grams, schedule: carbratios)
  154. guard areCRsOK else {
  155. group.leave()
  156. return
  157. }
  158. var areBasalsOK = true
  159. let pumpName = self.apsManager.pumpName.value
  160. let basals = fetchedProfile.basal
  161. .map { basal -> BasalProfileEntry in
  162. if pumpName != "Omnipod DASH", basal.value <= 0
  163. {
  164. error =
  165. "\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.)"
  166. areBasalsOK = false
  167. }
  168. return BasalProfileEntry(
  169. start: basal.time,
  170. minutes: self.offset(basal.time) / 60,
  171. rate: basal.value
  172. ) }
  173. // DASH pumps can have 0U/h basal rates but don't import if total basals (24 hours) amount to 0 U.
  174. if pumpName == "Omnipod DASH", basals.map({ each in each.rate }).reduce(0, +) <= 0
  175. {
  176. error =
  177. "\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.)"
  178. areBasalsOK = false
  179. }
  180. guard areBasalsOK else {
  181. group.leave()
  182. return
  183. }
  184. let sensitivities = fetchedProfile.sens.map { sensitivity -> InsulinSensitivityEntry in
  185. InsulinSensitivityEntry(
  186. sensitivity: self.units == .mmolL ? sensitivity.value : sensitivity.value.asMgdL,
  187. offset: self.offset(sensitivity.time) / 60,
  188. start: sensitivity.time
  189. )
  190. }
  191. if sensitivities.filter({ $0.sensitivity <= 0 }).isNotEmpty {
  192. error =
  193. "\nInvalid Nightcsout Sensitivities Settings. \n\nImport aborted. Please check your Nightscout Profile Sensitivities Settings!"
  194. group.leave()
  195. return
  196. }
  197. let sensitivitiesProfile = InsulinSensitivities(
  198. units: self.units,
  199. userPrefferedUnits: self.units,
  200. sensitivities: sensitivities
  201. )
  202. let targets = fetchedProfile.target_low
  203. .map { target -> BGTargetEntry in
  204. BGTargetEntry(
  205. low: self.units == .mmolL ? target.value : target.value.asMgdL,
  206. high: self.units == .mmolL ? target.value : target.value.asMgdL,
  207. start: target.time,
  208. offset: self.offset(target.time) / 60
  209. ) }
  210. let targetsProfile = BGTargets(
  211. units: self.units,
  212. userPrefferedUnits: self.units,
  213. targets: targets
  214. )
  215. // IS THERE A PUMP?
  216. guard let pump = self.apsManager.pumpManager else {
  217. self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  218. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  219. self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  220. self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  221. debug(
  222. .service,
  223. "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"
  224. )
  225. error =
  226. "\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"
  227. group.leave()
  228. return
  229. }
  230. let syncValues = basals.map {
  231. RepeatingScheduleValue(startTime: TimeInterval($0.minutes * 60), value: Double($0.rate))
  232. }
  233. // SSAVE TO STORAGE. SAVE TO PUMP (LoopKit)
  234. pump.syncBasalRateSchedule(items: syncValues) { result in
  235. switch result {
  236. case .success:
  237. self.storage.save(basals, as: OpenAPS.Settings.basalProfile)
  238. self.storage.save(carbratiosProfile, as: OpenAPS.Settings.carbRatios)
  239. self.storage.save(sensitivitiesProfile, as: OpenAPS.Settings.insulinSensitivities)
  240. self.storage.save(targetsProfile, as: OpenAPS.Settings.bgTargets)
  241. debug(.service, "Settings have been imported and the Basals saved to pump!")
  242. // DIA. Save if changed.
  243. let dia = fetchedProfile.dia
  244. print("dia: " + dia.description)
  245. print("pump dia: " + self.dia.description)
  246. if dia != self.dia, dia >= 0 {
  247. let file = PumpSettings(
  248. insulinActionCurve: dia,
  249. maxBolus: self.maxBolus,
  250. maxBasal: self.maxBasal
  251. )
  252. self.storage.save(file, as: OpenAPS.Settings.settings)
  253. debug(.nightscout, "DIA setting updated to " + dia.description + " after a NS import.")
  254. }
  255. group.leave()
  256. case .failure:
  257. error =
  258. "\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"
  259. debug(.service, "Basals couldn't be save to pump")
  260. group.leave()
  261. }
  262. }
  263. } catch let parsingError {
  264. print(parsingError)
  265. error = parsingError.localizedDescription
  266. group.leave()
  267. }
  268. }
  269. }
  270. task.resume()
  271. group.wait(wallTimeout: .now() + 5)
  272. group.notify(queue: .global(qos: .background)) {
  273. self.saveError(error)
  274. }
  275. }
  276. func offset(_ string: String) -> Int {
  277. let hours = Int(string.prefix(2)) ?? 0
  278. let minutes = Int(string.suffix(2)) ?? 0
  279. return ((hours * 60) + minutes) * 60
  280. }
  281. func saveError(_ string: String) {
  282. coredataContext.performAndWait {
  283. let saveToCoreData = ImportError(context: self.coredataContext)
  284. saveToCoreData.date = Date()
  285. saveToCoreData.error = string
  286. if coredataContext.hasChanges {
  287. try? coredataContext.save()
  288. }
  289. }
  290. }
  291. func backfillGlucose() {
  292. backfilling = true
  293. nightscoutManager.fetchGlucose(since: Date().addingTimeInterval(-1.days.timeInterval))
  294. .sink { [weak self] glucose in
  295. guard let self = self else { return }
  296. DispatchQueue.main.async {
  297. self.backfilling = false
  298. }
  299. guard glucose.isNotEmpty else { return }
  300. self.healthKitManager.saveIfNeeded(bloodGlucose: glucose)
  301. self.glucoseStorage.storeGlucose(glucose)
  302. }
  303. .store(in: &lifetime)
  304. }
  305. func delete() {
  306. keychain.removeObject(forKey: Config.urlKey)
  307. keychain.removeObject(forKey: Config.secretKey)
  308. url = ""
  309. secret = ""
  310. }
  311. }
  312. }