DexcomSourceG5.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import CGMBLEKit
  2. import Combine
  3. import Foundation
  4. import LoopKit
  5. import LoopKitUI
  6. import ShareClient
  7. final class DexcomSourceG5: GlucoseSource {
  8. private let processQueue = DispatchQueue(label: "DexcomSource.processQueue")
  9. private let glucoseStorage: GlucoseStorage!
  10. var glucoseManager: FetchGlucoseManager?
  11. var cgmManager: CGMManagerUI?
  12. var cgmType: CGMType = .dexcomG5
  13. var cgmHasValidSensorSession: Bool = false
  14. private var promise: Future<[BloodGlucose], Error>.Promise?
  15. init(glucoseStorage: GlucoseStorage, glucoseManager: FetchGlucoseManager) {
  16. self.glucoseStorage = glucoseStorage
  17. self.glucoseManager = glucoseManager
  18. cgmManager = G5CGMManager
  19. .init(state: TransmitterManagerState(
  20. transmitterID: UserDefaults.standard
  21. .dexcomTransmitterID ?? "000000",
  22. shouldSyncToRemoteService: glucoseManager.settingsManager.settings.uploadGlucose
  23. ))
  24. cgmManager?.cgmManagerDelegate = self
  25. }
  26. var transmitterID: String {
  27. guard let cgmG5Manager = cgmManager as? G5CGMManager else { return "000000" }
  28. return cgmG5Manager.transmitter.ID
  29. }
  30. func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
  31. Future<[BloodGlucose], Error> { [weak self] promise in
  32. self?.promise = promise
  33. }
  34. .timeout(60 * 5, scheduler: processQueue, options: nil, customError: nil)
  35. .replaceError(with: [])
  36. .replaceEmpty(with: [])
  37. .eraseToAnyPublisher()
  38. }
  39. func fetchIfNeeded() -> AnyPublisher<[BloodGlucose], Never> {
  40. Future<[BloodGlucose], Error> { _ in
  41. self.processQueue.async {
  42. guard let cgmManager = self.cgmManager else { return }
  43. cgmManager.fetchNewDataIfNeeded { result in
  44. self.processCGMReadingResult(cgmManager, readingResult: result) {
  45. // nothing to do
  46. }
  47. }
  48. }
  49. }
  50. .timeout(60, scheduler: processQueue, options: nil, customError: nil)
  51. .replaceError(with: [])
  52. .replaceEmpty(with: [])
  53. .eraseToAnyPublisher()
  54. }
  55. deinit {
  56. // dexcomManager.transmitter.stopScanning()
  57. }
  58. }
  59. extension DexcomSourceG5: CGMManagerDelegate {
  60. func deviceManager(
  61. _: LoopKit.DeviceManager,
  62. logEventForDeviceIdentifier deviceIdentifier: String?,
  63. type _: LoopKit.DeviceLogEntryType,
  64. message: String,
  65. completion _: ((Error?) -> Void)?
  66. ) {
  67. debug(.deviceManager, "device Manager for \(String(describing: deviceIdentifier)) : \(message)")
  68. }
  69. func issueAlert(_: LoopKit.Alert) {}
  70. func retractAlert(identifier _: LoopKit.Alert.Identifier) {}
  71. func doesIssuedAlertExist(identifier _: LoopKit.Alert.Identifier, completion _: @escaping (Result<Bool, Error>) -> Void) {}
  72. func lookupAllUnretracted(
  73. managerIdentifier _: String,
  74. completion _: @escaping (Result<[LoopKit.PersistedAlert], Error>) -> Void
  75. ) {}
  76. func lookupAllUnacknowledgedUnretracted(
  77. managerIdentifier _: String,
  78. completion _: @escaping (Result<[LoopKit.PersistedAlert], Error>) -> Void
  79. ) {}
  80. func recordRetractedAlert(_: LoopKit.Alert, at _: Date) {}
  81. func cgmManagerWantsDeletion(_ manager: CGMManager) {
  82. dispatchPrecondition(condition: .onQueue(.main))
  83. debug(.deviceManager, " CGM Manager with identifier \(manager.pluginIdentifier) wants deletion")
  84. glucoseManager?.cgmGlucoseSourceType = nil
  85. }
  86. func cgmManager(_ manager: CGMManager, hasNew readingResult: CGMReadingResult) {
  87. dispatchPrecondition(condition: .onQueue(.main))
  88. processCGMReadingResult(manager, readingResult: readingResult) {
  89. debug(.deviceManager, "DEXCOM - Direct return done")
  90. }
  91. }
  92. func cgmManager(_: LoopKit.CGMManager, hasNew events: [LoopKit.PersistedCgmEvent]) {
  93. dispatchPrecondition(condition: .onQueue(processQueue))
  94. // TODO: Events in APS ?
  95. // currently only display in log the date of the event
  96. events.forEach { debug(.deviceManager, "events from CGM at \($0.date)") }
  97. }
  98. func startDateToFilterNewData(for _: CGMManager) -> Date? {
  99. dispatchPrecondition(condition: .onQueue(.main))
  100. return glucoseStorage.lastGlucoseDate()
  101. // return glucoseStore.latestGlucose?.startDate
  102. }
  103. func cgmManagerDidUpdateState(_ manager: CGMManager) {
  104. dispatchPrecondition(condition: .onQueue(processQueue))
  105. guard let g5Manager = manager as? TransmitterManager else {
  106. return
  107. }
  108. glucoseManager?.settingsManager.settings.uploadGlucose = g5Manager.shouldSyncToRemoteService
  109. UserDefaults.standard.dexcomTransmitterID = g5Manager.rawState["transmitterID"] as? String
  110. }
  111. func credentialStoragePrefix(for _: CGMManager) -> String {
  112. // return string unique to this instance of the CGMManager
  113. UUID().uuidString
  114. }
  115. func cgmManager(_: CGMManager, didUpdate status: CGMManagerStatus) {
  116. DispatchQueue.main.async {
  117. if self.cgmHasValidSensorSession != status.hasValidSensorSession {
  118. self.cgmHasValidSensorSession = status.hasValidSensorSession
  119. }
  120. }
  121. }
  122. private func processCGMReadingResult(
  123. _: CGMManager,
  124. readingResult: CGMReadingResult,
  125. completion: @escaping () -> Void
  126. ) {
  127. debug(.deviceManager, "DEXCOM - Process CGM Reading Result launched")
  128. switch readingResult {
  129. case let .newData(values):
  130. let bloodGlucose = values.compactMap { newGlucoseSample -> BloodGlucose? in
  131. let quantity = newGlucoseSample.quantity
  132. let value = Int(quantity.doubleValue(for: .milligramsPerDeciliter))
  133. return BloodGlucose(
  134. _id: UUID().uuidString,
  135. sgv: value,
  136. direction: .init(trendType: newGlucoseSample.trend),
  137. date: Decimal(Int(newGlucoseSample.date.timeIntervalSince1970 * 1000)),
  138. dateString: newGlucoseSample.date,
  139. unfiltered: Decimal(value),
  140. filtered: nil,
  141. noise: nil,
  142. glucose: value,
  143. type: "sgv",
  144. transmitterID: self.transmitterID
  145. )
  146. }
  147. promise?(.success(bloodGlucose))
  148. completion()
  149. case .unreliableData:
  150. // loopManager.receivedUnreliableCGMReading()
  151. promise?(.failure(GlucoseDataError.unreliableData))
  152. completion()
  153. case .noData:
  154. promise?(.failure(GlucoseDataError.noData))
  155. completion()
  156. case let .error(error):
  157. promise?(.failure(error))
  158. completion()
  159. }
  160. }
  161. }
  162. extension DexcomSourceG5 {
  163. func sourceInfo() -> [String: Any]? {
  164. [GlucoseSourceKey.description.rawValue: "Dexcom tramsmitter ID: \(transmitterID)"]
  165. }
  166. }