GlucoseSimulatorSource.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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(_: DispatchTimer?) -> 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. let startup = Date()
  87. init(currentGlucose: Int) {
  88. self.currentGlucose = currentGlucose
  89. }
  90. func getBloodGlucoses(startDate: Date, finishDate: Date, withInterval interval: TimeInterval) -> [BloodGlucose] {
  91. var result = [BloodGlucose]()
  92. var _currentDate = startDate
  93. while _currentDate <= finishDate {
  94. result.append(getNextBloodGlucose(forDate: _currentDate))
  95. _currentDate = _currentDate.addingTimeInterval(interval)
  96. }
  97. return result
  98. }
  99. // get next glucose's value in current trend
  100. private func getNextBloodGlucose(forDate date: Date) -> BloodGlucose {
  101. let previousGlucose = currentGlucose
  102. makeStepInTrend()
  103. trandsStepDirection = getDirection(fromGlucose: previousGlucose, toGlucose: currentGlucose).rawValue
  104. let glucose = BloodGlucose(
  105. _id: UUID().uuidString,
  106. sgv: nil,
  107. direction: BloodGlucose.Direction(rawValue: trandsStepDirection),
  108. date: Decimal(Int(date.timeIntervalSince1970) * 1000),
  109. dateString: date,
  110. unfiltered: nil,
  111. filtered: nil,
  112. noise: nil,
  113. glucose: currentGlucose,
  114. type: nil,
  115. activationDate: startup,
  116. sessionStartDate: startup,
  117. transmitterID: "SIMULATOR"
  118. )
  119. return glucose
  120. }
  121. private func setNewRandomTarget() {
  122. guard trendTargetValue > 0 else {
  123. trendTargetValue = Array(80 ... 110).randomElement()!
  124. return
  125. }
  126. let difference = (Array(-50 ... -20) + Array(20 ... 50)).randomElement()!
  127. let _value = trendTargetValue + difference
  128. if _value <= Config.minGlucose {
  129. trendTargetValue = Config.minGlucose
  130. } else if _value >= Config.maxGlucose {
  131. trendTargetValue = Config.maxGlucose
  132. } else {
  133. trendTargetValue = _value
  134. }
  135. }
  136. private func setNewRandomSteps() {
  137. trendStepsLeft = Array(3 ... 8).randomElement()!
  138. }
  139. private func getDirection(fromGlucose from: Int, toGlucose to: Int) -> BloodGlucose.Direction {
  140. BloodGlucose.Direction(trend: to - from)
  141. }
  142. private func generateNewTrend() {
  143. setNewRandomTarget()
  144. setNewRandomSteps()
  145. }
  146. private func makeStepInTrend() {
  147. currentGlucose +=
  148. Int(Double((trendTargetValue - currentGlucose) / trendStepsLeft) * [0.3, 0.6, 1, 1.3, 1.6].randomElement()!)
  149. trendStepsLeft -= 1
  150. if trendStepsLeft == 0 {
  151. generateNewTrend()
  152. }
  153. }
  154. func sourceInfo() -> [String: Any]? {
  155. [GlucoseSourceKey.description.rawValue: "Glucose simulator"]
  156. }
  157. }