BolusWizardEstimatePumpEvent.swift 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // BolusWizardEstimatePumpEvent.swift
  3. // RileyLink
  4. //
  5. // Created by Pete Schwamb on 3/8/16.
  6. // Copyright © 2016 Pete Schwamb. All rights reserved.
  7. //
  8. import Foundation
  9. public struct BolusWizardEstimatePumpEvent: TimestampedPumpEvent {
  10. public let length: Int
  11. public let rawData: Data
  12. public let timestamp: DateComponents
  13. public let carbohydrates: Int
  14. public let bloodGlucose: Int
  15. public let foodEstimate: Double
  16. public let correctionEstimate: Double
  17. public let bolusEstimate: Double
  18. public let unabsorbedInsulinTotal: Double
  19. public let bgTargetLow: Int
  20. public let bgTargetHigh: Int
  21. public let insulinSensitivity: Int
  22. public let carbRatio: Double
  23. public init?(availableData: Data, pumpModel: PumpModel) {
  24. func d(_ idx: Int) -> Int {
  25. return Int(availableData[idx])
  26. }
  27. func insulinDecode(_ a: Int, b: Int) -> Double {
  28. return Double((a << 8) + b) / 40.0
  29. }
  30. if pumpModel.larger {
  31. length = 22
  32. } else {
  33. length = 20
  34. }
  35. guard length <= availableData.count else {
  36. return nil
  37. }
  38. rawData = availableData.subdata(in: 0..<length)
  39. timestamp = DateComponents(pumpEventData: availableData, offset: 2)
  40. if pumpModel.larger {
  41. carbohydrates = ((d(8) & 0xc) << 6) + d(7)
  42. bloodGlucose = ((d(8) & 0x3) << 8) + d(1)
  43. foodEstimate = insulinDecode(d(14), b: d(15))
  44. correctionEstimate = Double(((d(16) & 0b111000) << 5) + d(13)) / 40.0
  45. bolusEstimate = insulinDecode(d(19), b: d(20))
  46. unabsorbedInsulinTotal = insulinDecode(d(17), b: d(18))
  47. bgTargetLow = d(12)
  48. bgTargetHigh = d(21)
  49. insulinSensitivity = d(11)
  50. carbRatio = Double(((d(9) & 0x7) << 8) + d(10)) / 10.0
  51. } else {
  52. carbohydrates = d(7)
  53. bloodGlucose = ((d(8) & 0x3) << 8) + d(1)
  54. foodEstimate = Double(d(13))/10.0
  55. correctionEstimate = Double((d(14) << 8) + d(12)) / 10.0
  56. bolusEstimate = Double(d(18))/10.0
  57. unabsorbedInsulinTotal = Double(d(16))/10.0
  58. bgTargetLow = d(11)
  59. bgTargetHigh = d(19)
  60. insulinSensitivity = d(10)
  61. carbRatio = Double(d(9))
  62. }
  63. }
  64. public var dictionaryRepresentation: [String: Any] {
  65. return [
  66. "_type": "BolusWizardBolusEstimate",
  67. "bg": bloodGlucose,
  68. "bgTargetHigh": bgTargetHigh,
  69. "correctionEstimate": correctionEstimate,
  70. "carbInput": carbohydrates,
  71. "unabsorbedInsulinTotal": unabsorbedInsulinTotal,
  72. "bolusEstimate": bolusEstimate,
  73. "carbRatio": carbRatio,
  74. "foodEstimate": foodEstimate,
  75. "bgTargetLow": bgTargetLow,
  76. "insulinSensitivity": insulinSensitivity
  77. ]
  78. }
  79. }