BloodGlucose.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import Foundation
  2. struct BloodGlucose: JSON, Identifiable, Hashable {
  3. enum Direction: String, JSON {
  4. case tripleUp = "TripleUp"
  5. case doubleUp = "DoubleUp"
  6. case singleUp = "SingleUp"
  7. case fortyFiveUp = "FortyFiveUp"
  8. case flat = "Flat"
  9. case fortyFiveDown = "FortyFiveDown"
  10. case singleDown = "SingleDown"
  11. case doubleDown = "DoubleDown"
  12. case tripleDown = "TripleDown"
  13. case none = "NONE"
  14. case notComputable = "NOT COMPUTABLE"
  15. case rateOutOfRange = "RATE OUT OF RANGE"
  16. }
  17. var _id = UUID().uuidString
  18. var id: String {
  19. _id
  20. }
  21. var sgv: Int?
  22. var direction: Direction?
  23. let date: Decimal
  24. let dateString: Date
  25. let unfiltered: Decimal?
  26. let filtered: Decimal?
  27. let noise: Int?
  28. var glucose: Int?
  29. let type: String?
  30. var activationDate: Date? = nil
  31. var sessionStartDate: Date? = nil
  32. var transmitterID: String? = nil
  33. var isStateValid: Bool { sgv ?? 0 >= 39 && noise ?? 1 != 4 }
  34. static func == (lhs: BloodGlucose, rhs: BloodGlucose) -> Bool {
  35. lhs.dateString == rhs.dateString
  36. }
  37. func hash(into hasher: inout Hasher) {
  38. hasher.combine(dateString)
  39. }
  40. }
  41. enum GlucoseUnits: String, JSON, Equatable {
  42. case mgdL = "mg/dL"
  43. case mmolL = "mmol/L"
  44. static let exchangeRate: Decimal = 0.0555
  45. }
  46. extension Int {
  47. var asMmolL: Decimal {
  48. Decimal(self) * GlucoseUnits.exchangeRate
  49. }
  50. }
  51. extension Decimal {
  52. var asMmolL: Decimal {
  53. self * GlucoseUnits.exchangeRate
  54. }
  55. var asMgdL: Decimal {
  56. self / GlucoseUnits.exchangeRate
  57. }
  58. }
  59. extension Double {
  60. var asMmolL: Decimal {
  61. Decimal(self) * GlucoseUnits.exchangeRate
  62. }
  63. var asMgdL: Decimal {
  64. Decimal(self) / GlucoseUnits.exchangeRate
  65. }
  66. }
  67. extension BloodGlucose: SavitzkyGolaySmoothable {
  68. var value: Double {
  69. get {
  70. Double(glucose ?? 0)
  71. }
  72. set {
  73. glucose = Int(newValue)
  74. sgv = Int(newValue)
  75. }
  76. }
  77. }