-
Notifications
You must be signed in to change notification settings - Fork 514
/
PumpHistoryStorage.swift
403 lines (379 loc) · 14.3 KB
/
PumpHistoryStorage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
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 nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment]
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,
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 determineBolusEventType(for event: PumpHistoryEvent) -> EventType {
if event.isExternalInsulin ?? false {
return .externalInsulin
}
return event.type
}
func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment] {
let events = recent()
guard !events.isEmpty else { return [] }
let temps: [NigtscoutTreatment] = events.reduce([]) { result, event in
var result = result
switch event.type {
case .tempBasal:
result.append(NigtscoutTreatment(
duration: nil,
rawDuration: nil,
rawRate: event,
absolute: event.rate,
rate: event.rate,
eventType: .nsTempBasal,
createdAt: event.timestamp,
enteredBy: NigtscoutTreatment.local,
bolus: nil,
insulin: nil,
notes: nil,
carbs: nil,
fat: nil,
protein: nil,
targetTop: nil,
targetBottom: nil
))
case .tempBasalDuration:
if var last = result.popLast(), last.eventType == .nsTempBasal, last.createdAt == event.timestamp {
last.duration = event.durationMin
last.rawDuration = event
result.append(last)
}
default: break
}
return result
}
let bolusesAndCarbs = events.compactMap { event -> NigtscoutTreatment? in
switch event.type {
case .bolus:
let eventType = determineBolusEventType(for: event)
return NigtscoutTreatment(
duration: event.duration,
rawDuration: nil,
rawRate: nil,
absolute: nil,
rate: nil,
eventType: eventType,
createdAt: event.timestamp,
enteredBy: NigtscoutTreatment.local,
bolus: event,
insulin: event.amount,
notes: nil,
carbs: nil,
fat: nil,
protein: nil,
targetTop: nil,
targetBottom: nil
)
case .journalCarbs:
return NigtscoutTreatment(
duration: nil,
rawDuration: nil,
rawRate: nil,
absolute: nil,
rate: nil,
eventType: .nsCarbCorrection,
createdAt: event.timestamp,
enteredBy: NigtscoutTreatment.local,
bolus: nil,
insulin: nil,
notes: nil,
carbs: Decimal(event.carbInput ?? 0),
fat: nil,
protein: nil,
targetTop: nil,
targetBottom: nil
)
default: return nil
}
}
let misc = events.compactMap { event -> NigtscoutTreatment? in
switch event.type {
case .prime:
return NigtscoutTreatment(
duration: event.duration,
rawDuration: nil,
rawRate: nil,
absolute: nil,
rate: nil,
eventType: .nsSiteChange,
createdAt: event.timestamp,
enteredBy: NigtscoutTreatment.local,
bolus: event,
insulin: nil,
notes: nil,
carbs: nil,
fat: nil,
protein: nil,
targetTop: nil,
targetBottom: nil
)
case .rewind:
return NigtscoutTreatment(
duration: nil,
rawDuration: nil,
rawRate: nil,
absolute: nil,
rate: nil,
eventType: .nsInsulinChange,
createdAt: event.timestamp,
enteredBy: NigtscoutTreatment.local,
bolus: nil,
insulin: nil,
notes: nil,
carbs: nil,
fat: nil,
protein: nil,
targetTop: nil,
targetBottom: nil
)
case .pumpAlarm:
return NigtscoutTreatment(
duration: 30, // minutes
rawDuration: nil,
rawRate: nil,
absolute: nil,
rate: nil,
eventType: .nsAnnouncement,
createdAt: event.timestamp,
enteredBy: NigtscoutTreatment.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
}
}
let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedPumphistory, as: [NigtscoutTreatment].self) ?? []
let treatments = Array(Set([bolusesAndCarbs, temps, misc].flatMap { $0 }).subtracting(Set(uploaded)))
return treatments.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)
}
}