NightscoutConfigStateModel.swift 18 KB

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