PumpHistoryStorage.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import Foundation
  2. import LoopKit
  3. import SwiftDate
  4. import Swinject
  5. protocol PumpHistoryObserver {
  6. func pumpHistoryDidUpdate(_ events: [PumpHistoryEvent])
  7. }
  8. protocol PumpHistoryStorage {
  9. func storePumpEvents(_ events: [NewPumpEvent])
  10. func storeEvents(_ events: [PumpHistoryEvent])
  11. func storeJournalCarbs(_ carbs: Int)
  12. func recent() -> [PumpHistoryEvent]
  13. func nightscoutTreatmentsNotUploaded() -> [NightscoutTreatment]
  14. func saveCancelTempEvents()
  15. func deleteInsulin(at date: Date)
  16. }
  17. final class BasePumpHistoryStorage: PumpHistoryStorage, Injectable {
  18. private let processQueue = DispatchQueue(label: "BasePumpHistoryStorage.processQueue")
  19. @Injected() private var storage: FileStorage!
  20. @Injected() private var broadcaster: Broadcaster!
  21. init(resolver: Resolver) {
  22. injectServices(resolver)
  23. }
  24. func storePumpEvents(_ events: [NewPumpEvent]) {
  25. processQueue.async {
  26. let eventsToStore = events.flatMap { event -> [PumpHistoryEvent] in
  27. let id = event.raw.md5String
  28. switch event.type {
  29. case .bolus:
  30. guard let dose = event.dose else { return [] }
  31. let amount = Decimal(string: dose.unitsInDeliverableIncrements.description)
  32. let minutes = Int((dose.endDate - dose.startDate).timeInterval / 60)
  33. return [PumpHistoryEvent(
  34. id: id,
  35. type: .bolus,
  36. timestamp: event.date,
  37. amount: amount,
  38. duration: minutes,
  39. durationMin: nil,
  40. rate: nil,
  41. temp: nil,
  42. carbInput: nil,
  43. isSMB: dose.automatic,
  44. isExternalInsulin: dose.manuallyEntered
  45. )]
  46. case .tempBasal:
  47. guard let dose = event.dose else { return [] }
  48. let rate = Decimal(dose.unitsPerHour)
  49. let minutes = (dose.endDate - dose.startDate).timeInterval / 60
  50. let delivered = dose.deliveredUnits
  51. let date = event.date
  52. let isCancel = delivered != nil //! event.isMutable && delivered != nil
  53. guard !isCancel else { return [] }
  54. return [
  55. PumpHistoryEvent(
  56. id: id,
  57. type: .tempBasalDuration,
  58. timestamp: date,
  59. amount: nil,
  60. duration: nil,
  61. durationMin: Int(round(minutes)),
  62. rate: nil,
  63. temp: nil,
  64. carbInput: nil
  65. ),
  66. PumpHistoryEvent(
  67. id: "_" + id,
  68. type: .tempBasal,
  69. timestamp: date,
  70. amount: nil,
  71. duration: nil,
  72. durationMin: nil,
  73. rate: rate,
  74. temp: .absolute,
  75. carbInput: nil
  76. )
  77. ]
  78. case .suspend:
  79. return [
  80. PumpHistoryEvent(
  81. id: id,
  82. type: .pumpSuspend,
  83. timestamp: event.date,
  84. amount: nil,
  85. duration: nil,
  86. durationMin: nil,
  87. rate: nil,
  88. temp: nil,
  89. carbInput: nil
  90. )
  91. ]
  92. case .resume:
  93. return [
  94. PumpHistoryEvent(
  95. id: id,
  96. type: .pumpResume,
  97. timestamp: event.date,
  98. amount: nil,
  99. duration: nil,
  100. durationMin: nil,
  101. rate: nil,
  102. temp: nil,
  103. carbInput: nil
  104. )
  105. ]
  106. case .rewind:
  107. return [
  108. PumpHistoryEvent(
  109. id: id,
  110. type: .rewind,
  111. timestamp: event.date,
  112. amount: nil,
  113. duration: nil,
  114. durationMin: nil,
  115. rate: nil,
  116. temp: nil,
  117. carbInput: nil
  118. )
  119. ]
  120. case .prime:
  121. return [
  122. PumpHistoryEvent(
  123. id: id,
  124. type: .prime,
  125. timestamp: event.date,
  126. amount: nil,
  127. duration: nil,
  128. durationMin: nil,
  129. rate: nil,
  130. temp: nil,
  131. carbInput: nil
  132. )
  133. ]
  134. case .alarm:
  135. return [
  136. PumpHistoryEvent(
  137. id: id,
  138. type: .pumpAlarm,
  139. timestamp: event.date,
  140. note: event.title
  141. )
  142. ]
  143. default:
  144. return []
  145. }
  146. }
  147. self.storeEvents(eventsToStore)
  148. }
  149. }
  150. func storeJournalCarbs(_ carbs: Int) {
  151. processQueue.async {
  152. let eventsToStore = [
  153. PumpHistoryEvent(
  154. id: UUID().uuidString,
  155. type: .journalCarbs,
  156. timestamp: Date(),
  157. amount: nil,
  158. duration: nil,
  159. durationMin: nil,
  160. rate: nil,
  161. temp: nil,
  162. carbInput: carbs
  163. )
  164. ]
  165. self.storeEvents(eventsToStore)
  166. }
  167. }
  168. func storeEvents(_ events: [PumpHistoryEvent]) {
  169. processQueue.async {
  170. let file = OpenAPS.Monitor.pumpHistory
  171. var uniqEvents: [PumpHistoryEvent] = []
  172. self.storage.transaction { storage in
  173. storage.append(events, to: file, uniqBy: \.id)
  174. uniqEvents = storage.retrieve(file, as: [PumpHistoryEvent].self)?
  175. .filter { $0.timestamp.addingTimeInterval(1.days.timeInterval) > Date() }
  176. .sorted { $0.timestamp > $1.timestamp } ?? []
  177. storage.save(Array(uniqEvents), as: file)
  178. }
  179. self.broadcaster.notify(PumpHistoryObserver.self, on: self.processQueue) {
  180. $0.pumpHistoryDidUpdate(uniqEvents)
  181. }
  182. }
  183. }
  184. func recent() -> [PumpHistoryEvent] {
  185. storage.retrieve(OpenAPS.Monitor.pumpHistory, as: [PumpHistoryEvent].self)?.reversed() ?? []
  186. }
  187. func deleteInsulin(at date: Date) {
  188. processQueue.sync {
  189. var allValues = storage.retrieve(OpenAPS.Monitor.pumpHistory, as: [PumpHistoryEvent].self) ?? []
  190. guard let entryIndex = allValues.firstIndex(where: { $0.timestamp == date }) else {
  191. return
  192. }
  193. allValues.remove(at: entryIndex)
  194. storage.save(allValues, as: OpenAPS.Monitor.pumpHistory)
  195. broadcaster.notify(PumpHistoryObserver.self, on: processQueue) {
  196. $0.pumpHistoryDidUpdate(allValues)
  197. }
  198. }
  199. }
  200. func nightscoutTreatmentsNotUploaded() -> [NightscoutTreatment] {
  201. let events = recent()
  202. guard !events.isEmpty else { return [] }
  203. var treatments: [NightscoutTreatment?] = []
  204. for i in 0 ..< events.count {
  205. let event = events[i]
  206. var nextEvent: PumpHistoryEvent?
  207. if i + 1 < events.count {
  208. nextEvent = events[i + 1]
  209. }
  210. if event.type == .tempBasal, nextEvent?.type == .tempBasalDuration {
  211. treatments.append(NightscoutTreatment(event: event, tempBasalDuration: nextEvent))
  212. } else {
  213. treatments.append(NightscoutTreatment(event: event))
  214. }
  215. }
  216. let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedPumphistory, as: [NightscoutTreatment].self) ?? []
  217. let treatmentsToUpload = Set(treatments.compactMap { $0 }).subtracting(Set(uploaded))
  218. return treatmentsToUpload.sorted { $0.createdAt! > $1.createdAt! }
  219. }
  220. func saveCancelTempEvents() {
  221. let basalID = UUID().uuidString
  222. let date = Date()
  223. let events = [
  224. PumpHistoryEvent(
  225. id: basalID,
  226. type: .tempBasalDuration,
  227. timestamp: date,
  228. amount: nil,
  229. duration: nil,
  230. durationMin: 0,
  231. rate: nil,
  232. temp: nil,
  233. carbInput: nil
  234. ),
  235. PumpHistoryEvent(
  236. id: "_" + basalID,
  237. type: .tempBasal,
  238. timestamp: date,
  239. amount: nil,
  240. duration: nil,
  241. durationMin: nil,
  242. rate: 0,
  243. temp: .absolute,
  244. carbInput: nil
  245. )
  246. ]
  247. storeEvents(events)
  248. }
  249. }
  250. extension NightscoutTreatment {
  251. init?(event: PumpHistoryEvent, tempBasalDuration: PumpHistoryEvent? = nil) {
  252. var basalDurationEvent: PumpHistoryEvent?
  253. if tempBasalDuration != nil, tempBasalDuration?.timestamp == event.timestamp, event.type == .tempBasal,
  254. tempBasalDuration?.type == .tempBasalDuration
  255. {
  256. basalDurationEvent = tempBasalDuration
  257. }
  258. switch event.type {
  259. case .tempBasal:
  260. self.init(
  261. duration: basalDurationEvent?.durationMin,
  262. rawDuration: basalDurationEvent,
  263. rawRate: event,
  264. absolute: event.rate,
  265. rate: event.rate,
  266. eventType: .nsTempBasal,
  267. createdAt: event.timestamp,
  268. enteredBy: NightscoutTreatment.local,
  269. bolus: nil,
  270. insulin: nil,
  271. notes: nil,
  272. carbs: nil,
  273. fat: nil,
  274. protein: nil,
  275. targetTop: nil,
  276. targetBottom: nil
  277. )
  278. case .bolus:
  279. let eventType = determineBolusEventType(for: event)
  280. self.init(
  281. duration: event.duration,
  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: event,
  290. insulin: event.amount,
  291. notes: nil,
  292. carbs: nil,
  293. fat: nil,
  294. protein: nil,
  295. targetTop: nil,
  296. targetBottom: nil
  297. )
  298. case .journalCarbs:
  299. self.init(
  300. duration: nil,
  301. rawDuration: nil,
  302. rawRate: nil,
  303. absolute: nil,
  304. rate: nil,
  305. eventType: .nsCarbCorrection,
  306. createdAt: event.timestamp,
  307. enteredBy: NightscoutTreatment.local,
  308. bolus: nil,
  309. insulin: nil,
  310. notes: nil,
  311. carbs: Decimal(event.carbInput ?? 0),
  312. fat: Decimal(event.fatInput ?? 0),
  313. protein: Decimal(event.proteinInput ?? 0),
  314. targetTop: nil,
  315. targetBottom: nil
  316. )
  317. case .prime:
  318. self.init(
  319. duration: event.duration,
  320. rawDuration: nil,
  321. rawRate: nil,
  322. absolute: nil,
  323. rate: nil,
  324. eventType: .nsSiteChange,
  325. createdAt: event.timestamp,
  326. enteredBy: NightscoutTreatment.local,
  327. bolus: event,
  328. insulin: nil,
  329. notes: nil,
  330. carbs: nil,
  331. fat: nil,
  332. protein: nil,
  333. targetTop: nil,
  334. targetBottom: nil
  335. )
  336. case .rewind:
  337. self.init(
  338. duration: nil,
  339. rawDuration: nil,
  340. rawRate: nil,
  341. absolute: nil,
  342. rate: nil,
  343. eventType: .nsInsulinChange,
  344. createdAt: event.timestamp,
  345. enteredBy: NightscoutTreatment.local,
  346. bolus: nil,
  347. insulin: nil,
  348. notes: nil,
  349. carbs: nil,
  350. fat: nil,
  351. protein: nil,
  352. targetTop: nil,
  353. targetBottom: nil
  354. )
  355. case .pumpAlarm:
  356. self.init(
  357. duration: 30, // minutes
  358. rawDuration: nil,
  359. rawRate: nil,
  360. absolute: nil,
  361. rate: nil,
  362. eventType: .nsAnnouncement,
  363. createdAt: event.timestamp,
  364. enteredBy: NightscoutTreatment.local,
  365. bolus: nil,
  366. insulin: nil,
  367. notes: "Alarm \(String(describing: event.note)) \(event.type)",
  368. carbs: nil,
  369. fat: nil,
  370. protein: nil,
  371. targetTop: nil,
  372. targetBottom: nil
  373. )
  374. default:
  375. return nil
  376. }
  377. }
  378. }