NightscoutConfigStateModel.swift 17 KB

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