NightscoutConfigStateModel.swift 17 KB

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