forked from tidepool-org/TidepoolService
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDoseEntry.swift
More file actions
540 lines (446 loc) · 22.5 KB
/
DoseEntry.swift
File metadata and controls
540 lines (446 loc) · 22.5 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//
// DoseEntry.swift
// TidepoolServiceKit
//
// Created by Darin Krauss on 2/7/22.
// Copyright © 2022 LoopKit Authors. All rights reserved.
//
import LoopKit
import TidepoolKit
import LoopAlgorithm
import HealthKit
/*
DoseEntry
Properties:
- type DoseType .type, .deliveryType, .subType
- startDate Date .time, .duration
- endDate Date .duration
- value Double .dose.total, .normal, .expectedNormal, .rate, .payload["deliveredUnits"]
- unit DoseUnit .dose.total, .normal, .expectedNormal, .rate, .payload["deliveredUnits"]
- deliveredUnits Double? .dose.total, .normal, .expectedNormal, .payload["deliveredUnits"]
- description String? (N/A - unused)
- insulinType InsulinType? .formulation, .insulinFormulation
- automatic Bool? .type, .deliveryType, .subType
- manuallyEntered Bool .type, .subType
- syncIdentifier String? .id, .origin.id, .payload["syncIdentifier"]
- scheduledBasalRate HKQuantity? .rate, .supressed.rate
- isMutable Bool .normal, .expectedNormal, .duration, .expectedDuration, .annotations
*/
extension DoseEntry: IdentifiableDatum {
func data(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
guard syncIdentifier != nil else {
return []
}
switch type {
case .basal:
return dataForBasal(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .bolus:
return dataForBolus(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .resume:
return []
case .suspend:
return dataForSuspend(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .tempBasal:
return dataForTempBasal(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
}
}
var syncIdentifierAsString: String { syncIdentifier!.md5hash! } // Actual sync identifier may be human readable and of variable length
private func dataForBasal(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
if automatic != true {
return dataForBasalManual(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
} else {
return dataForBasalAutomatic(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
}
}
private func dataForBasalManual(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var payload = datumPayload
payload["deliveredUnits"] = datumBasalDeliveredUnits
var datum = TScheduledBasalDatum(time: datumTime,
duration: datumDuration,
rate: datumScheduledBasalRate,
scheduleName: StoredSettings.activeScheduleNameDefault,
insulinFormulation: datumInsulinFormulation)
let origin = datumOrigin(for: resolvedIdentifier(for: TScheduledBasalDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TScheduledBasalDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private func dataForBasalAutomatic(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var payload = datumPayload
payload["deliveredUnits"] = datumBasalDeliveredUnits
var datum = TAutomatedBasalDatum(time: datumTime,
duration: datumDuration,
expectedDuration: nil,
rate: datumScheduledBasalRate,
scheduleName: StoredSettings.activeScheduleNameDefault,
insulinFormulation: datumInsulinFormulation)
let origin = datumOrigin(for: resolvedIdentifier(for: TAutomatedBasalDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TAutomatedBasalDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private func dataForBolus(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
// TODO: revert to using .insulin datum type once fully supported in Tidepool frontend
// if manuallyEntered {
// return dataForBolusManuallyEntered(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
// } else
if automatic != true {
return dataForBolusManual(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
} else {
return dataForBolusAutomatic(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
}
}
private func dataForBolusManuallyEntered(for userId: String, hostIdentifier: String, hostVersion: String) ->[TDatum] {
var payload = datumPayload
payload["duration"] = datumDuration.milliseconds
var datum = TInsulinDatum(time: datumTime,
dose: TInsulinDatum.Dose(total: deliveredUnits ?? programmedUnits),
formulation: datumInsulinFormulation)
let origin = datumOrigin(for: resolvedIdentifier(for: TInsulinDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TInsulinDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private func dataForBolusManual(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var payload = datumPayload
payload["duration"] = datumDuration.milliseconds
let programmedUnits = programmedUnits
let deliveredUnits = deliveredUnits ?? programmedUnits
var datum = TNormalBolusDatum(time: datumTime,
normal: !isMutable ? deliveredUnits : programmedUnits,
expectedNormal: !isMutable && programmedUnits != deliveredUnits ? programmedUnits : nil,
insulinFormulation: datumInsulinFormulation)
if manuallyEntered {
datum.notes = ["manual entry"]
}
let origin = datumOrigin(for: resolvedIdentifier(for: TNormalBolusDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TNormalBolusDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private func dataForBolusAutomatic(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var payload = datumPayload
payload["duration"] = datumDuration.milliseconds
let programmedUnits = programmedUnits
let deliveredUnits = deliveredUnits ?? programmedUnits
var datum = TAutomatedBolusDatum(time: datumTime,
normal: !isMutable ? deliveredUnits : programmedUnits,
expectedNormal: !isMutable && programmedUnits != deliveredUnits ? programmedUnits : nil,
insulinFormulation: datumInsulinFormulation)
let origin = datumOrigin(for: resolvedIdentifier(for: TAutomatedBolusDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TAutomatedBolusDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private func dataForSuspend(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var datum = TSuspendedBasalDatum(time: datumTime,
duration: datumDuration)
datum.suppressed = datumSuppressed
let origin = datumOrigin(for: resolvedIdentifier(for: TSuspendedBasalDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TSuspendedBasalDatum.self),
annotations: datumAnnotations,
payload: datumPayload,
origin: origin)
return [datum]
}
private func dataForTempBasal(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
if automatic == false {
return dataForTempBasalManual(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
} else {
return dataForTempBasalAutomatic(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
}
}
private func dataForTempBasalManual(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var payload = datumPayload
payload["deliveredUnits"] = deliveredUnits
var datum = TTemporaryBasalDatum(time: datumTime,
duration: !isMutable ? datumDuration : 0,
expectedDuration: !isMutable && datumDuration < basalDatumExpectedDuration ? basalDatumExpectedDuration : nil,
rate: datumRate,
insulinFormulation: datumInsulinFormulation)
datum.suppressed = datumSuppressed
let origin = datumOrigin(for: resolvedIdentifier(for: TTemporaryBasalDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TTemporaryBasalDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private func dataForTempBasalAutomatic(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var payload = datumPayload
payload["deliveredUnits"] = deliveredUnits
var datum = TAutomatedBasalDatum(time: datumTime,
duration: datumDuration,
expectedDuration: datumDuration < basalDatumExpectedDuration ? basalDatumExpectedDuration : nil,
rate: datumRate,
scheduleName: StoredSettings.activeScheduleNameDefault,
insulinFormulation: datumInsulinFormulation)
datum.suppressed = datumSuppressed
let origin = datumOrigin(for: resolvedIdentifier(for: TAutomatedBasalDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TAutomatedBasalDatum.self),
annotations: datumAnnotations,
payload: payload,
origin: origin)
return [datum]
}
private var datumTime: Date { startDate }
private var datumDuration: TimeInterval { startDate.distance(to: endDate) }
private var datumRate: Double { unitsPerHour }
private var datumBasalDeliveredUnits: Double? {
guard type == .basal || type == .tempBasal else {
return nil
}
if let deliveredUnits = deliveredUnits {
return deliveredUnits
}
if unit == .units {
return programmedUnits
}
return nil
}
private var datumScheduledBasalRate: Double {
if let rate = scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) {
return rate
}
return unitsPerHour
}
private var datumSuppressed: TScheduledBasalDatum.Suppressed? {
guard type == .tempBasal || type == .suspend else {
return nil
}
return TScheduledBasalDatum.Suppressed(rate: datumScheduledBasalRate,
scheduleName: StoredSettings.activeScheduleNameDefault)
}
private var datumInsulinFormulation: TInsulinDatum.Formulation? { insulinType?.datum }
private var datumAnnotations: [TDictionary]? {
guard isMutable else {
return nil
}
switch type {
case .basal, .suspend, .tempBasal:
return [TDictionary(["code": "basal/unknown-duration"])]
case .bolus:
return [TDictionary(["code": "bolus/mutable"])]
case .resume:
return nil
}
}
private var datumPayload: TDictionary {
var dictionary = TDictionary()
dictionary["syncIdentifier"] = syncIdentifier
return dictionary
}
private var basalDatumExpectedDuration: TimeInterval { .minutes(30) }
}
extension DoseEntry {
var selectors: [TDatum.Selector] {
guard syncIdentifier != nil else {
return []
}
switch type {
case .basal:
return [datumSelector(for: TScheduledBasalDatum.self)]
case .bolus:
// TODO: revert to using .insulin datum type once fully supported in Tidepool frontend
// if manuallyEntered {
// return [datumSelector(for: TInsulinDatum.self)]
// } else if automatic != true {
if automatic != true {
return [datumSelector(for: TNormalBolusDatum.self)]
} else {
return [datumSelector(for: TAutomatedBolusDatum.self)]
}
case .resume:
return []
case .suspend:
return [datumSelector(for: TSuspendedBasalDatum.self)]
case .tempBasal:
if automatic == false {
return [datumSelector(for: TTemporaryBasalDatum.self)]
} else {
return [datumSelector(for: TAutomatedBasalDatum.self)]
}
}
}
}
extension TAutomatedBasalDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.basal.rawValue)/\(TBasalDatum.DeliveryType.automated.rawValue)" }
}
extension TScheduledBasalDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.basal.rawValue)/\(TBasalDatum.DeliveryType.scheduled.rawValue)" }
}
extension TSuspendedBasalDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.basal.rawValue)/\(TBasalDatum.DeliveryType.suspended.rawValue)" }
}
extension TTemporaryBasalDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.basal.rawValue)/\(TBasalDatum.DeliveryType.temporary.rawValue)" }
}
extension TAutomatedBolusDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.bolus.rawValue)/\(TBolusDatum.SubType.automated.rawValue)" }
}
extension TNormalBolusDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.bolus.rawValue)/\(TBolusDatum.SubType.normal.rawValue)" }
}
extension TInsulinDatum: TypedDatum {
static var resolvedType: String { TDatum.DatumType.insulin.rawValue }
}
extension DoseEntry {
/// Annotates a dose with the context of a history of scheduled basal rates
///
/// If the dose crosses a schedule boundary, it will be split into multiple doses so each dose has a
/// single scheduled basal rate.
///
/// - Parameter basalHistory: The history of basal schedule values to apply. Only schedule values overlapping the dose should be included.
/// - Returns: An array of annotated doses
fileprivate func annotated(with basalHistory: [AbsoluteScheduleValue<Double>]) -> [DoseEntry] {
guard type == .tempBasal || type == .suspend, !basalHistory.isEmpty else {
return [self]
}
if type == .suspend {
guard value == 0 else {
preconditionFailure("suspend with non-zero delivery")
}
} else {
guard unit != .units else {
preconditionFailure("temp basal without rate unsupported")
}
}
if isMutable {
var newDose = self
let basal = basalHistory.first!
newDose.scheduledBasalRate = HKQuantity(unit: .internationalUnitsPerHour, doubleValue: basal.value)
return [newDose]
}
var doses: [DoseEntry] = []
for (index, basalItem) in basalHistory.enumerated() {
let startDate: Date
let endDate: Date
if index == 0 {
startDate = self.startDate
} else {
startDate = basalItem.startDate
}
if index == basalHistory.count - 1 {
endDate = self.endDate
} else {
endDate = basalHistory[index + 1].startDate
}
let segmentStartDate = max(startDate, self.startDate)
let segmentEndDate = max(startDate, min(endDate, self.endDate))
let segmentDuration = segmentEndDate.timeIntervalSince(segmentStartDate)
let segmentPortion = (segmentDuration / duration)
var annotatedDose = self
annotatedDose.startDate = segmentStartDate
annotatedDose.endDate = segmentEndDate
annotatedDose.scheduledBasalRate = HKQuantity(unit: .internationalUnitsPerHour, doubleValue: basalItem.value)
if let deliveredUnits {
annotatedDose.deliveredUnits = deliveredUnits * segmentPortion
}
doses.append(annotatedDose)
}
if doses.count > 1 {
for (index, dose) in doses.enumerated() {
if let originalIdentifier = dose.syncIdentifier, index>0 {
doses[index].syncIdentifier = originalIdentifier + "\(index+1)/\(doses.count)"
}
}
}
return doses
}
}
extension Collection where Element == DoseEntry {
/// Annotates a sequence of dose entries with the configured basal history
///
/// Doses which cross time boundaries in the basal rate schedule are split into multiple entries.
///
/// - Parameter basalHistory: A history of basal rates covering the timespan of these doses.
/// - Returns: An array of annotated dose entries
public func annotated(with basalHistory: [AbsoluteScheduleValue<Double>]) -> [DoseEntry] {
var annotatedDoses: [DoseEntry] = []
for dose in self {
let basalItems = basalHistory.filterDateRange(dose.startDate, dose.endDate)
annotatedDoses += dose.annotated(with: basalItems)
}
return annotatedDoses
}
/// Assigns an automation status to any dose where automation is not already specified
///
/// - Parameters:
/// - automationHistory: A history of automation periods.
/// - Returns: An array of doses, with the automation flag set based on automation history. Doses will be split if the automation state changes mid-dose.
public func overlayAutomationHistory(
_ automationHistory: [AbsoluteScheduleValue<Bool>]
) -> [DoseEntry] {
guard count > 0 else {
return []
}
var newEntries = [DoseEntry]()
var automation = automationHistory
// Assume automation if doses start before automationHistory
if let firstAutomation = automation.first, firstAutomation.startDate > first!.startDate {
automation.insert(AbsoluteScheduleValue(startDate: first!.startDate, endDate: firstAutomation.startDate, value: true), at: 0)
}
// Overlay automation periods
func annotateDoseWithAutomation(dose: DoseEntry) {
var addedCount = 0
for period in automation {
if period.endDate > dose.startDate && period.startDate < dose.endDate {
var newDose = dose
if dose.isMutable {
newDose.automatic = period.value
newEntries.append(newDose)
return
}
newDose.startDate = Swift.max(period.startDate, dose.startDate)
newDose.endDate = Swift.min(period.endDate, dose.endDate)
if let delivered = dose.deliveredUnits {
newDose.deliveredUnits = newDose.duration / dose.duration * delivered
}
newDose.automatic = period.value
if addedCount > 0 {
newDose.syncIdentifier = "\(dose.syncIdentifierAsString)\(addedCount+1)"
}
newEntries.append(newDose)
addedCount += 1
}
}
if addedCount == 0 {
// automation history did not cover dose; mark automatic as default
var newDose = dose
newDose.automatic = true
newEntries.append(newDose)
}
}
for dose in self {
switch dose.type {
case .tempBasal, .basal, .suspend:
if dose.automatic == nil {
annotateDoseWithAutomation(dose: dose)
} else {
newEntries.append(dose)
}
default:
newEntries.append(dose)
break
}
}
return newEntries
}
}
extension DoseEntry {
var simpleDesc: String {
let seconds = Int(duration)
let automatic = automatic?.description ?? "na"
return "\(startDate) (\(seconds)s) - \(type) - isMutable:\(isMutable) automatic:\(automatic) value:\(value) delivered:\(String(describing: deliveredUnits)) scheduled:\(String(describing: scheduledBasalRate)) syncId:\(String(describing: syncIdentifier))"
}
}