AbsorbedCarbValue.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // AbsorbedCarbValue.swift
  3. // LoopKit
  4. //
  5. // Copyright © 2017 LoopKit Authors. All rights reserved.
  6. //
  7. import Foundation
  8. import HealthKit
  9. /// A quantity of carbs absorbed over a given date interval
  10. public struct AbsorbedCarbValue: SampleValue {
  11. /// The quantity of carbs absorbed
  12. public let observed: HKQuantity
  13. /// The quantity of carbs absorbed, clamped to the original prediction
  14. public let clamped: HKQuantity
  15. /// The quantity of carbs entered as eaten
  16. public let total: HKQuantity
  17. /// The quantity of carbs expected to still absorb
  18. public let remaining: HKQuantity
  19. /// The dates over which absorption was observed
  20. public let observedDate: DateInterval
  21. /// The predicted time for the remaining carbs to absorb
  22. public let estimatedTimeRemaining: TimeInterval
  23. // Total predicted absorption time for this carb entry
  24. public var estimatedDate: DateInterval {
  25. return DateInterval(start: observedDate.start, duration: observedDate.duration + estimatedTimeRemaining)
  26. }
  27. /// The amount of time required to absorb observed carbs
  28. public let timeToAbsorbObservedCarbs: TimeInterval
  29. /// Whether absorption is still in-progress
  30. public var isActive: Bool {
  31. return estimatedTimeRemaining > 0
  32. }
  33. public var observedProgress: HKQuantity {
  34. let gram = HKUnit.gram()
  35. let totalGrams = total.doubleValue(for: gram)
  36. let percent = HKUnit.percent()
  37. guard totalGrams > 0 else {
  38. return HKQuantity(unit: percent, doubleValue: 0)
  39. }
  40. return HKQuantity(
  41. unit: percent,
  42. doubleValue: observed.doubleValue(for: gram) / totalGrams
  43. )
  44. }
  45. public var clampedProgress: HKQuantity {
  46. let gram = HKUnit.gram()
  47. let totalGrams = total.doubleValue(for: gram)
  48. let percent = HKUnit.percent()
  49. guard totalGrams > 0 else {
  50. return HKQuantity(unit: percent, doubleValue: 0)
  51. }
  52. return HKQuantity(
  53. unit: percent,
  54. doubleValue: clamped.doubleValue(for: gram) / totalGrams
  55. )
  56. }
  57. // MARK: SampleValue
  58. public var quantity: HKQuantity {
  59. return clamped
  60. }
  61. public var startDate: Date {
  62. return estimatedDate.start
  63. }
  64. }