DexcomSource.swift 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import CGMBLEKit
  2. import Combine
  3. import Foundation
  4. final class DexcomSource: GlucoseSource {
  5. private let processQueue = DispatchQueue(label: "DexcomSource.processQueue")
  6. private let dexcomManager = TransmitterManager(
  7. state: TransmitterManagerState(transmitterID: UserDefaults.standard.dexcomTransmitterID ?? "000000")
  8. )
  9. private var promise: Future<[BloodGlucose], Error>.Promise?
  10. init() {
  11. dexcomManager.delegate = self
  12. }
  13. var transmitterID: String {
  14. dexcomManager.transmitter.ID
  15. }
  16. func fetch() -> AnyPublisher<[BloodGlucose], Never> {
  17. dexcomManager.transmitter.resumeScanning()
  18. return Future<[BloodGlucose], Error> { [weak self] promise in
  19. self?.promise = promise
  20. }
  21. .timeout(60, scheduler: processQueue, options: nil, customError: nil)
  22. .replaceError(with: [])
  23. .replaceEmpty(with: [])
  24. .eraseToAnyPublisher()
  25. }
  26. deinit {
  27. dexcomManager.transmitter.stopScanning()
  28. }
  29. }
  30. extension DexcomSource: TransmitterManagerDelegate {
  31. func transmitterManager(_: TransmitterManager, didFailWith error: Error) {
  32. promise?(.failure(error))
  33. }
  34. func transmitterManager(_: TransmitterManager, didRead glucose: [CGMBLEKit.Glucose]) {
  35. let bloodGlucose = glucose.compactMap { glucose -> BloodGlucose? in
  36. guard let quantity = glucose.glucose else {
  37. return nil
  38. }
  39. let value = Int(quantity.doubleValue(for: .milligramsPerDeciliter))
  40. return BloodGlucose(
  41. _id: glucose.syncIdentifier,
  42. sgv: value,
  43. direction: .init(trend: glucose.trend),
  44. date: Decimal(Int(glucose.readDate.timeIntervalSince1970 * 1000)),
  45. dateString: glucose.readDate,
  46. unfiltered: nil,
  47. filtered: nil,
  48. noise: nil,
  49. glucose: value,
  50. type: "sgv"
  51. )
  52. }
  53. promise?(.success(bloodGlucose))
  54. }
  55. func sourceInfo() -> [String: Any]? {
  56. [GlucoseSourceKey.description.rawValue: "Dexcom tramsmitter ID: \(transmitterID)"]
  57. }
  58. }
  59. extension BloodGlucose.Direction {
  60. init(trend: Int) {
  61. guard trend < Int(Int8.max) else {
  62. self = .none
  63. return
  64. }
  65. switch trend {
  66. case let x where x <= -30:
  67. self = .doubleDown
  68. case let x where x <= -20:
  69. self = .singleDown
  70. case let x where x <= -10:
  71. self = .fortyFiveDown
  72. case let x where x < 10:
  73. self = .flat
  74. case let x where x < 20:
  75. self = .fortyFiveUp
  76. case let x where x < 30:
  77. self = .singleUp
  78. default:
  79. self = .doubleUp
  80. }
  81. }
  82. }