GlucoseSimulatorSource.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. // MARK: - Glucose simulator
  21. final class GlucoseSimulatorSource: GlucoseSource {
  22. var glucoseManager: FetchGlucoseManager?
  23. private enum Config {
  24. // min time period to publish data
  25. static let workInterval: TimeInterval = 300
  26. // default BloodGlucose item at first run
  27. // 288 = 1 day * 24 hours * 60 minites * 60 seconds / workInterval
  28. static let defaultBGItems = 288
  29. }
  30. @Persisted(key: "GlucoseSimulatorLastGlucose") private var lastGlucose = 100
  31. @Persisted(key: "GlucoseSimulatorLastFetchDate") private var lastFetchDate: Date! = nil
  32. init() {
  33. if lastFetchDate == nil {
  34. var lastDate = Date()
  35. for _ in 1 ... Config.defaultBGItems {
  36. lastDate = lastDate.addingTimeInterval(-Config.workInterval)
  37. }
  38. lastFetchDate = lastDate
  39. }
  40. }
  41. private lazy var generator: BloodGlucoseGenerator = {
  42. IntelligentGenerator(
  43. currentGlucose: lastGlucose
  44. )
  45. }()
  46. private var canGenerateNewValues: Bool {
  47. guard let lastDate = lastFetchDate else { return true }
  48. if Calendar.current.dateComponents([.second], from: lastDate, to: Date()).second! >= Int(Config.workInterval) {
  49. return true
  50. } else {
  51. return false
  52. }
  53. }
  54. func fetch(_: DispatchTimer?) -> AnyPublisher<[BloodGlucose], Never> {
  55. guard canGenerateNewValues else {
  56. return Just([]).eraseToAnyPublisher()
  57. }
  58. let glucoses = generator.getBloodGlucoses(
  59. startDate: lastFetchDate,
  60. finishDate: Date(),
  61. withInterval: Config.workInterval
  62. )
  63. if let lastItem = glucoses.last {
  64. lastGlucose = lastItem.glucose!
  65. lastFetchDate = Date()
  66. }
  67. return Just(glucoses).eraseToAnyPublisher()
  68. }
  69. func fetchIfNeeded() -> AnyPublisher<[BloodGlucose], Never> {
  70. fetch(nil)
  71. }
  72. }
  73. // MARK: - Glucose generator
  74. protocol BloodGlucoseGenerator {
  75. func getBloodGlucoses(startDate: Date, finishDate: Date, withInterval: TimeInterval) -> [BloodGlucose]
  76. }
  77. class IntelligentGenerator: BloodGlucoseGenerator {
  78. private enum Config {
  79. // max and min glucose of trend's target
  80. static let maxGlucose = 320
  81. static let minGlucose = 45
  82. }
  83. // target glucose of trend
  84. @Persisted(key: "GlucoseSimulatorTargetValue") private var trendTargetValue = 100
  85. // how many steps left in current trend
  86. @Persisted(key: "GlucoseSimulatorTargetSteps") private var trendStepsLeft = 1
  87. // direction of last step
  88. @Persisted(key: "GlucoseSimulatorDirection") private var trandsStepDirection = BloodGlucose.Direction.flat.rawValue
  89. var currentGlucose: Int
  90. let startup = Date()
  91. init(currentGlucose: Int) {
  92. self.currentGlucose = currentGlucose
  93. }
  94. func getBloodGlucoses(startDate: Date, finishDate: Date, withInterval interval: TimeInterval) -> [BloodGlucose] {
  95. var result = [BloodGlucose]()
  96. var _currentDate = startDate
  97. while _currentDate <= finishDate {
  98. result.append(getNextBloodGlucose(forDate: _currentDate))
  99. _currentDate = _currentDate.addingTimeInterval(interval)
  100. }
  101. return result
  102. }
  103. // get next glucose's value in current trend
  104. private func getNextBloodGlucose(forDate date: Date) -> BloodGlucose {
  105. let previousGlucose = currentGlucose
  106. makeStepInTrend()
  107. trandsStepDirection = getDirection(fromGlucose: previousGlucose, toGlucose: currentGlucose).rawValue
  108. let glucose = BloodGlucose(
  109. _id: UUID().uuidString,
  110. sgv: nil,
  111. direction: BloodGlucose.Direction(rawValue: trandsStepDirection),
  112. date: Decimal(Int(date.timeIntervalSince1970) * 1000),
  113. dateString: date,
  114. unfiltered: nil,
  115. filtered: nil,
  116. noise: nil,
  117. glucose: currentGlucose,
  118. type: nil,
  119. activationDate: startup,
  120. sessionStartDate: startup,
  121. transmitterID: "SIMULATOR"
  122. )
  123. return glucose
  124. }
  125. private func setNewRandomTarget() {
  126. guard trendTargetValue > 0 else {
  127. trendTargetValue = Array(80 ... 110).randomElement()!
  128. return
  129. }
  130. let difference = (Array(-50 ... -20) + Array(20 ... 50)).randomElement()!
  131. let _value = trendTargetValue + difference
  132. if _value <= Config.minGlucose {
  133. trendTargetValue = Config.minGlucose
  134. } else if _value >= Config.maxGlucose {
  135. trendTargetValue = Config.maxGlucose
  136. } else {
  137. trendTargetValue = _value
  138. }
  139. }
  140. private func setNewRandomSteps() {
  141. trendStepsLeft = Array(3 ... 8).randomElement()!
  142. }
  143. private func getDirection(fromGlucose from: Int, toGlucose to: Int) -> BloodGlucose.Direction {
  144. BloodGlucose.Direction(trend: Int(to - from))
  145. }
  146. private func generateNewTrend() {
  147. setNewRandomTarget()
  148. setNewRandomSteps()
  149. }
  150. private func makeStepInTrend() {
  151. currentGlucose +=
  152. Int(Double((trendTargetValue - currentGlucose) / trendStepsLeft) * [0.3, 0.6, 1, 1.3, 1.6].randomElement()!)
  153. trendStepsLeft -= 1
  154. if trendStepsLeft == 0 {
  155. generateNewTrend()
  156. }
  157. }
  158. func sourceInfo() -> [String: Any]? {
  159. [GlucoseSourceKey.description.rawValue: "Glucose simulator"]
  160. }
  161. }