PumpEvent+helper.swift 10 KB

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