GlucoseSimulatorSource.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /// Glucose source - Blood Glucose Simulator
  2. ///
  3. /// Source publish fake data about glucose's level, creates ascending and descending trends
  4. ///
  5. /// Enter point of Source is GlucoseSimulatorSource.fetch method. Method is called from FetchGlucoseManager module.
  6. /// Not more often than a specified period (default - 300 seconds), it returns a Combine-publisher that publishes data on glucose values (global type BloodGlucose). If there is no up-to-date data (or the publication period has not passed yet), then a publisher of type Empty is returned, otherwise it returns a publisher of type Just.
  7. ///
  8. /// Simulator composition
  9. /// ===================
  10. ///
  11. /// class GlucoseSimulatorSource - main class
  12. /// protocol BloodGlucoseGenerator
  13. /// - IntelligentGenerator: BloodGlucoseGenerator
  14. // TODO: Every itteration trend make two steps, but must only one
  15. // TODO: Trend's value sticks to max and min Glucose value (in Glucose Generator)
  16. // TODO: Add reaction to insulin
  17. // TODO: Add probability to set trend's target value. Middle values must have more probability, than max and min.
  18. import Combine
  19. import Foundation
  20. import LoopKitUI
  21. // MARK: - Glucose simulator
  22. final class GlucoseSimulatorSource: GlucoseSource {
  23. var cgmManager: CGMManagerUI?
  24. var glucoseManager: FetchGlucoseManager?
  25. private enum Config {
  26. // min time period to publish data
  27. static let workInterval: TimeInterval = 300
  28. // default BloodGlucose item at first run
  29. // 288 = 1 day * 24 hours * 60 minites * 60 seconds / workInterval
  30. static let defaultBGItems = 288
  31. }
  32. @Persisted(key: "GlucoseSimulatorLastGlucose") private var lastGlucose = 100
  33. @Persisted(key: "GlucoseSimulatorLastFetchDate") private var lastFetchDate: Date! = nil
  34. init() {
  35. if lastFetchDate == nil {
  36. var lastDate = Date()
  37. for _ in 1 ... Config.defaultBGItems {
  38. lastDate = lastDate.addingTimeInterval(-Config.workInterval)
  39. }
  40. lastFetchDate = lastDate
  41. }
  42. }
  43. private lazy var generator: BloodGlucoseGenerator = {
  44. IntelligentGenerator(
  45. currentGlucose: lastGlucose
  46. )
  47. }()
  48. private var canGenerateNewValues: Bool {
  49. guard let lastDate = lastFetchDate else { return true }
  50. if Calendar.current.dateComponents([.second], from: lastDate, to: Date()).second! >= Int(Config.workInterval) {
  51. return true
  52. } else {
  53. return false
  54. }
  55. }
  56. func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
  57. guard canGenerateNewValues else {
  58. return Just([]).eraseToAnyPublisher()
  59. }
  60. let glucoses = generator.getBloodGlucoses(
  61. startDate: lastFetchDate,
  62. finishDate: Date(),
  63. withInterval: Config.workInterval
  64. )
  65. if let lastItem = glucoses.last {
  66. lastGlucose = lastItem.glucose!
  67. lastFetchDate = Date()
  68. }
  69. return Just(glucoses).eraseToAnyPublisher()
  70. }
  71. func fetchIfNeeded() -> AnyPublisher<[BloodGlucose], Never> {
  72. fetch(nil)
  73. }
  74. }
  75. // MARK: - Glucose generator
  76. protocol BloodGlucoseGenerator {
  77. func getBloodGlucoses(startDate: Date, finishDate: Date, withInterval: TimeInterval) -> [BloodGlucose]
  78. }
  79. class IntelligentGenerator: BloodGlucoseGenerator {
  80. private enum Config {
  81. // max and min glucose of trend's target
  82. static let maxGlucose = 320
  83. static let minGlucose = 45
  84. }
  85. // target glucose of trend
  86. @Persisted(key: "GlucoseSimulatorTargetValue") private var trendTargetValue = 100
  87. // how many steps left in current trend
  88. @Persisted(key: "GlucoseSimulatorTargetSteps") private var trendStepsLeft = 1
  89. // direction of last step
  90. @Persisted(key: "GlucoseSimulatorDirection") private var trandsStepDirection = BloodGlucose.Direction.flat.rawValue
  91. var currentGlucose: Int
  92. let startup = Date()
  93. init(currentGlucose: Int) {
  94. self.currentGlucose = currentGlucose
  95. }
  96. func getBloodGlucoses(startDate: Date, finishDate: Date, withInterval interval: TimeInterval) -> [BloodGlucose] {
  97. var result = [BloodGlucose]()
  98. var _currentDate = startDate
  99. while _currentDate <= finishDate {
  100. result.append(getNextBloodGlucose(forDate: _currentDate))
  101. _currentDate = _currentDate.addingTimeInterval(interval)
  102. }
  103. return result
  104. }
  105. // get next glucose's value in current trend
  106. private func getNextBloodGlucose(forDate date: Date) -> BloodGlucose {
  107. let previousGlucose = currentGlucose
  108. makeStepInTrend()
  109. trandsStepDirection = getDirection(fromGlucose: previousGlucose, toGlucose: currentGlucose).rawValue
  110. let glucose = BloodGlucose(
  111. _id: UUID().uuidString,
  112. sgv: currentGlucose,
  113. direction: BloodGlucose.Direction(rawValue: trandsStepDirection),
  114. date: Decimal(Int(date.timeIntervalSince1970) * 1000),
  115. dateString: date,
  116. unfiltered: Decimal(currentGlucose),
  117. filtered: nil,
  118. noise: nil,
  119. glucose: currentGlucose,
  120. type: nil,
  121. activationDate: startup,
  122. sessionStartDate: startup,
  123. transmitterID: "SIMULATOR"
  124. )
  125. return glucose
  126. }
  127. private func setNewRandomTarget() {
  128. guard trendTargetValue > 0 else {
  129. trendTargetValue = Array(80 ... 110).randomElement()!
  130. return
  131. }
  132. let difference = (Array(-50 ... -20) + Array(20 ... 50)).randomElement()!
  133. let _value = trendTargetValue + difference
  134. if _value <= Config.minGlucose {
  135. trendTargetValue = Config.minGlucose
  136. } else if _value >= Config.maxGlucose {
  137. trendTargetValue = Config.maxGlucose
  138. } else {
  139. trendTargetValue = _value
  140. }
  141. }
  142. private func setNewRandomSteps() {
  143. trendStepsLeft = Array(3 ... 8).randomElement()!
  144. }
  145. private func getDirection(fromGlucose from: Int, toGlucose to: Int) -> BloodGlucose.Direction {
  146. BloodGlucose.Direction(trend: Int(to - from))
  147. }
  148. private func generateNewTrend() {
  149. setNewRandomTarget()
  150. setNewRandomSteps()
  151. }
  152. private func makeStepInTrend() {
  153. currentGlucose +=
  154. Int(Double((trendTargetValue - currentGlucose) / trendStepsLeft) * [0.3, 0.6, 1, 1.3, 1.6, 2.0].randomElement()!)
  155. trendStepsLeft -= 1
  156. if trendStepsLeft == 0 {
  157. generateNewTrend()
  158. }
  159. }
  160. func sourceInfo() -> [String: Any]? {
  161. [GlucoseSourceKey.description.rawValue: "Glucose simulator"]
  162. }
  163. }