PumpHistoryStorage.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKit
  5. import SwiftDate
  6. import Swinject
  7. protocol PumpHistoryObserver {
  8. func pumpHistoryDidUpdate(_ events: [PumpHistoryEvent])
  9. }
  10. protocol PumpHistoryStorage {
  11. var updatePublisher: AnyPublisher<Void, Never> { get }
  12. func getPumpHistory() async throws -> [PumpHistoryEvent]
  13. func storePumpEvents(_ events: [NewPumpEvent]) async throws
  14. func storeExternalInsulinEvent(amount: Decimal, timestamp: Date) async
  15. func getPumpHistoryNotYetUploadedToNightscout() async throws -> [NightscoutTreatment]
  16. func getPumpHistoryNotYetUploadedToHealth() async throws -> [PumpHistoryEvent]
  17. func getPumpHistoryNotYetUploadedToTidepool() async throws -> [PumpHistoryEvent]
  18. }
  19. final class BasePumpHistoryStorage: PumpHistoryStorage, Injectable {
  20. private let processQueue = DispatchQueue(label: "BasePumpHistoryStorage.processQueue")
  21. @Injected() private var storage: FileStorage!
  22. @Injected() private var broadcaster: Broadcaster!
  23. @Injected() private var settings: SettingsManager!
  24. private let updateSubject = PassthroughSubject<Void, Never>()
  25. private let context = CoreDataStack.shared.newTaskContext()
  26. var updatePublisher: AnyPublisher<Void, Never> {
  27. updateSubject.eraseToAnyPublisher()
  28. }
  29. init(resolver: Resolver) {
  30. injectServices(resolver)
  31. }
  32. typealias PumpEvent = PumpEventStored.EventType
  33. typealias TempType = PumpEventStored.TempType
  34. private func roundDose(_ dose: Double, toIncrement increment: Double) -> Decimal {
  35. let roundedValue = (dose / increment).rounded() * increment
  36. return Decimal(roundedValue)
  37. }
  38. func storePumpEvents(_ events: [NewPumpEvent]) async throws {
  39. try await context.perform {
  40. for event in events {
  41. let existingEvents: [PumpEventStored] = try CoreDataStack.shared.fetchEntities(
  42. ofType: PumpEventStored.self,
  43. onContext: self.context,
  44. predicate: NSPredicate.duplicateInLastHour(event.date),
  45. key: "timestamp",
  46. ascending: false,
  47. batchSize: 50
  48. ) as? [PumpEventStored] ?? []
  49. switch event.type {
  50. case .bolus:
  51. guard let dose = event.dose else { continue }
  52. let amount = self.roundDose(
  53. dose.unitsInDeliverableIncrements,
  54. toIncrement: Double(self.settings.preferences.bolusIncrement)
  55. )
  56. guard existingEvents.isEmpty else {
  57. // Duplicate found, do not store the event
  58. print("Duplicate event found with timestamp: \(event.date)")
  59. if let existingEvent = existingEvents.first(where: { $0.type == EventType.bolus.rawValue }) {
  60. if existingEvent.timestamp == event.date {
  61. if let existingAmount = existingEvent.bolus?.amount, amount < existingAmount as Decimal {
  62. // Update existing event with new smaller value
  63. existingEvent.bolus?.amount = amount as NSDecimalNumber
  64. existingEvent.bolus?.isSMB = dose.automatic ?? true
  65. existingEvent.isUploadedToNS = false
  66. existingEvent.isUploadedToHealth = false
  67. existingEvent.isUploadedToTidepool = false
  68. print("Updated existing event with smaller value: \(amount)")
  69. }
  70. }
  71. }
  72. continue
  73. }
  74. let newPumpEvent = PumpEventStored(context: self.context)
  75. newPumpEvent.id = UUID().uuidString
  76. // restrict entry to now or past
  77. newPumpEvent.timestamp = event.date > Date() ? Date() : event.date
  78. newPumpEvent.type = PumpEvent.bolus.rawValue
  79. newPumpEvent.isUploadedToNS = false
  80. newPumpEvent.isUploadedToHealth = false
  81. newPumpEvent.isUploadedToTidepool = false
  82. let newBolusEntry = BolusStored(context: self.context)
  83. newBolusEntry.pumpEvent = newPumpEvent
  84. newBolusEntry.amount = NSDecimalNumber(decimal: amount)
  85. newBolusEntry.isExternal = dose.manuallyEntered
  86. newBolusEntry.isSMB = dose.automatic ?? true
  87. case .tempBasal:
  88. guard let dose = event.dose else { continue }
  89. guard existingEvents.isEmpty else {
  90. // Duplicate found, do not store the event
  91. print("Duplicate event found with timestamp: \(event.date)")
  92. continue
  93. }
  94. let rate = Decimal(dose.unitsPerHour)
  95. let minutes = (dose.endDate - dose.startDate).timeInterval / 60
  96. let delivered = dose.deliveredUnits
  97. let date = event.date
  98. let isCancel = delivered != nil
  99. guard !isCancel else { continue }
  100. let newPumpEvent = PumpEventStored(context: self.context)
  101. newPumpEvent.id = UUID().uuidString
  102. newPumpEvent.timestamp = date
  103. newPumpEvent.type = PumpEvent.tempBasal.rawValue
  104. newPumpEvent.isUploadedToNS = false
  105. newPumpEvent.isUploadedToHealth = false
  106. newPumpEvent.isUploadedToTidepool = false
  107. let newTempBasal = TempBasalStored(context: self.context)
  108. newTempBasal.pumpEvent = newPumpEvent
  109. newTempBasal.duration = Int16(round(minutes))
  110. newTempBasal.rate = rate as NSDecimalNumber
  111. newTempBasal.tempType = TempType.absolute.rawValue
  112. case .suspend:
  113. guard existingEvents.isEmpty else {
  114. // Duplicate found, do not store the event
  115. print("Duplicate event found with timestamp: \(event.date)")
  116. continue
  117. }
  118. let newPumpEvent = PumpEventStored(context: self.context)
  119. newPumpEvent.id = UUID().uuidString
  120. newPumpEvent.timestamp = event.date
  121. newPumpEvent.type = PumpEvent.pumpSuspend.rawValue
  122. newPumpEvent.isUploadedToNS = false
  123. newPumpEvent.isUploadedToHealth = false
  124. newPumpEvent.isUploadedToTidepool = false
  125. case .resume:
  126. guard existingEvents.isEmpty else {
  127. // Duplicate found, do not store the event
  128. print("Duplicate event found with timestamp: \(event.date)")
  129. continue
  130. }
  131. let newPumpEvent = PumpEventStored(context: self.context)
  132. newPumpEvent.id = UUID().uuidString
  133. newPumpEvent.timestamp = event.date
  134. newPumpEvent.type = PumpEvent.pumpResume.rawValue
  135. newPumpEvent.isUploadedToNS = false
  136. newPumpEvent.isUploadedToHealth = false
  137. newPumpEvent.isUploadedToTidepool = false
  138. case .rewind:
  139. guard existingEvents.isEmpty else {
  140. // Duplicate found, do not store the event
  141. print("Duplicate event found with timestamp: \(event.date)")
  142. continue
  143. }
  144. let newPumpEvent = PumpEventStored(context: self.context)
  145. newPumpEvent.id = UUID().uuidString
  146. newPumpEvent.timestamp = event.date
  147. newPumpEvent.type = PumpEvent.rewind.rawValue
  148. newPumpEvent.isUploadedToNS = false
  149. newPumpEvent.isUploadedToHealth = false
  150. newPumpEvent.isUploadedToTidepool = false
  151. case .prime:
  152. guard existingEvents.isEmpty else {
  153. // Duplicate found, do not store the event
  154. print("Duplicate event found with timestamp: \(event.date)")
  155. continue
  156. }
  157. let newPumpEvent = PumpEventStored(context: self.context)
  158. newPumpEvent.id = UUID().uuidString
  159. newPumpEvent.timestamp = event.date
  160. newPumpEvent.type = PumpEvent.prime.rawValue
  161. newPumpEvent.isUploadedToNS = false
  162. newPumpEvent.isUploadedToHealth = false
  163. newPumpEvent.isUploadedToTidepool = false
  164. case .alarm:
  165. guard existingEvents.isEmpty else {
  166. // Duplicate found, do not store the event
  167. print("Duplicate event found with timestamp: \(event.date)")
  168. continue
  169. }
  170. let newPumpEvent = PumpEventStored(context: self.context)
  171. newPumpEvent.id = UUID().uuidString
  172. newPumpEvent.timestamp = event.date
  173. newPumpEvent.type = PumpEvent.pumpAlarm.rawValue
  174. newPumpEvent.isUploadedToNS = false
  175. newPumpEvent.isUploadedToHealth = false
  176. newPumpEvent.isUploadedToTidepool = false
  177. newPumpEvent.note = event.title
  178. default:
  179. continue
  180. }
  181. }
  182. do {
  183. guard self.context.hasChanges else { return }
  184. try self.context.save()
  185. self.updateSubject.send(())
  186. debugPrint("\(DebuggingIdentifiers.succeeded) stored pump events in Core Data")
  187. } catch let error as NSError {
  188. debugPrint("\(DebuggingIdentifiers.failed) failed to store pump events with error: \(error.userInfo)")
  189. throw error
  190. }
  191. }
  192. }
  193. func storeExternalInsulinEvent(amount: Decimal, timestamp: Date) async {
  194. debug(.default, "External insulin saved")
  195. await context.perform {
  196. // create pump event
  197. let newPumpEvent = PumpEventStored(context: self.context)
  198. newPumpEvent.id = UUID().uuidString
  199. // restrict entry to now or past
  200. newPumpEvent.timestamp = timestamp > Date() ? Date() : timestamp
  201. newPumpEvent.type = PumpEvent.bolus.rawValue
  202. newPumpEvent.isUploadedToNS = false
  203. newPumpEvent.isUploadedToHealth = false
  204. newPumpEvent.isUploadedToTidepool = false
  205. // create bolus entry and specify relationship to pump event
  206. let newBolusEntry = BolusStored(context: self.context)
  207. newBolusEntry.pumpEvent = newPumpEvent
  208. newBolusEntry.amount = amount as NSDecimalNumber
  209. newBolusEntry.isExternal = true // we are creating an external dose
  210. newBolusEntry.isSMB = false // the dose is manually administered
  211. do {
  212. guard self.context.hasChanges else { return }
  213. try self.context.save()
  214. self.updateSubject.send(())
  215. } catch {
  216. print(error.localizedDescription)
  217. }
  218. }
  219. }
  220. func getPumpHistory() async throws -> [PumpHistoryEvent] {
  221. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  222. ofType: PumpEventStored.self,
  223. onContext: context,
  224. predicate: NSPredicate.pumpHistoryLast24h,
  225. key: "timestamp",
  226. ascending: false,
  227. fetchLimit: 288
  228. )
  229. return await context.perform {
  230. guard let fetchedPumpEvents = results as? [PumpEventStored] else { return [] }
  231. return fetchedPumpEvents.map { event in
  232. switch event.type {
  233. case PumpEventStored.EventType.bolus.rawValue:
  234. return PumpHistoryEvent(
  235. id: event.id ?? UUID().uuidString,
  236. type: .bolus,
  237. timestamp: event.timestamp ?? Date(),
  238. amount: event.bolus?.amount as Decimal?
  239. )
  240. case PumpEventStored.EventType.tempBasal.rawValue:
  241. return PumpHistoryEvent(
  242. id: event.id ?? UUID().uuidString,
  243. type: .tempBasal,
  244. timestamp: event.timestamp ?? Date(),
  245. amount: event.tempBasal?.rate as Decimal?,
  246. duration: Int(event.tempBasal?.duration ?? 0)
  247. )
  248. default:
  249. return nil
  250. }
  251. }.compactMap { $0 }
  252. }
  253. }
  254. func determineBolusEventType(for event: PumpEventStored) -> PumpEventStored.EventType {
  255. if event.bolus!.isSMB {
  256. return .smb
  257. }
  258. if event.bolus!.isExternal {
  259. return .isExternal
  260. }
  261. return PumpEventStored.EventType(rawValue: event.type!) ?? PumpEventStored.EventType.bolus
  262. }
  263. func getPumpHistoryNotYetUploadedToNightscout() async throws -> [NightscoutTreatment] {
  264. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  265. ofType: PumpEventStored.self,
  266. onContext: context,
  267. predicate: NSPredicate.pumpEventsNotYetUploadedToNightscout,
  268. key: "timestamp",
  269. ascending: false
  270. )
  271. return try await context.perform { [self] in
  272. guard let fetchedPumpEvents = results as? [PumpEventStored] else {
  273. throw CoreDataError.fetchError(function: #function, file: #file)
  274. }
  275. return fetchedPumpEvents.map { event in
  276. switch event.type {
  277. case PumpEvent.bolus.rawValue:
  278. // eventType determines whether bolus is external, smb or manual (=administered via app by user)
  279. let eventType = determineBolusEventType(for: event)
  280. return NightscoutTreatment(
  281. duration: nil,
  282. rawDuration: nil,
  283. rawRate: nil,
  284. absolute: nil,
  285. rate: nil,
  286. eventType: eventType,
  287. createdAt: event.timestamp,
  288. enteredBy: NightscoutTreatment.local,
  289. bolus: nil,
  290. insulin: event.bolus?.amount as Decimal?,
  291. notes: nil,
  292. carbs: nil,
  293. fat: nil,
  294. protein: nil,
  295. targetTop: nil,
  296. targetBottom: nil,
  297. id: event.id
  298. )
  299. case PumpEvent.tempBasal.rawValue:
  300. return NightscoutTreatment(
  301. duration: Int(event.tempBasal?.duration ?? 0),
  302. rawDuration: nil,
  303. rawRate: nil,
  304. absolute: event.tempBasal?.rate as Decimal?,
  305. rate: event.tempBasal?.rate as Decimal?,
  306. eventType: .nsTempBasal,
  307. createdAt: event.timestamp,
  308. enteredBy: NightscoutTreatment.local,
  309. bolus: nil,
  310. insulin: nil,
  311. notes: nil,
  312. carbs: nil,
  313. fat: nil,
  314. protein: nil,
  315. targetTop: nil,
  316. targetBottom: nil,
  317. id: event.id
  318. )
  319. case PumpEvent.pumpSuspend.rawValue:
  320. return NightscoutTreatment(
  321. duration: nil,
  322. rawDuration: nil,
  323. rawRate: nil,
  324. absolute: nil,
  325. rate: nil,
  326. eventType: .nsNote,
  327. createdAt: event.timestamp,
  328. enteredBy: NightscoutTreatment.local,
  329. bolus: nil,
  330. insulin: nil,
  331. notes: PumpEvent.pumpSuspend.rawValue,
  332. carbs: nil,
  333. fat: nil,
  334. protein: nil,
  335. targetTop: nil,
  336. targetBottom: nil
  337. )
  338. case PumpEvent.pumpResume.rawValue:
  339. return NightscoutTreatment(
  340. duration: nil,
  341. rawDuration: nil,
  342. rawRate: nil,
  343. absolute: nil,
  344. rate: nil,
  345. eventType: .nsNote,
  346. createdAt: event.timestamp,
  347. enteredBy: NightscoutTreatment.local,
  348. bolus: nil,
  349. insulin: nil,
  350. notes: PumpEvent.pumpResume.rawValue,
  351. carbs: nil,
  352. fat: nil,
  353. protein: nil,
  354. targetTop: nil,
  355. targetBottom: nil
  356. )
  357. case PumpEvent.rewind.rawValue:
  358. return NightscoutTreatment(
  359. duration: nil,
  360. rawDuration: nil,
  361. rawRate: nil,
  362. absolute: nil,
  363. rate: nil,
  364. eventType: .nsInsulinChange,
  365. createdAt: event.timestamp,
  366. enteredBy: NightscoutTreatment.local,
  367. bolus: nil,
  368. insulin: nil,
  369. notes: nil,
  370. carbs: nil,
  371. fat: nil,
  372. protein: nil,
  373. targetTop: nil,
  374. targetBottom: nil
  375. )
  376. case PumpEvent.prime.rawValue:
  377. return NightscoutTreatment(
  378. duration: nil,
  379. rawDuration: nil,
  380. rawRate: nil,
  381. absolute: nil,
  382. rate: nil,
  383. eventType: .nsSiteChange,
  384. createdAt: event.timestamp,
  385. enteredBy: NightscoutTreatment.local,
  386. bolus: nil,
  387. insulin: nil,
  388. notes: nil,
  389. carbs: nil,
  390. fat: nil,
  391. protein: nil,
  392. targetTop: nil,
  393. targetBottom: nil
  394. )
  395. case PumpEvent.pumpAlarm.rawValue:
  396. return NightscoutTreatment(
  397. duration: 30, // minutes
  398. rawDuration: nil,
  399. rawRate: nil,
  400. absolute: nil,
  401. rate: nil,
  402. eventType: .nsAnnouncement,
  403. createdAt: event.timestamp,
  404. enteredBy: NightscoutTreatment.local,
  405. bolus: nil,
  406. insulin: nil,
  407. notes: "Alarm \(String(describing: event.note)) \(PumpEvent.pumpAlarm.rawValue)",
  408. carbs: nil,
  409. fat: nil,
  410. protein: nil,
  411. targetTop: nil,
  412. targetBottom: nil
  413. )
  414. default:
  415. return nil
  416. }
  417. }.compactMap { $0 }
  418. }
  419. }
  420. func getPumpHistoryNotYetUploadedToHealth() async throws -> [PumpHistoryEvent] {
  421. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  422. ofType: PumpEventStored.self,
  423. onContext: context,
  424. predicate: NSPredicate.pumpEventsNotYetUploadedToHealth,
  425. key: "timestamp",
  426. ascending: false
  427. )
  428. return try await context.perform {
  429. guard let fetchedPumpEvents = results as? [PumpEventStored] else {
  430. throw CoreDataError.fetchError(function: #function, file: #file)
  431. }
  432. return fetchedPumpEvents.map { event in
  433. switch event.type {
  434. case PumpEvent.bolus.rawValue:
  435. return PumpHistoryEvent(
  436. id: event.id ?? UUID().uuidString,
  437. type: .bolus,
  438. timestamp: event.timestamp ?? Date(),
  439. amount: event.bolus?.amount as Decimal?
  440. )
  441. case PumpEvent.tempBasal.rawValue:
  442. if let id = event.id, let timestamp = event.timestamp, let tempBasal = event.tempBasal,
  443. let tempBasalRate = tempBasal.rate
  444. {
  445. return PumpHistoryEvent(
  446. id: id,
  447. type: .tempBasal,
  448. timestamp: timestamp,
  449. amount: tempBasalRate as Decimal,
  450. duration: Int(tempBasal.duration)
  451. )
  452. } else {
  453. return nil
  454. }
  455. default:
  456. return nil
  457. }
  458. }.compactMap { $0 }
  459. }
  460. }
  461. func getPumpHistoryNotYetUploadedToTidepool() async throws -> [PumpHistoryEvent] {
  462. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  463. ofType: PumpEventStored.self,
  464. onContext: context,
  465. predicate: NSPredicate.pumpEventsNotYetUploadedToTidepool,
  466. key: "timestamp",
  467. ascending: false
  468. )
  469. return try await context.perform {
  470. guard let fetchedPumpEvents = results as? [PumpEventStored] else {
  471. throw CoreDataError.fetchError(function: #function, file: #file)
  472. }
  473. return fetchedPumpEvents.map { event in
  474. switch event.type {
  475. case PumpEvent.bolus.rawValue:
  476. return PumpHistoryEvent(
  477. id: event.id ?? UUID().uuidString,
  478. type: .bolus,
  479. timestamp: event.timestamp ?? Date(),
  480. amount: event.bolus?.amount as Decimal?,
  481. isSMB: event.bolus?.isSMB ?? true,
  482. isExternal: event.bolus?.isExternal ?? false
  483. )
  484. case PumpEvent.tempBasal.rawValue:
  485. if let id = event.id, let timestamp = event.timestamp, let tempBasal = event.tempBasal,
  486. let tempBasalRate = tempBasal.rate
  487. {
  488. return PumpHistoryEvent(
  489. id: id,
  490. type: .tempBasal,
  491. timestamp: timestamp,
  492. amount: tempBasalRate as Decimal,
  493. duration: Int(tempBasal.duration)
  494. )
  495. } else {
  496. return nil
  497. }
  498. default:
  499. return nil
  500. }
  501. }.compactMap { $0 }
  502. }
  503. }
  504. }