PumpEvent+helper.swift 9.9 KB

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