PumpEvent+helper.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 = EventType.bolus.rawValue
  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 = EventType.tempBasal.rawValue
  122. }
  123. struct TempBasalDurationDTO: Codable {
  124. var id: String
  125. var timestamp: String
  126. var duration: Int
  127. var _type: String = EventType.tempBasalDuration.rawValue
  128. private enum CodingKeys: String, CodingKey {
  129. case id
  130. case timestamp
  131. case duration = "duration (min)"
  132. case _type
  133. }
  134. }
  135. struct SuspendDTO: Codable {
  136. var id: String
  137. var timestamp: String
  138. var _type: String = EventType.pumpSuspend.rawValue
  139. }
  140. struct ResumeDTO: Codable {
  141. var id: String
  142. var timestamp: String
  143. var _type: String = EventType.pumpResume.rawValue
  144. }
  145. struct RewindDTO: Codable {
  146. var id: String
  147. var timestamp: String
  148. var _type: String = EventType.rewind.rawValue
  149. }
  150. struct PrimeDTO: Codable {
  151. var id: String
  152. var timestamp: String
  153. var _type: String = EventType.prime.rawValue
  154. }
  155. // Mask distinct DTO subtypes with a common enum that conforms to Encodable
  156. enum PumpEventDTO: Encodable {
  157. case bolus(BolusDTO)
  158. case tempBasal(TempBasalDTO)
  159. case tempBasalDuration(TempBasalDurationDTO)
  160. case suspend(SuspendDTO)
  161. case resume(ResumeDTO)
  162. case rewind(RewindDTO)
  163. case prime(PrimeDTO)
  164. func encode(to encoder: Encoder) throws {
  165. switch self {
  166. case let .bolus(bolus):
  167. try bolus.encode(to: encoder)
  168. case let .tempBasal(tempBasal):
  169. try tempBasal.encode(to: encoder)
  170. case let .tempBasalDuration(tempBasalDuration):
  171. try tempBasalDuration.encode(to: encoder)
  172. case let .suspend(suspend):
  173. try suspend.encode(to: encoder)
  174. case let .resume(resume):
  175. try resume.encode(to: encoder)
  176. case let .rewind(rewind):
  177. try rewind.encode(to: encoder)
  178. case let .prime(prime):
  179. try prime.encode(to: encoder)
  180. }
  181. }
  182. }
  183. // Extension with helper functions to map pump events to DTO objects via uniform masking enum
  184. extension PumpEventStored {
  185. static let dateFormatter: ISO8601DateFormatter = {
  186. let formatter = ISO8601DateFormatter()
  187. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  188. return formatter
  189. }()
  190. func toBolusDTOEnum() -> PumpEventDTO? {
  191. guard let timestamp = timestamp, let bolus = bolus, let amount = bolus.amount else {
  192. return nil
  193. }
  194. let bolusDTO = BolusDTO(
  195. id: id ?? UUID().uuidString,
  196. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  197. amount: amount.doubleValue,
  198. isExternal: bolus.isExternal,
  199. isSMB: bolus.isSMB,
  200. duration: 0
  201. )
  202. return .bolus(bolusDTO)
  203. }
  204. func toTempBasalDTOEnum() -> PumpEventDTO? {
  205. guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal, let rate = tempBasal.rate else {
  206. return nil
  207. }
  208. let tempBasalDTO = TempBasalDTO(
  209. id: "_\(id)",
  210. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  211. temp: tempBasal.tempType ?? "unknown",
  212. rate: rate.doubleValue
  213. )
  214. return .tempBasal(tempBasalDTO)
  215. }
  216. func toTempBasalDurationDTOEnum() -> PumpEventDTO? {
  217. guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal else {
  218. return nil
  219. }
  220. let tempBasalDurationDTO = TempBasalDurationDTO(
  221. id: id,
  222. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  223. duration: Int(tempBasal.duration)
  224. )
  225. return .tempBasalDuration(tempBasalDurationDTO)
  226. }
  227. func toPumpSuspendDTO() -> PumpEventDTO? {
  228. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.pumpSuspend.rawValue else {
  229. return nil
  230. }
  231. let suspendDTO = SuspendDTO(
  232. id: id,
  233. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  234. )
  235. return .suspend(suspendDTO)
  236. }
  237. func toPumpResumeDTO() -> PumpEventDTO? {
  238. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.pumpResume.rawValue else {
  239. return nil
  240. }
  241. let resumeDTO = ResumeDTO(
  242. id: id,
  243. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  244. )
  245. return .resume(resumeDTO)
  246. }
  247. func toRewindDTO() -> PumpEventDTO? {
  248. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.rewind.rawValue else {
  249. return nil
  250. }
  251. let rewindDTO = RewindDTO(
  252. id: id,
  253. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  254. )
  255. return .rewind(rewindDTO)
  256. }
  257. func toPrimeDTO() -> PumpEventDTO? {
  258. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.prime.rawValue else {
  259. return nil
  260. }
  261. let primeDTO = PrimeDTO(
  262. id: id,
  263. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  264. )
  265. return .prime(primeDTO)
  266. }
  267. }