PumpEvent+helper.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import CoreData
  2. import Foundation
  3. extension PumpEventStored {
  4. static func fetch(_ predicate: NSPredicate, ascending: Bool, fetchLimit: Int? = nil) -> NSFetchRequest<PumpEventStored> {
  5. let request = PumpEventStored.fetchRequest()
  6. request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: ascending)]
  7. request.resultType = .managedObjectResultType
  8. request.predicate = predicate
  9. if let fetchLimit = fetchLimit {
  10. request.fetchLimit = fetchLimit
  11. }
  12. return request
  13. }
  14. // Preview
  15. @discardableResult static func makePreviewEvents(count: Int, provider: CoreDataStack) -> [PumpEventStored] {
  16. let context = provider.persistentContainer.viewContext
  17. let events = (0 ..< count).map { index -> PumpEventStored in
  18. let event = PumpEventStored(context: context)
  19. event.id = UUID().uuidString
  20. event.timestamp = Date.now.addingTimeInterval(Double(index) * -300) // Every 5 minutes
  21. event.type = EventType.bolus.rawValue
  22. event.isUploadedToNS = false
  23. event.isUploadedToHealth = false
  24. event.isUploadedToTidepool = false
  25. // Add a bolus
  26. let bolus = BolusStored(context: context)
  27. bolus.amount = 2.5 as NSDecimalNumber
  28. bolus.isExternal = false
  29. bolus.isSMB = false
  30. bolus.pumpEvent = event
  31. return event
  32. }
  33. try? context.save()
  34. return events
  35. }
  36. }
  37. public extension PumpEventStored {
  38. enum EventType: String, JSON {
  39. case bolus = "Bolus"
  40. case smb = "SMB"
  41. case isExternal = "External Insulin"
  42. case mealBolus = "Meal Bolus"
  43. case correctionBolus = "Correction Bolus"
  44. case snackBolus = "Snack Bolus"
  45. case bolusWizard = "BolusWizard"
  46. case tempBasal = "TempBasal"
  47. case tempBasalDuration = "TempBasalDuration"
  48. case pumpSuspend = "PumpSuspend"
  49. case pumpResume = "PumpResume"
  50. case pumpAlarm = "PumpAlarm"
  51. case pumpBattery = "PumpBattery"
  52. case rewind = "Rewind"
  53. case prime = "Prime"
  54. case journalCarbs = "JournalEntryMealMarker"
  55. case nsNote = "Note"
  56. case nsTempBasal = "Temp Basal"
  57. case nsCarbCorrection = "Carb Correction"
  58. case nsTempTarget = "Temporary Target"
  59. case nsInsulinChange = "Insulin Change"
  60. case nsSiteChange = "Site Change"
  61. case nsBatteryChange = "Pump Battery Change"
  62. case nsAnnouncement = "Announcement"
  63. case nsSensorChange = "Sensor Start"
  64. case nsExercise = "Exercise"
  65. case capillaryGlucose = "BG Check"
  66. }
  67. enum TempType: String, JSON {
  68. case absolute
  69. case percent
  70. }
  71. }
  72. extension NSPredicate {
  73. static var pumpHistoryLast1440Minutes: NSPredicate {
  74. let date = Date.oneDayAgoInMinutes
  75. return NSPredicate(format: "timestamp >= %@", date as NSDate)
  76. }
  77. static var pumpHistoryLast24h: NSPredicate {
  78. let date = Date.oneDayAgo
  79. return NSPredicate(format: "timestamp >= %@", date as NSDate)
  80. }
  81. static var recentPumpHistory: NSPredicate {
  82. let date = Date.twentyMinutesAgo
  83. return NSPredicate(format: "timestamp >= %@", date as NSDate)
  84. }
  85. static var lastPumpBolus: NSPredicate {
  86. let date = Date.twentyMinutesAgo
  87. return NSPredicate(format: "timestamp >= %@ AND bolus.isExternal == %@", date as NSDate, false as NSNumber)
  88. }
  89. static func duplicateInLastHour(_ date: Date) -> NSPredicate {
  90. let date60m = Date.oneHourAgo
  91. return NSPredicate(format: "timestamp >= %@ && timestamp == %@", date60m as NSDate, date as NSDate)
  92. }
  93. static var pumpEventsNotYetUploadedToNightscout: NSPredicate {
  94. let date = Date.oneDayAgo
  95. return NSPredicate(format: "timestamp >= %@ AND isUploadedToNS == %@", date as NSDate, false as NSNumber)
  96. }
  97. static var pumpEventsNotYetUploadedToHealth: NSPredicate {
  98. let date = Date.oneDayAgo
  99. return NSPredicate(format: "timestamp >= %@ AND isUploadedToHealth == %@", date as NSDate, false as NSNumber)
  100. }
  101. static var pumpEventsNotYetUploadedToTidepool: NSPredicate {
  102. let date = Date.oneDayAgo
  103. return NSPredicate(format: "timestamp >= %@ AND isUploadedToTidepool == %@", date as NSDate, false as NSNumber)
  104. }
  105. }
  106. // Declare helper structs ("data transfer objects" = DTO) to utilize parsing a flattened pump history
  107. struct BolusDTO: Codable {
  108. var id: String
  109. var timestamp: String
  110. var amount: Double
  111. var isExternal: Bool
  112. var isSMB: Bool
  113. var duration: Int
  114. var _type: String = "Bolus"
  115. }
  116. struct TempBasalDTO: Codable {
  117. var id: String
  118. var timestamp: String
  119. var temp: String
  120. var rate: Double
  121. var _type: String = "TempBasal"
  122. }
  123. struct TempBasalDurationDTO: Codable {
  124. var id: String
  125. var timestamp: String
  126. var duration: Int
  127. var _type: String = "TempBasalDuration"
  128. private enum CodingKeys: String, CodingKey {
  129. case id
  130. case timestamp
  131. case duration = "duration (min)"
  132. case _type
  133. }
  134. }
  135. // Mask distinct DTO subtypes with a common enum that conforms to Encodable
  136. enum PumpEventDTO: Encodable {
  137. case bolus(BolusDTO)
  138. case tempBasal(TempBasalDTO)
  139. case tempBasalDuration(TempBasalDurationDTO)
  140. func encode(to encoder: Encoder) throws {
  141. switch self {
  142. case let .bolus(bolus):
  143. try bolus.encode(to: encoder)
  144. case let .tempBasal(tempBasal):
  145. try tempBasal.encode(to: encoder)
  146. case let .tempBasalDuration(tempBasalDuration):
  147. try tempBasalDuration.encode(to: encoder)
  148. }
  149. }
  150. }
  151. // Extension with helper functions to map pump events to DTO objects via uniform masking enum
  152. extension PumpEventStored {
  153. static let dateFormatter: ISO8601DateFormatter = {
  154. let formatter = ISO8601DateFormatter()
  155. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  156. return formatter
  157. }()
  158. func toBolusDTOEnum() -> PumpEventDTO? {
  159. guard let timestamp = timestamp, let bolus = bolus, let amount = bolus.amount else {
  160. return nil
  161. }
  162. let bolusDTO = BolusDTO(
  163. id: id ?? UUID().uuidString,
  164. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  165. amount: amount.doubleValue,
  166. isExternal: bolus.isExternal,
  167. isSMB: bolus.isSMB,
  168. duration: 0
  169. )
  170. return .bolus(bolusDTO)
  171. }
  172. func toTempBasalDTOEnum() -> PumpEventDTO? {
  173. guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal, let rate = tempBasal.rate else {
  174. return nil
  175. }
  176. let tempBasalDTO = TempBasalDTO(
  177. id: "_\(id)",
  178. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  179. temp: tempBasal.tempType ?? "unknown",
  180. rate: rate.doubleValue
  181. )
  182. return .tempBasal(tempBasalDTO)
  183. }
  184. func toTempBasalDurationDTOEnum() -> PumpEventDTO? {
  185. guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal else {
  186. return nil
  187. }
  188. let tempBasalDurationDTO = TempBasalDurationDTO(
  189. id: id,
  190. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  191. duration: Int(tempBasal.duration)
  192. )
  193. return .tempBasalDuration(tempBasalDurationDTO)
  194. }
  195. }