PumpEvent+helper.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 pumpHistoryForStats: NSPredicate {
  82. let date = Date.threeMonthsAgo
  83. return NSPredicate(format: "pumpEvent.timestamp >= %@", date as NSDate)
  84. }
  85. static var recentPumpHistory: NSPredicate {
  86. let date = Date.twentyMinutesAgo
  87. return NSPredicate(
  88. format: "type == %@ AND timestamp >= %@",
  89. PumpEventStored.EventType.tempBasal.rawValue,
  90. date as NSDate
  91. )
  92. }
  93. static var lastPumpBolus: NSPredicate {
  94. let date = Date.twentyMinutesAgo
  95. return NSPredicate(format: "timestamp >= %@ AND bolus.isExternal == %@", date as NSDate, false as NSNumber)
  96. }
  97. static func duplicateInLastHour(_ date: Date) -> NSPredicate {
  98. let date60m = Date.oneHourAgo
  99. return NSPredicate(format: "timestamp >= %@ && timestamp == %@", date60m as NSDate, date as NSDate)
  100. }
  101. static var pumpEventsNotYetUploadedToNightscout: NSPredicate {
  102. let date = Date.oneDayAgo
  103. return NSPredicate(format: "timestamp >= %@ AND isUploadedToNS == %@", date as NSDate, false as NSNumber)
  104. }
  105. static var pumpEventsNotYetUploadedToHealth: NSPredicate {
  106. let date = Date.oneDayAgo
  107. return NSPredicate(format: "timestamp >= %@ AND isUploadedToHealth == %@", date as NSDate, false as NSNumber)
  108. }
  109. static var pumpEventsNotYetUploadedToTidepool: NSPredicate {
  110. let date = Date.oneDayAgo
  111. return NSPredicate(format: "timestamp >= %@ AND isUploadedToTidepool == %@", date as NSDate, false as NSNumber)
  112. }
  113. }
  114. // Declare helper structs ("data transfer objects" = DTO) to utilize parsing a flattened pump history
  115. struct BolusDTO: Codable {
  116. var id: String
  117. var timestamp: String
  118. var amount: Double
  119. var isExternal: Bool
  120. var isSMB: Bool
  121. var duration: Int
  122. var _type: String = EventType.bolus.rawValue
  123. }
  124. struct TempBasalDTO: Codable {
  125. var id: String
  126. var timestamp: String
  127. var temp: String
  128. var rate: Double
  129. var _type: String = EventType.tempBasal.rawValue
  130. }
  131. struct TempBasalDurationDTO: Codable {
  132. var id: String
  133. var timestamp: String
  134. var duration: Int
  135. var _type: String = EventType.tempBasalDuration.rawValue
  136. private enum CodingKeys: String, CodingKey {
  137. case id
  138. case timestamp
  139. case duration = "duration (min)"
  140. case _type
  141. }
  142. }
  143. struct SuspendDTO: Codable {
  144. var id: String
  145. var timestamp: String
  146. var _type: String = EventType.pumpSuspend.rawValue
  147. }
  148. struct ResumeDTO: Codable {
  149. var id: String
  150. var timestamp: String
  151. var _type: String = EventType.pumpResume.rawValue
  152. }
  153. struct RewindDTO: Codable {
  154. var id: String
  155. var timestamp: String
  156. var _type: String = EventType.rewind.rawValue
  157. }
  158. struct PrimeDTO: Codable {
  159. var id: String
  160. var timestamp: String
  161. var _type: String = EventType.prime.rawValue
  162. }
  163. // Mask distinct DTO subtypes with a common enum that conforms to Encodable
  164. enum PumpEventDTO: Encodable {
  165. case bolus(BolusDTO)
  166. case tempBasal(TempBasalDTO)
  167. case tempBasalDuration(TempBasalDurationDTO)
  168. case suspend(SuspendDTO)
  169. case resume(ResumeDTO)
  170. case rewind(RewindDTO)
  171. case prime(PrimeDTO)
  172. func encode(to encoder: Encoder) throws {
  173. switch self {
  174. case let .bolus(bolus):
  175. try bolus.encode(to: encoder)
  176. case let .tempBasal(tempBasal):
  177. try tempBasal.encode(to: encoder)
  178. case let .tempBasalDuration(tempBasalDuration):
  179. try tempBasalDuration.encode(to: encoder)
  180. case let .suspend(suspend):
  181. try suspend.encode(to: encoder)
  182. case let .resume(resume):
  183. try resume.encode(to: encoder)
  184. case let .rewind(rewind):
  185. try rewind.encode(to: encoder)
  186. case let .prime(prime):
  187. try prime.encode(to: encoder)
  188. }
  189. }
  190. }
  191. // Extension with helper functions to map pump events to DTO objects via uniform masking enum
  192. extension PumpEventStored {
  193. static let dateFormatter: ISO8601DateFormatter = {
  194. let formatter = ISO8601DateFormatter()
  195. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  196. return formatter
  197. }()
  198. func toBolusDTOEnum() -> PumpEventDTO? {
  199. guard let timestamp = timestamp, let bolus = bolus, let amount = bolus.amount else {
  200. return nil
  201. }
  202. let bolusDTO = BolusDTO(
  203. id: id ?? UUID().uuidString,
  204. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  205. amount: amount.doubleValue,
  206. isExternal: bolus.isExternal,
  207. isSMB: bolus.isSMB,
  208. duration: 0
  209. )
  210. return .bolus(bolusDTO)
  211. }
  212. func toTempBasalDTOEnum() -> PumpEventDTO? {
  213. guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal, let rate = tempBasal.rate else {
  214. return nil
  215. }
  216. let tempBasalDTO = TempBasalDTO(
  217. id: "_\(id)",
  218. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  219. temp: tempBasal.tempType ?? "unknown",
  220. rate: rate.doubleValue
  221. )
  222. return .tempBasal(tempBasalDTO)
  223. }
  224. func toTempBasalDurationDTOEnum() -> PumpEventDTO? {
  225. guard let id = id, let timestamp = timestamp, let tempBasal = tempBasal else {
  226. return nil
  227. }
  228. let tempBasalDurationDTO = TempBasalDurationDTO(
  229. id: id,
  230. timestamp: PumpEventStored.dateFormatter.string(from: timestamp),
  231. duration: Int(tempBasal.duration)
  232. )
  233. return .tempBasalDuration(tempBasalDurationDTO)
  234. }
  235. func toPumpSuspendDTO() -> PumpEventDTO? {
  236. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.pumpSuspend.rawValue else {
  237. return nil
  238. }
  239. let suspendDTO = SuspendDTO(
  240. id: id,
  241. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  242. )
  243. return .suspend(suspendDTO)
  244. }
  245. func toPumpResumeDTO() -> PumpEventDTO? {
  246. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.pumpResume.rawValue else {
  247. return nil
  248. }
  249. let resumeDTO = ResumeDTO(
  250. id: id,
  251. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  252. )
  253. return .resume(resumeDTO)
  254. }
  255. func toRewindDTO() -> PumpEventDTO? {
  256. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.rewind.rawValue else {
  257. return nil
  258. }
  259. let rewindDTO = RewindDTO(
  260. id: id,
  261. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  262. )
  263. return .rewind(rewindDTO)
  264. }
  265. func toPrimeDTO() -> PumpEventDTO? {
  266. guard let id = id, let timestamp = timestamp, let type = type, type == EventType.prime.rawValue else {
  267. return nil
  268. }
  269. let primeDTO = PrimeDTO(
  270. id: id,
  271. timestamp: PumpEventStored.dateFormatter.string(from: timestamp)
  272. )
  273. return .prime(primeDTO)
  274. }
  275. }