PumpHistoryStorage.swift 23 KB

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