GlucoseSimulatorSource.swift 6.2 KB

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