PumpEvent+helper.swift 10.0 KB

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