| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402 |
- import Foundation
- import LoopKit
- import SwiftDate
- import Swinject
- protocol PumpHistoryObserver {
- func pumpHistoryDidUpdate(_ events: [PumpHistoryEvent])
- }
- protocol PumpHistoryStorage {
- func storePumpEvents(_ events: [NewPumpEvent])
- func storeEvents(_ events: [PumpHistoryEvent])
- func storeJournalCarbs(_ carbs: Int)
- func recent() -> [PumpHistoryEvent]
- func nightscoutTreatmentsNotUploaded() -> [NightscoutTreatment]
- func saveCancelTempEvents()
- func deleteInsulin(at date: Date)
- }
- final class BasePumpHistoryStorage: PumpHistoryStorage, Injectable {
- private let processQueue = DispatchQueue(label: "BasePumpHistoryStorage.processQueue")
- @Injected() private var storage: FileStorage!
- @Injected() private var broadcaster: Broadcaster!
- init(resolver: Resolver) {
- injectServices(resolver)
- }
- func storePumpEvents(_ events: [NewPumpEvent]) {
- processQueue.async {
- let eventsToStore = events.flatMap { event -> [PumpHistoryEvent] in
- let id = event.raw.md5String
- switch event.type {
- case .bolus:
- guard let dose = event.dose else { return [] }
- let amount = Decimal(string: dose.unitsInDeliverableIncrements.description)
- let minutes = Int((dose.endDate - dose.startDate).timeInterval / 60)
- return [PumpHistoryEvent(
- id: id,
- type: .bolus,
- timestamp: event.date,
- amount: amount,
- duration: minutes,
- durationMin: nil,
- rate: nil,
- temp: nil,
- carbInput: nil,
- isSMB: dose.automatic,
- isExternalInsulin: dose.manuallyEntered
- )]
- case .tempBasal:
- guard let dose = event.dose else { return [] }
- let rate = Decimal(dose.unitsPerHour)
- let minutes = (dose.endDate - dose.startDate).timeInterval / 60
- let delivered = dose.deliveredUnits
- let date = event.date
- let isCancel = delivered != nil //! event.isMutable && delivered != nil
- guard !isCancel else { return [] }
- return [
- PumpHistoryEvent(
- id: id,
- type: .tempBasalDuration,
- timestamp: date,
- amount: nil,
- duration: nil,
- durationMin: Int(round(minutes)),
- rate: nil,
- temp: nil,
- carbInput: nil
- ),
- PumpHistoryEvent(
- id: "_" + id,
- type: .tempBasal,
- timestamp: date,
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: rate,
- temp: .absolute,
- carbInput: nil
- )
- ]
- case .suspend:
- return [
- PumpHistoryEvent(
- id: id,
- type: .pumpSuspend,
- timestamp: event.date,
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: nil,
- temp: nil,
- carbInput: nil
- )
- ]
- case .resume:
- return [
- PumpHistoryEvent(
- id: id,
- type: .pumpResume,
- timestamp: event.date,
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: nil,
- temp: nil,
- carbInput: nil
- )
- ]
- case .rewind:
- return [
- PumpHistoryEvent(
- id: id,
- type: .rewind,
- timestamp: event.date,
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: nil,
- temp: nil,
- carbInput: nil
- )
- ]
- case .prime:
- return [
- PumpHistoryEvent(
- id: id,
- type: .prime,
- timestamp: event.date,
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: nil,
- temp: nil,
- carbInput: nil
- )
- ]
- case .alarm:
- return [
- PumpHistoryEvent(
- id: id,
- type: .pumpAlarm,
- timestamp: event.date,
- note: event.title
- )
- ]
- default:
- return []
- }
- }
- self.storeEvents(eventsToStore)
- }
- }
- func storeJournalCarbs(_ carbs: Int) {
- processQueue.async {
- let eventsToStore = [
- PumpHistoryEvent(
- id: UUID().uuidString,
- type: .journalCarbs,
- timestamp: Date(),
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: nil,
- temp: nil,
- carbInput: carbs
- )
- ]
- self.storeEvents(eventsToStore)
- }
- }
- func storeEvents(_ events: [PumpHistoryEvent]) {
- processQueue.async {
- let file = OpenAPS.Monitor.pumpHistory
- var uniqEvents: [PumpHistoryEvent] = []
- self.storage.transaction { storage in
- storage.append(events, to: file, uniqBy: \.id)
- uniqEvents = storage.retrieve(file, as: [PumpHistoryEvent].self)?
- .filter { $0.timestamp.addingTimeInterval(1.days.timeInterval) > Date() }
- .sorted { $0.timestamp > $1.timestamp } ?? []
- storage.save(Array(uniqEvents), as: file)
- }
- self.broadcaster.notify(PumpHistoryObserver.self, on: self.processQueue) {
- $0.pumpHistoryDidUpdate(uniqEvents)
- }
- }
- }
- func recent() -> [PumpHistoryEvent] {
- storage.retrieve(OpenAPS.Monitor.pumpHistory, as: [PumpHistoryEvent].self)?.reversed() ?? []
- }
- func deleteInsulin(at date: Date) {
- processQueue.sync {
- var allValues = storage.retrieve(OpenAPS.Monitor.pumpHistory, as: [PumpHistoryEvent].self) ?? []
- guard let entryIndex = allValues.firstIndex(where: { $0.timestamp == date }) else {
- return
- }
- allValues.remove(at: entryIndex)
- storage.save(allValues, as: OpenAPS.Monitor.pumpHistory)
- broadcaster.notify(PumpHistoryObserver.self, on: processQueue) {
- $0.pumpHistoryDidUpdate(allValues)
- }
- }
- }
- func nightscoutTreatmentsNotUploaded() -> [NightscoutTreatment] {
- let events = recent()
- guard !events.isEmpty else { return [] }
- var treatments: [NightscoutTreatment?] = []
- for i in 0 ..< events.count {
- let event = events[i]
- var nextEvent: PumpHistoryEvent?
- if i + 1 < events.count {
- nextEvent = events[i + 1]
- }
- if event.type == .tempBasal, nextEvent?.type == .tempBasalDuration {
- treatments.append(NightscoutTreatment(event: event, tempBasalDuration: nextEvent))
- } else {
- treatments.append(NightscoutTreatment(event: event))
- }
- }
- let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedPumphistory, as: [NightscoutTreatment].self) ?? []
- let treatmentsToUpload = Set(treatments.compactMap { $0 }).subtracting(Set(uploaded))
- return treatmentsToUpload.sorted { $0.createdAt! > $1.createdAt! }
- }
- func saveCancelTempEvents() {
- let basalID = UUID().uuidString
- let date = Date()
- let events = [
- PumpHistoryEvent(
- id: basalID,
- type: .tempBasalDuration,
- timestamp: date,
- amount: nil,
- duration: nil,
- durationMin: 0,
- rate: nil,
- temp: nil,
- carbInput: nil
- ),
- PumpHistoryEvent(
- id: "_" + basalID,
- type: .tempBasal,
- timestamp: date,
- amount: nil,
- duration: nil,
- durationMin: nil,
- rate: 0,
- temp: .absolute,
- carbInput: nil
- )
- ]
- storeEvents(events)
- }
- }
- extension NightscoutTreatment {
- init?(event: PumpHistoryEvent, tempBasalDuration: PumpHistoryEvent? = nil) {
- var basalDurationEvent: PumpHistoryEvent?
- if tempBasalDuration != nil, tempBasalDuration?.timestamp == event.timestamp, event.type == .tempBasal,
- tempBasalDuration?.type == .tempBasalDuration
- {
- basalDurationEvent = tempBasalDuration
- }
- switch event.type {
- case .tempBasal:
- self.init(
- duration: basalDurationEvent?.durationMin,
- rawDuration: basalDurationEvent,
- rawRate: event,
- absolute: event.rate,
- rate: event.rate,
- eventType: .nsTempBasal,
- createdAt: event.timestamp,
- enteredBy: NightscoutTreatment.local,
- bolus: nil,
- insulin: nil,
- notes: nil,
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- case .bolus:
- let eventType = determineBolusEventType(for: event)
- self.init(
- duration: event.duration,
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: eventType,
- createdAt: event.timestamp,
- enteredBy: NightscoutTreatment.local,
- bolus: event,
- insulin: event.amount,
- notes: nil,
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- case .journalCarbs:
- self.init(
- duration: nil,
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: .nsCarbCorrection,
- createdAt: event.timestamp,
- enteredBy: NightscoutTreatment.local,
- bolus: nil,
- insulin: nil,
- notes: nil,
- carbs: Decimal(event.carbInput ?? 0),
- fat: Decimal(event.fatInput ?? 0),
- protein: Decimal(event.proteinInput ?? 0),
- targetTop: nil,
- targetBottom: nil
- )
- case .prime:
- self.init(
- duration: event.duration,
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: .nsSiteChange,
- createdAt: event.timestamp,
- enteredBy: NightscoutTreatment.local,
- bolus: event,
- insulin: nil,
- notes: nil,
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- case .rewind:
- self.init(
- duration: nil,
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: .nsInsulinChange,
- createdAt: event.timestamp,
- enteredBy: NightscoutTreatment.local,
- bolus: nil,
- insulin: nil,
- notes: nil,
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- case .pumpAlarm:
- self.init(
- duration: 30, // minutes
- rawDuration: nil,
- rawRate: nil,
- absolute: nil,
- rate: nil,
- eventType: .nsAnnouncement,
- createdAt: event.timestamp,
- enteredBy: NightscoutTreatment.local,
- bolus: nil,
- insulin: nil,
- notes: "Alarm \(String(describing: event.note)) \(event.type)",
- carbs: nil,
- fat: nil,
- protein: nil,
- targetTop: nil,
- targetBottom: nil
- )
- default:
- return nil
- }
- }
- }
|