-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathOmnipodSettingsViewModel.swift
More file actions
623 lines (528 loc) · 21.7 KB
/
OmnipodSettingsViewModel.swift
File metadata and controls
623 lines (528 loc) · 21.7 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//
// OmnipodSettingsViewModel.swift
// OmniKit
//
// Created by Pete Schwamb on 3/8/20.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import SwiftUI
import LoopKit
import LoopKitUI
import HealthKit
import OmniKit
import Combine
enum OmnipodSettingsViewAlert {
case suspendError(Error)
case resumeError(Error)
case cancelManualBasalError(Error)
case syncTimeError(OmnipodPumpManagerError)
}
struct OmnipodSettingsNotice {
let title: String
let description: String
}
class OmnipodSettingsViewModel: ObservableObject {
@Published var lifeState: PodLifeState
@Published var activatedAt: Date?
@Published var expiresAt: Date?
@Published var beepPreference: BeepPreference
@Published var silencePodPreference: SilencePodPreference
@Published var rileylinkConnected: Bool
var activatedAtString: String {
if let activatedAt = activatedAt {
return dateFormatter.string(from: activatedAt)
} else {
return "—"
}
}
var expiresAtString: String {
if let expiresAt = expiresAt {
return dateFormatter.string(from: expiresAt)
} else {
return "—"
}
}
var serviceTimeRemainingString: String? {
if let serviceTimeRemaining = pumpManager.podServiceTimeRemaining, let serviceTimeRemainingString = timeRemainingFormatter.string(from: serviceTimeRemaining) {
return serviceTimeRemainingString
} else {
return nil
}
}
// Expiration reminder date for current pod
@Published var expirationReminderDate: Date?
var allowedScheduledReminderDates: [Date]? {
return pumpManager.allowedExpirationReminderDates
}
// Hours before expiration
@Published var expirationReminderDefault: Int {
didSet {
self.pumpManager.defaultExpirationReminderOffset = .hours(Double(expirationReminderDefault))
}
}
// Units to alert at
@Published var lowReservoirAlertValue: Int
@Published var basalDeliveryState: PumpManagerStatus.BasalDeliveryState?
@Published var basalDeliveryRate: Double?
@Published var activeAlert: OmnipodSettingsViewAlert? = nil {
didSet {
if activeAlert != nil {
alertIsPresented = true
}
}
}
@Published var alertIsPresented: Bool = false {
didSet {
if !alertIsPresented {
activeAlert = nil
}
}
}
@Published var reservoirLevel: ReservoirLevel?
@Published var reservoirLevelHighlightState: ReservoirLevelHighlightState?
@Published var synchronizingTime: Bool = false
@Published var podCommState: PodCommState
@Published var insulinType: InsulinType?
@Published var podDetails: PodDetails?
@Published var previousPodDetails: PodDetails?
var timeZone: TimeZone {
return pumpManager.status.timeZone
}
var viewTitle: String {
return pumpManager.localizedTitle
}
var isClockOffset: Bool {
return pumpManager.isClockOffset
}
var isPodDataStale: Bool {
return Date().timeIntervalSince(pumpManager.lastSync ?? .distantPast) > .minutes(12)
}
var recoveryText: String? {
if case .fault = podCommState {
return LocalizedString("⚠️ Insulin delivery stopped. Change Pod now.", comment: "The action string on pod status page when pod faulted")
} else if podOk && isPodDataStale {
return LocalizedString("Make sure your phone and pod are close to each other. If communication issues persist, move to a new area.", comment: "The action string on pod status page when pod data is stale")
} else if let serviceTimeRemaining = pumpManager.podServiceTimeRemaining, serviceTimeRemaining <= Pod.serviceDuration - Pod.nominalPodLife {
if let serviceTimeRemainingString = serviceTimeRemainingString {
return String(format: LocalizedString("Change Pod now. Insulin delivery will stop in %1$@ or when no more insulin remains.", comment: "Format string for the action string on pod status page when pod expired. (1: service time remaining)"), serviceTimeRemainingString)
} else {
return LocalizedString("Change Pod now. Insulin delivery will stop 8 hours after the Pod has expired or when no more insulin remains.", comment: "The action string on pod status page when pod expired")
}
} else {
return nil
}
}
var notice: OmnipodSettingsNotice? {
if pumpManager.isClockOffset {
return OmnipodSettingsNotice(
title: LocalizedString("Time Change Detected", comment: "title for time change detected notice"),
description: LocalizedString("The time on your pump is different from the current time. Your pump’s time controls your scheduled therapy settings. Scroll down to Pump Time row to review the time difference and configure your pump.", comment: "description for time change detected notice"))
} else {
return nil
}
}
var isScheduledBasal: Bool {
switch basalDeliveryState {
case .active(_), .initiatingTempBasal:
return true
default:
return false
}
}
let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .medium
dateFormatter.doesRelativeDateFormatting = true
return dateFormatter
}()
let timeFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .none
return dateFormatter
}()
let timeRemainingFormatter: DateComponentsFormatter = {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute]
dateComponentsFormatter.unitsStyle = .full
dateComponentsFormatter.zeroFormattingBehavior = .dropAll
return dateComponentsFormatter
}()
let basalRateFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = 1
numberFormatter.minimumIntegerDigits = 1
return numberFormatter
}()
var manualBasalTimeRemaining: TimeInterval? {
if case .tempBasal(let dose) = basalDeliveryState, !(dose.automatic ?? true) {
let remaining = dose.endDate.timeIntervalSinceNow
if remaining > 0 {
return remaining
}
}
return nil
}
let reservoirVolumeFormatter = QuantityFormatter(for: .internationalUnit())
var didFinish: (() -> Void)?
var navigateTo: ((OmnipodUIScreen) -> Void)?
private let pumpManager: OmnipodPumpManager
private lazy var cancellables = Set<AnyCancellable>()
init(pumpManager: OmnipodPumpManager) {
self.pumpManager = pumpManager
lifeState = pumpManager.lifeState
activatedAt = pumpManager.podActivatedAt
expiresAt = pumpManager.expiresAt
basalDeliveryState = pumpManager.status.basalDeliveryState
basalDeliveryRate = self.pumpManager.basalDeliveryRate
reservoirLevel = self.pumpManager.reservoirLevel
reservoirLevelHighlightState = self.pumpManager.reservoirLevelHighlightState
expirationReminderDate = self.pumpManager.scheduledExpirationReminder
expirationReminderDefault = Int(self.pumpManager.defaultExpirationReminderOffset.hours)
lowReservoirAlertValue = Int(self.pumpManager.state.lowReservoirReminderValue)
podCommState = self.pumpManager.podCommState
beepPreference = self.pumpManager.beepPreference
silencePodPreference = self.pumpManager.silencePod ? .enabled : .disabled
insulinType = self.pumpManager.insulinType
podDetails = self.pumpManager.podDetails
previousPodDetails = self.pumpManager.previousPodDetails
// TODO:
rileylinkConnected = false
pumpManager.addPodStateObserver(self, queue: DispatchQueue.main)
pumpManager.addStatusObserver(self, queue: DispatchQueue.main)
// Register for device notifications
NotificationCenter.default.publisher(for: .DeviceConnectionStateDidChange)
.sink { [weak self] _ in
self?.updateConnectionStatus()
}
.store(in: &cancellables)
// Trigger refresh
pumpManager.getPodStatus() { _ in }
updateConnectionStatus()
}
func updateConnectionStatus() {
pumpManager.rileyLinkDeviceProvider.getDevices { (devices) in
DispatchQueue.main.async { [weak self] in
self?.rileylinkConnected = devices.firstConnected != nil
}
}
}
func changeTimeZoneTapped() {
synchronizingTime = true
pumpManager.setTime { (error) in
DispatchQueue.main.async {
self.synchronizingTime = false
self.lifeState = self.pumpManager.lifeState
if let error = error {
self.activeAlert = .syncTimeError(error)
}
}
}
}
func doneTapped() {
self.didFinish?()
}
func stopUsingOmnipodTapped() {
pumpManager.notifyDelegateOfDeactivation {
DispatchQueue.main.async {
self.didFinish?()
}
}
}
func suspendDelivery(duration: TimeInterval) {
pumpManager.suspendDelivery(withSuspendReminders: duration) { (error) in
DispatchQueue.main.async {
if let error = error {
self.activeAlert = .suspendError(error)
}
}
}
}
func resumeDelivery() {
pumpManager.resumeDelivery { (error) in
DispatchQueue.main.async {
if let error = error {
self.activeAlert = .resumeError(error)
}
}
}
}
func runTemporaryBasalProgram(unitsPerHour: Double, for duration: TimeInterval, completion: @escaping (PumpManagerError?) -> Void) {
pumpManager.runTemporaryBasalProgram(unitsPerHour: unitsPerHour, for: duration, automatic: false, completion: completion)
}
func saveScheduledExpirationReminder(_ selectedDate: Date?, _ completion: @escaping (Error?) -> Void) {
if let podExpiresAt = pumpManager.podExpiresAt {
var intervalBeforeExpiration : TimeInterval?
if let selectedDate = selectedDate {
intervalBeforeExpiration = .hours(round(podExpiresAt.timeIntervalSince(selectedDate).hours))
}
pumpManager.updateExpirationReminder(intervalBeforeExpiration) { (error) in
DispatchQueue.main.async {
if error == nil {
self.expirationReminderDate = selectedDate
}
completion(error)
}
}
}
}
func saveLowReservoirReminder(_ selectedValue: Int, _ completion: @escaping (Error?) -> Void) {
pumpManager.updateLowReservoirReminder(selectedValue) { (error) in
DispatchQueue.main.async {
if error == nil {
self.lowReservoirAlertValue = selectedValue
}
completion(error)
}
}
}
func playTestBeeps() async throws {
try await pumpManager.playTestBeeps()
}
func setConfirmationBeeps(_ preference: BeepPreference, _ completion: @escaping (_ error: LocalizedError?) -> Void) {
pumpManager.setConfirmationBeeps(newPreference: preference) { error in
DispatchQueue.main.async {
if error == nil {
self.beepPreference = preference
}
completion(error)
}
}
}
func setSilencePod(_ silencePodPreference: SilencePodPreference, _ completion: @escaping (_ error: LocalizedError?) -> Void) {
pumpManager.setSilencePod(silencePod: silencePodPreference == .enabled) { error in
DispatchQueue.main.async {
if error == nil {
self.silencePodPreference = silencePodPreference
}
completion(error)
}
}
}
func didChangeInsulinType(_ newType: InsulinType?) {
self.pumpManager.insulinType = newType
}
var podOk: Bool {
guard basalDeliveryState != nil else { return false }
switch podCommState {
case .noPod, .activating, .deactivating, .fault:
return false
default:
return true
}
}
var noPod: Bool {
return podCommState == .noPod
}
var diagnosticCommands: DiagnosticCommands {
return pumpManager
}
var podError: String? {
switch podCommState {
case .fault(let status):
switch status.faultEventCode.faultType {
case .reservoirEmpty:
return LocalizedString("No Insulin", comment: "Error message for reservoir view when reservoir empty")
case .exceededMaximumPodLife80Hrs:
return LocalizedString("Pod Expired", comment: "Error message for reservoir view when pod expired")
case .occluded, .occlusionCheckStartup1, .occlusionCheckStartup2, .occlusionCheckTimeouts1, .occlusionCheckTimeouts2, .occlusionCheckTimeouts3, .occlusionCheckPulseIssue, .occlusionCheckBolusProblem, .occlusionCheckAboveThreshold, .occlusionCheckValueTooHigh:
return LocalizedString("Pod Occlusion", comment: "Error message for reservoir view when pod occlusion checks failed")
default:
return String(format: LocalizedString("Pod Fault %1$03d", comment: "Error message for reservoir view during general pod fault: (1: fault code value)"), status.faultEventCode.rawValue)
}
case .active:
if isPodDataStale {
return LocalizedString("Signal Loss", comment: "Error message for reservoir view during general pod fault")
} else {
return nil
}
default:
return nil
}
}
func reservoirText(for level: ReservoirLevel) -> String {
switch level {
case .aboveThreshold:
let quantity = HKQuantity(unit: .internationalUnit(), doubleValue: Pod.maximumReservoirReading)
let thresholdString = reservoirVolumeFormatter.string(from: quantity, includeUnit: false) ?? ""
let unitString = reservoirVolumeFormatter.localizedUnitStringWithPlurality(forValue: Pod.maximumReservoirReading, avoidLineBreaking: true)
return String(format: LocalizedString("%1$@+ %2$@", comment: "Format string for reservoir level above max measurable threshold. (1: measurable reservoir threshold) (2: units)"),
thresholdString, unitString)
case .valid(let value):
let quantity = HKQuantity(unit: .internationalUnit(), doubleValue: value)
return reservoirVolumeFormatter.string(from: quantity) ?? ""
}
}
var suspendResumeActionText: String {
let defaultText = LocalizedString("Suspend Insulin Delivery", comment: "Text for suspend resume button when insulin delivery active")
guard podOk else {
return defaultText
}
switch basalDeliveryState {
case .suspending:
return LocalizedString("Suspending insulin delivery...", comment: "Text for suspend resume button when insulin delivery is suspending")
case .suspended:
return LocalizedString("Resume Insulin Delivery", comment: "Text for suspend resume button when insulin delivery is suspended")
case .resuming:
return LocalizedString("Resuming insulin delivery...", comment: "Text for suspend resume button when insulin delivery is resuming")
default:
return defaultText
}
}
var basalTransitioning: Bool {
switch basalDeliveryState {
case .suspending, .resuming:
return true
default:
return false
}
}
func suspendResumeButtonColor(guidanceColors: GuidanceColors) -> Color {
guard podOk else {
return Color.secondary
}
switch basalDeliveryState {
case .suspending, .resuming:
return Color.secondary
case .suspended:
return guidanceColors.warning
default:
return .accentColor
}
}
func suspendResumeActionColor() -> Color {
guard podOk else {
return Color.secondary
}
switch basalDeliveryState {
case .suspending, .resuming:
return Color.secondary
default:
return Color.accentColor
}
}
var isSuspendedOrResuming: Bool {
switch basalDeliveryState {
case .suspended, .resuming:
return true
default:
return false
}
}
public var allowedTempBasalRates: [Double] {
return Pod.supportedTempBasalRates.filter { $0 <= pumpManager.state.maximumTempBasalRate }
}
}
extension OmnipodSettingsViewModel: PodStateObserver {
func podStateDidUpdate(_ state: PodState?) {
lifeState = self.pumpManager.lifeState
basalDeliveryRate = self.pumpManager.basalDeliveryRate
reservoirLevel = self.pumpManager.reservoirLevel
activatedAt = state?.activatedAt
expiresAt = state?.expiresAt
reservoirLevelHighlightState = self.pumpManager.reservoirLevelHighlightState
expirationReminderDate = self.pumpManager.scheduledExpirationReminder
podCommState = self.pumpManager.podCommState
beepPreference = self.pumpManager.beepPreference
insulinType = self.pumpManager.insulinType
podDetails = self.pumpManager.podDetails
previousPodDetails = self.pumpManager.previousPodDetails
}
func podConnectionStateDidChange(isConnected: Bool) {
self.rileylinkConnected = isConnected
}
}
extension OmnipodSettingsViewModel: PumpManagerStatusObserver {
func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) {
basalDeliveryState = self.pumpManager.status.basalDeliveryState
}
}
extension OmnipodPumpManager {
var lifeState: PodLifeState {
switch podCommState {
case .fault(let status):
switch status.faultEventCode.faultType {
case .exceededMaximumPodLife80Hrs:
return .expired
default:
let remaining = Pod.nominalPodLife - (status.faultEventTimeSinceActivation ?? Pod.nominalPodLife)
let podTimeUntilReminder = remaining - (state.scheduledExpirationReminderOffset ?? 0)
if remaining > 0 {
return .timeRemaining(timeUntilExpiration: remaining, timeUntilExpirationReminder: podTimeUntilReminder)
} else {
return .expired
}
}
case .noPod:
return .noPod
case .activating:
return .podActivating
case .deactivating:
return .podDeactivating
case .active:
if let podTimeRemaining = podTimeRemaining {
if podTimeRemaining > 0 {
let podTimeUntilReminder = podTimeRemaining - (state.scheduledExpirationReminderOffset ?? 0)
return .timeRemaining(timeUntilExpiration: podTimeRemaining, timeUntilExpirationReminder: podTimeUntilReminder)
} else {
return .expired
}
} else {
return .podDeactivating
}
}
}
var basalDeliveryRate: Double? {
if let tempBasal = state.podState?.unfinalizedTempBasal, !tempBasal.isFinished() {
return tempBasal.rate
} else {
switch state.podState?.suspendState {
case .resumed:
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = state.timeZone
return state.basalSchedule.currentRate(using: calendar, at: dateGenerator())
case .suspended, .none:
return nil
}
}
}
fileprivate var podServiceTimeRemaining : TimeInterval? {
guard let podTimeRemaining = podTimeRemaining else {
return nil;
}
return max(0, Pod.serviceDuration - Pod.nominalPodLife + podTimeRemaining);
}
private func podDetails(fromPodState podState: PodState) -> PodDetails {
return PodDetails(
lotNumber: podState.lot,
sequenceNumber: podState.tid,
piVersion: podState.piVersion,
pmVersion: podState.pmVersion,
totalDelivery: podState.lastInsulinMeasurements?.delivered,
lastStatus: podState.lastInsulinMeasurements?.validTime,
fault: podState.fault?.faultEventCode,
activatedAt: podState.activatedAt,
activeTime: podState.activeTime,
pdmRef: podState.fault?.pdmRef
)
}
public var podDetails: PodDetails? {
guard let podState = state.podState else {
return nil
}
return podDetails(fromPodState: podState)
}
public var previousPodDetails: PodDetails? {
guard let podState = state.previousPodState else {
return nil
}
return podDetails(fromPodState: podState)
}
}
extension OmnipodPumpManager: DiagnosticCommands {
func pumpManagerDetails() -> String {
return debugDescription
}
}