GlucoseEffectVelocity.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // GlucoseEffectVelocity.swift
  3. // LoopKit
  4. //
  5. // Copyright © 2017 LoopKit Authors. All rights reserved.
  6. //
  7. import Foundation
  8. import HealthKit
  9. /// The first-derivative of GlucoseEffect, blood glucose over time.
  10. public struct GlucoseEffectVelocity: SampleValue {
  11. public let startDate: Date
  12. public let endDate: Date
  13. public let quantity: HKQuantity
  14. public init(startDate: Date, endDate: Date, quantity: HKQuantity) {
  15. self.startDate = startDate
  16. self.endDate = endDate
  17. self.quantity = quantity
  18. }
  19. }
  20. extension GlucoseEffectVelocity {
  21. static let perSecondUnit = HKUnit.milligramsPerDeciliter.unitDivided(by: .second())
  22. /// The integration of the velocity span
  23. public var effect: GlucoseEffect {
  24. let duration = endDate.timeIntervalSince(startDate)
  25. let velocityPerSecond = quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit)
  26. return GlucoseEffect(
  27. startDate: endDate,
  28. quantity: HKQuantity(
  29. unit: .milligramsPerDeciliter,
  30. doubleValue: velocityPerSecond * duration
  31. )
  32. )
  33. }
  34. /// The integration of the velocity span from `start` to `end`
  35. public func effect(from start: Date, to end: Date) -> GlucoseEffect? {
  36. guard
  37. start <= end,
  38. startDate <= start,
  39. end <= endDate
  40. else {
  41. return nil
  42. }
  43. let duration = end.timeIntervalSince(start)
  44. let velocityPerSecond = quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit)
  45. return GlucoseEffect(
  46. startDate: end,
  47. quantity: HKQuantity(
  48. unit: .milligramsPerDeciliter,
  49. doubleValue: velocityPerSecond * duration
  50. )
  51. )
  52. }
  53. }