DexcomSource.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. .eraseToAnyPublisher()
  24. }
  25. deinit {
  26. dexcomManager.transmitter.stopScanning()
  27. }
  28. }
  29. extension DexcomSource: TransmitterManagerDelegate {
  30. func transmitterManager(_: TransmitterManager, didFailWith error: Error) {
  31. promise?(.failure(error))
  32. }
  33. func transmitterManager(_: TransmitterManager, didRead glucose: [CGMBLEKit.Glucose]) {
  34. let bloodGlucose = glucose.compactMap { glucose -> BloodGlucose? in
  35. guard let quantity = glucose.glucose else {
  36. return nil
  37. }
  38. let value = Int(quantity.doubleValue(for: .milligramsPerDeciliter))
  39. return BloodGlucose(
  40. _id: glucose.syncIdentifier,
  41. sgv: value,
  42. direction: .init(trend: glucose.trend),
  43. date: Decimal(Int(glucose.readDate.timeIntervalSince1970 * 1000)),
  44. dateString: glucose.readDate,
  45. unfiltered: nil,
  46. filtered: nil,
  47. noise: nil,
  48. glucose: value,
  49. type: "sgv"
  50. )
  51. }
  52. promise?(.success(bloodGlucose))
  53. }
  54. func sourceInfo() -> [String: Any]? {
  55. [GlucoseSourceKey.description.rawValue: "Dexcom tramsmitter ID: \(transmitterID)"]
  56. }
  57. }
  58. extension BloodGlucose.Direction {
  59. init(trend: Int) {
  60. guard trend < Int(Int8.max) else {
  61. self = .none
  62. return
  63. }
  64. switch trend {
  65. case let x where x <= -30:
  66. self = .doubleDown
  67. case let x where x <= -20:
  68. self = .singleDown
  69. case let x where x <= -10:
  70. self = .fortyFiveDown
  71. case let x where x < 10:
  72. self = .flat
  73. case let x where x < 20:
  74. self = .fortyFiveUp
  75. case let x where x < 30:
  76. self = .singleUp
  77. default:
  78. self = .doubleUp
  79. }
  80. }
  81. }