MockCGMManager.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. //
  2. // MockCGMManager.swift
  3. // LoopKit
  4. //
  5. // Created by Michael Pangburn on 11/20/18.
  6. // Copyright © 2018 LoopKit Authors. All rights reserved.
  7. //
  8. import HealthKit
  9. import LoopKit
  10. import LoopKitUI // TODO: DeviceStatusBadge references should live in MockKitUI
  11. import LoopTestingKit
  12. public struct MockCGMState: GlucoseDisplayable {
  13. public var isStateValid: Bool
  14. public var trendType: GlucoseTrend?
  15. public var trendRate: HKQuantity?
  16. public var isLocal: Bool {
  17. return true
  18. }
  19. public var glucoseRangeCategory: GlucoseRangeCategory?
  20. public let unit: HKUnit = .milligramsPerDeciliter
  21. public var glucoseAlertingEnabled: Bool
  22. public var samplesShouldBeUploaded: Bool
  23. private var cgmLowerLimitValue: Double
  24. // HKQuantity isn't codable
  25. public var cgmLowerLimit: HKQuantity {
  26. get {
  27. return HKQuantity.init(unit: unit, doubleValue: cgmLowerLimitValue)
  28. }
  29. set {
  30. var newDoubleValue = newValue.doubleValue(for: unit)
  31. if newDoubleValue >= urgentLowGlucoseThresholdValue {
  32. newDoubleValue = urgentLowGlucoseThresholdValue - 1
  33. }
  34. cgmLowerLimitValue = newDoubleValue
  35. }
  36. }
  37. private var urgentLowGlucoseThresholdValue: Double
  38. public var urgentLowGlucoseThreshold: HKQuantity {
  39. get {
  40. return HKQuantity.init(unit: unit, doubleValue: urgentLowGlucoseThresholdValue)
  41. }
  42. set {
  43. var newDoubleValue = newValue.doubleValue(for: unit)
  44. if newDoubleValue <= cgmLowerLimitValue {
  45. newDoubleValue = cgmLowerLimitValue + 1
  46. }
  47. if newDoubleValue >= lowGlucoseThresholdValue {
  48. newDoubleValue = lowGlucoseThresholdValue - 1
  49. }
  50. urgentLowGlucoseThresholdValue = newDoubleValue
  51. }
  52. }
  53. private var lowGlucoseThresholdValue: Double
  54. public var lowGlucoseThreshold: HKQuantity {
  55. get {
  56. return HKQuantity.init(unit: unit, doubleValue: lowGlucoseThresholdValue)
  57. }
  58. set {
  59. var newDoubleValue = newValue.doubleValue(for: unit)
  60. if newDoubleValue <= urgentLowGlucoseThresholdValue {
  61. newDoubleValue = urgentLowGlucoseThresholdValue + 1
  62. }
  63. if newDoubleValue >= highGlucoseThresholdValue {
  64. newDoubleValue = highGlucoseThresholdValue - 1
  65. }
  66. lowGlucoseThresholdValue = newDoubleValue
  67. }
  68. }
  69. private var highGlucoseThresholdValue: Double
  70. public var highGlucoseThreshold: HKQuantity {
  71. get {
  72. return HKQuantity.init(unit: unit, doubleValue: highGlucoseThresholdValue)
  73. }
  74. set {
  75. var newDoubleValue = newValue.doubleValue(for: unit)
  76. if newDoubleValue <= lowGlucoseThresholdValue {
  77. newDoubleValue = lowGlucoseThresholdValue + 1
  78. }
  79. if newDoubleValue >= cgmUpperLimitValue {
  80. newDoubleValue = cgmUpperLimitValue - 1
  81. }
  82. highGlucoseThresholdValue = newDoubleValue
  83. }
  84. }
  85. private var cgmUpperLimitValue: Double
  86. public var cgmUpperLimit: HKQuantity {
  87. get {
  88. return HKQuantity.init(unit: unit, doubleValue: cgmUpperLimitValue)
  89. }
  90. set {
  91. var newDoubleValue = newValue.doubleValue(for: unit)
  92. if newDoubleValue <= highGlucoseThresholdValue {
  93. newDoubleValue = highGlucoseThresholdValue + 1
  94. }
  95. cgmUpperLimitValue = newDoubleValue
  96. }
  97. }
  98. public var cgmStatusHighlight: MockCGMStatusHighlight?
  99. public var cgmStatusBadge: MockCGMStatusBadge?
  100. public var cgmLifecycleProgress: MockCGMLifecycleProgress? {
  101. didSet {
  102. if cgmLifecycleProgress != oldValue {
  103. setProgressColor()
  104. }
  105. }
  106. }
  107. public var progressWarningThresholdPercentValue: Double? {
  108. didSet {
  109. if progressWarningThresholdPercentValue != oldValue {
  110. setProgressColor()
  111. }
  112. }
  113. }
  114. public var progressCriticalThresholdPercentValue: Double? {
  115. didSet {
  116. if progressCriticalThresholdPercentValue != oldValue {
  117. setProgressColor()
  118. }
  119. }
  120. }
  121. public var cgmBatteryChargeRemaining: Double? = 1
  122. private mutating func setProgressColor() {
  123. guard var cgmLifecycleProgress = cgmLifecycleProgress else {
  124. return
  125. }
  126. if let progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue,
  127. cgmLifecycleProgress.percentComplete >= progressCriticalThresholdPercentValue
  128. {
  129. cgmLifecycleProgress.progressState = .critical
  130. } else if let progressWarningThresholdPercentValue = progressWarningThresholdPercentValue,
  131. cgmLifecycleProgress.percentComplete >= progressWarningThresholdPercentValue
  132. {
  133. cgmLifecycleProgress.progressState = .warning
  134. } else {
  135. cgmLifecycleProgress.progressState = .normalCGM
  136. }
  137. self.cgmLifecycleProgress = cgmLifecycleProgress
  138. }
  139. public init(isStateValid: Bool = true,
  140. glucoseRangeCategory: GlucoseRangeCategory? = nil,
  141. glucoseAlertingEnabled: Bool = false,
  142. samplesShouldBeUploaded: Bool = false,
  143. urgentLowGlucoseThresholdValue: Double = 55,
  144. lowGlucoseThresholdValue: Double = 80,
  145. highGlucoseThresholdValue: Double = 200,
  146. cgmLowerLimitValue: Double = 40,
  147. cgmUpperLimitValue: Double = 400,
  148. cgmStatusHighlight: MockCGMStatusHighlight? = nil,
  149. cgmLifecycleProgress: MockCGMLifecycleProgress? = nil,
  150. progressWarningThresholdPercentValue: Double? = nil,
  151. progressCriticalThresholdPercentValue: Double? = nil)
  152. {
  153. self.isStateValid = isStateValid
  154. self.glucoseRangeCategory = glucoseRangeCategory
  155. self.glucoseAlertingEnabled = glucoseAlertingEnabled
  156. self.samplesShouldBeUploaded = samplesShouldBeUploaded
  157. self.urgentLowGlucoseThresholdValue = urgentLowGlucoseThresholdValue
  158. self.lowGlucoseThresholdValue = lowGlucoseThresholdValue
  159. self.highGlucoseThresholdValue = highGlucoseThresholdValue
  160. self.cgmLowerLimitValue = cgmLowerLimitValue
  161. self.cgmUpperLimitValue = cgmUpperLimitValue
  162. self.cgmStatusHighlight = cgmStatusHighlight
  163. self.cgmLifecycleProgress = cgmLifecycleProgress
  164. self.progressWarningThresholdPercentValue = progressWarningThresholdPercentValue
  165. self.progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue
  166. setProgressColor()
  167. }
  168. }
  169. public struct MockCGMStatusHighlight: DeviceStatusHighlight {
  170. public var localizedMessage: String
  171. public var imageName: String {
  172. switch alertIdentifier {
  173. case MockCGMManager.submarine.identifier:
  174. return "dot.radiowaves.left.and.right"
  175. case MockCGMManager.buzz.identifier:
  176. return "clock"
  177. default:
  178. return "exclamationmark.circle.fill"
  179. }
  180. }
  181. public var state: DeviceStatusHighlightState{
  182. switch alertIdentifier {
  183. case MockCGMManager.submarine.identifier:
  184. return .normalCGM
  185. case MockCGMManager.buzz.identifier:
  186. return .warning
  187. default:
  188. return .critical
  189. }
  190. }
  191. public var alertIdentifier: Alert.AlertIdentifier
  192. }
  193. public struct MockCGMStatusBadge: DeviceStatusBadge {
  194. public var image: UIImage? {
  195. return badgeType.image
  196. }
  197. public var state: DeviceStatusBadgeState {
  198. switch badgeType {
  199. case .lowBattery:
  200. return .critical
  201. case .calibrationRequested:
  202. return .warning
  203. }
  204. }
  205. public var badgeType: MockCGMStatusBadgeType
  206. public enum MockCGMStatusBadgeType: Int, CaseIterable {
  207. case lowBattery
  208. case calibrationRequested
  209. var image: UIImage? {
  210. switch self {
  211. case .lowBattery:
  212. return UIImage(frameworkImage: "battery.circle.fill")
  213. case .calibrationRequested:
  214. return UIImage(frameworkImage: "drop.circle.fill")
  215. }
  216. }
  217. }
  218. init(badgeType: MockCGMStatusBadgeType) {
  219. self.badgeType = badgeType
  220. }
  221. }
  222. public struct MockCGMLifecycleProgress: DeviceLifecycleProgress, Equatable {
  223. public var percentComplete: Double
  224. public var progressState: DeviceLifecycleProgressState
  225. public init(percentComplete: Double, progressState: DeviceLifecycleProgressState = .normalCGM) {
  226. self.percentComplete = percentComplete
  227. self.progressState = progressState
  228. }
  229. }
  230. extension MockCGMLifecycleProgress: RawRepresentable {
  231. public typealias RawValue = [String: Any]
  232. public init?(rawValue: RawValue) {
  233. guard let percentComplete = rawValue["percentComplete"] as? Double,
  234. let progressStateRawValue = rawValue["progressState"] as? DeviceLifecycleProgressState.RawValue,
  235. let progressState = DeviceLifecycleProgressState(rawValue: progressStateRawValue) else
  236. {
  237. return nil
  238. }
  239. self.percentComplete = percentComplete
  240. self.progressState = progressState
  241. }
  242. public var rawValue: RawValue {
  243. let rawValue: RawValue = [
  244. "percentComplete": percentComplete,
  245. "progressState": progressState.rawValue,
  246. ]
  247. return rawValue
  248. }
  249. }
  250. public final class MockCGMManager: TestingCGMManager {
  251. public static let managerIdentifier = "MockCGMManager"
  252. public var managerIdentifier: String {
  253. return MockCGMManager.managerIdentifier
  254. }
  255. public static let localizedTitle = "CGM Simulator"
  256. public var localizedTitle: String {
  257. return MockCGMManager.localizedTitle
  258. }
  259. public struct MockAlert {
  260. public let sound: Alert.Sound
  261. public let identifier: Alert.AlertIdentifier
  262. public let foregroundContent: Alert.Content
  263. public let backgroundContent: Alert.Content
  264. public let interruptionLevel: Alert.InterruptionLevel
  265. }
  266. let alerts: [Alert.AlertIdentifier: MockAlert] = [
  267. submarine.identifier: submarine, buzz.identifier: buzz, critical.identifier: critical, signalLoss.identifier: signalLoss
  268. ]
  269. public static let submarine = MockAlert(sound: .sound(name: "sub.caf"), identifier: "submarine",
  270. foregroundContent: Alert.Content(title: "Alert: FG Title", body: "Alert: Foreground Body", acknowledgeActionButtonLabel: "FG OK"),
  271. backgroundContent: Alert.Content(title: "Alert: BG Title", body: "Alert: Background Body", acknowledgeActionButtonLabel: "BG OK"),
  272. interruptionLevel: .timeSensitive)
  273. public static let critical = MockAlert(sound: .sound(name: "critical.caf"), identifier: "critical",
  274. foregroundContent: Alert.Content(title: "Critical Alert: FG Title", body: "Critical Alert: Foreground Body", acknowledgeActionButtonLabel: "Critical FG OK"),
  275. backgroundContent: Alert.Content(title: "Critical Alert: BG Title", body: "Critical Alert: Background Body", acknowledgeActionButtonLabel: "Critical BG OK"),
  276. interruptionLevel: .critical)
  277. public static let buzz = MockAlert(sound: .vibrate, identifier: "buzz",
  278. foregroundContent: Alert.Content(title: "Alert: FG Title", body: "FG bzzzt", acknowledgeActionButtonLabel: "Buzz"),
  279. backgroundContent: Alert.Content(title: "Alert: BG Title", body: "BG bzzzt", acknowledgeActionButtonLabel: "Buzz"),
  280. interruptionLevel: .active)
  281. public static let signalLoss = MockAlert(sound: .sound(name: "critical.caf"),
  282. identifier: "signalLoss",
  283. foregroundContent: Alert.Content(title: "Signal Loss", body: "CGM simulator signal loss", acknowledgeActionButtonLabel: "Dismiss"),
  284. backgroundContent: Alert.Content(title: "Signal Loss", body: "CGM simulator signal loss", acknowledgeActionButtonLabel: "Dismiss"),
  285. interruptionLevel: .critical)
  286. private let lockedMockSensorState = Locked(MockCGMState(isStateValid: true))
  287. public var mockSensorState: MockCGMState {
  288. get {
  289. lockedMockSensorState.value
  290. }
  291. set {
  292. lockedMockSensorState.mutate { $0 = newValue }
  293. self.notifyStatusObservers(cgmManagerStatus: self.cgmManagerStatus)
  294. }
  295. }
  296. public var glucoseDisplay: GlucoseDisplayable? {
  297. return mockSensorState
  298. }
  299. public var cgmManagerStatus: CGMManagerStatus {
  300. return CGMManagerStatus(hasValidSensorSession: dataSource.isValidSession, lastCommunicationDate: lastCommunicationDate, device: device)
  301. }
  302. private var lastCommunicationDate: Date? = nil
  303. public var testingDevice: HKDevice {
  304. return MockCGMDataSource.device
  305. }
  306. public var device: HKDevice? {
  307. return testingDevice
  308. }
  309. public weak var cgmManagerDelegate: CGMManagerDelegate? {
  310. get {
  311. return delegate.delegate
  312. }
  313. set {
  314. delegate.delegate = newValue
  315. }
  316. }
  317. public var delegateQueue: DispatchQueue! {
  318. get {
  319. return delegate.queue
  320. }
  321. set {
  322. delegate.queue = newValue
  323. }
  324. }
  325. private let delegate = WeakSynchronizedDelegate<CGMManagerDelegate>()
  326. private let lockedDataSource = Locked(MockCGMDataSource(model: .noData))
  327. public var dataSource: MockCGMDataSource {
  328. get {
  329. lockedDataSource.value
  330. }
  331. set {
  332. lockedDataSource.mutate { $0 = newValue }
  333. self.notifyStatusObservers(cgmManagerStatus: self.cgmManagerStatus)
  334. }
  335. }
  336. private var glucoseUpdateTimer: Timer?
  337. public init() {
  338. setupGlucoseUpdateTimer()
  339. }
  340. // MARK: Handling CGM Manager Status observers
  341. private var statusObservers = WeakSynchronizedSet<CGMManagerStatusObserver>()
  342. public func addStatusObserver(_ observer: CGMManagerStatusObserver, queue: DispatchQueue) {
  343. statusObservers.insert(observer, queue: queue)
  344. }
  345. public func removeStatusObserver(_ observer: CGMManagerStatusObserver) {
  346. statusObservers.removeElement(observer)
  347. }
  348. private func notifyStatusObservers(cgmManagerStatus: CGMManagerStatus) {
  349. delegate.notify { delegate in
  350. delegate?.cgmManagerDidUpdateState(self)
  351. delegate?.cgmManager(self, didUpdate: self.cgmManagerStatus)
  352. }
  353. statusObservers.forEach { observer in
  354. observer.cgmManager(self, didUpdate: cgmManagerStatus)
  355. }
  356. }
  357. public init?(rawState: RawStateValue) {
  358. if let mockSensorStateRawValue = rawState["mockSensorState"] as? MockCGMState.RawValue,
  359. let mockSensorState = MockCGMState(rawValue: mockSensorStateRawValue) {
  360. self.lockedMockSensorState.value = mockSensorState
  361. } else {
  362. self.lockedMockSensorState.value = MockCGMState(isStateValid: true)
  363. }
  364. if let dataSourceRawValue = rawState["dataSource"] as? MockCGMDataSource.RawValue,
  365. let dataSource = MockCGMDataSource(rawValue: dataSourceRawValue) {
  366. self.lockedDataSource.value = dataSource
  367. } else {
  368. self.lockedDataSource.value = MockCGMDataSource(model: .sineCurve(parameters: (baseGlucose: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 110), amplitude: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 20), period: TimeInterval(hours: 6), referenceDate: Date())))
  369. }
  370. setupGlucoseUpdateTimer()
  371. }
  372. deinit {
  373. glucoseUpdateTimer?.invalidate()
  374. }
  375. public var rawState: RawStateValue {
  376. return [
  377. "mockSensorState": mockSensorState.rawValue,
  378. "dataSource": dataSource.rawValue
  379. ]
  380. }
  381. public let isOnboarded = true // No distinction between created and onboarded
  382. public let appURL: URL? = nil
  383. public let providesBLEHeartbeat = false
  384. public let managedDataInterval: TimeInterval? = nil
  385. public var shouldSyncToRemoteService: Bool {
  386. return self.mockSensorState.samplesShouldBeUploaded
  387. }
  388. public var healthKitStorageDelayEnabled: Bool {
  389. get {
  390. MockCGMManager.healthKitStorageDelay == fixedHealthKitStorageDelay
  391. }
  392. set {
  393. MockCGMManager.healthKitStorageDelay = newValue ? fixedHealthKitStorageDelay : 0
  394. }
  395. }
  396. public let fixedHealthKitStorageDelay: TimeInterval = .minutes(2)
  397. public static var healthKitStorageDelay: TimeInterval = 0
  398. private func logDeviceComms(_ type: DeviceLogEntryType, message: String) {
  399. self.delegate.delegate?.deviceManager(self, logEventForDeviceIdentifier: "mockcgm", type: type, message: message, completion: nil)
  400. }
  401. private func sendCGMReadingResult(_ result: CGMReadingResult) {
  402. if case .newData(let samples) = result,
  403. let currentValue = samples.first
  404. {
  405. mockSensorState.trendType = currentValue.trend
  406. mockSensorState.trendRate = currentValue.trendRate
  407. mockSensorState.glucoseRangeCategory = glucoseRangeCategory(for: currentValue.quantitySample)
  408. issueAlert(for: currentValue)
  409. }
  410. self.delegate.notify { delegate in
  411. delegate?.cgmManager(self, hasNew: result)
  412. }
  413. }
  414. public func glucoseRangeCategory(for glucose: GlucoseSampleValue) -> GlucoseRangeCategory? {
  415. switch glucose.quantity {
  416. case ...mockSensorState.cgmLowerLimit:
  417. return glucose.wasUserEntered ? .urgentLow : .belowRange
  418. case mockSensorState.cgmLowerLimit..<mockSensorState.urgentLowGlucoseThreshold:
  419. return .urgentLow
  420. case mockSensorState.urgentLowGlucoseThreshold..<mockSensorState.lowGlucoseThreshold:
  421. return .low
  422. case mockSensorState.lowGlucoseThreshold..<mockSensorState.highGlucoseThreshold:
  423. return .normal
  424. case mockSensorState.highGlucoseThreshold..<mockSensorState.cgmUpperLimit:
  425. return .high
  426. default:
  427. return glucose.wasUserEntered ? .high : .aboveRange
  428. }
  429. }
  430. public func fetchNewDataIfNeeded(_ completion: @escaping (CGMReadingResult) -> Void) {
  431. let now = Date()
  432. logDeviceComms(.send, message: "Fetch new data")
  433. dataSource.fetchNewData { (result) in
  434. switch result {
  435. case .error(let error):
  436. self.logDeviceComms(.error, message: "Error fetching new data: \(error)")
  437. case .newData(let samples):
  438. self.lastCommunicationDate = now
  439. self.logDeviceComms(.receive, message: "New data received: \(samples)")
  440. case .unreliableData:
  441. self.lastCommunicationDate = now
  442. self.logDeviceComms(.receive, message: "Unreliable data received")
  443. case .noData:
  444. self.lastCommunicationDate = now
  445. self.logDeviceComms(.receive, message: "No new data")
  446. }
  447. completion(result)
  448. }
  449. }
  450. public func backfillData(datingBack duration: TimeInterval) {
  451. let now = Date()
  452. self.logDeviceComms(.send, message: "backfillData(\(duration))")
  453. dataSource.backfillData(from: DateInterval(start: now.addingTimeInterval(-duration), end: now)) { result in
  454. switch result {
  455. case .error(let error):
  456. self.logDeviceComms(.error, message: "Backfill error: \(error)")
  457. case .newData(let samples):
  458. self.logDeviceComms(.receive, message: "Backfill data: \(samples)")
  459. case .unreliableData:
  460. self.logDeviceComms(.receive, message: "Backfill data unreliable")
  461. case .noData:
  462. self.logDeviceComms(.receive, message: "Backfill empty")
  463. }
  464. self.sendCGMReadingResult(result)
  465. }
  466. }
  467. public func updateGlucoseUpdateTimer() {
  468. glucoseUpdateTimer?.invalidate()
  469. setupGlucoseUpdateTimer()
  470. }
  471. private func setupGlucoseUpdateTimer() {
  472. glucoseUpdateTimer = Timer.scheduledTimer(withTimeInterval: dataSource.dataPointFrequency.frequency, repeats: true) { [weak self] _ in
  473. guard let self = self else { return }
  474. self.fetchNewDataIfNeeded() { result in
  475. self.sendCGMReadingResult(result)
  476. }
  477. }
  478. }
  479. public func injectGlucoseSamples(_ samples: [NewGlucoseSample]) {
  480. guard !samples.isEmpty else { return }
  481. sendCGMReadingResult(CGMReadingResult.newData(samples.map { NewGlucoseSample($0, device: device) } ))
  482. }
  483. }
  484. fileprivate extension NewGlucoseSample {
  485. init(_ other: NewGlucoseSample, device: HKDevice?) {
  486. self.init(date: other.date,
  487. quantity: other.quantity,
  488. condition: other.condition,
  489. trend: other.trend,
  490. trendRate: other.trendRate,
  491. isDisplayOnly: other.isDisplayOnly,
  492. wasUserEntered: other.wasUserEntered,
  493. syncIdentifier: other.syncIdentifier,
  494. syncVersion: other.syncVersion,
  495. device: device)
  496. }
  497. }
  498. // MARK: Alert Stuff
  499. extension MockCGMManager {
  500. public func getSoundBaseURL() -> URL? {
  501. return Bundle(for: type(of: self)).bundleURL
  502. }
  503. public func getSounds() -> [Alert.Sound] {
  504. return alerts.map { $1.sound }
  505. }
  506. public var hasRetractableAlert: Bool {
  507. // signal loss alerts can only be removed by switching the CGM data source
  508. return currentAlertIdentifier != nil && currentAlertIdentifier != MockCGMManager.signalLoss.identifier
  509. }
  510. public var currentAlertIdentifier: Alert.AlertIdentifier? {
  511. return mockSensorState.cgmStatusHighlight?.alertIdentifier
  512. }
  513. public func issueAlert(identifier: Alert.AlertIdentifier, trigger: Alert.Trigger, delay: TimeInterval?, metadata: Alert.Metadata? = nil) {
  514. guard let alert = alerts[identifier] else {
  515. return
  516. }
  517. delegate.notifyDelayed(by: delay ?? 0) { delegate in
  518. self.logDeviceComms(.delegate, message: "\(#function): \(identifier) \(trigger)")
  519. delegate?.issueAlert(Alert(identifier: Alert.Identifier(managerIdentifier: self.managerIdentifier, alertIdentifier: identifier),
  520. foregroundContent: alert.foregroundContent,
  521. backgroundContent: alert.backgroundContent,
  522. trigger: trigger,
  523. interruptionLevel: alert.interruptionLevel,
  524. sound: alert.sound,
  525. metadata: metadata))
  526. }
  527. // updating the status highlight
  528. setStatusHighlight(MockCGMStatusHighlight(localizedMessage: alert.foregroundContent.title, alertIdentifier: alert.identifier))
  529. }
  530. public func issueSignalLossAlert() {
  531. issueAlert(identifier: MockCGMManager.signalLoss.identifier, trigger: .immediate, delay: nil)
  532. }
  533. public func retractSignalLossAlert() {
  534. retractAlert(identifier: MockCGMManager.signalLoss.identifier)
  535. }
  536. public func acknowledgeAlert(alertIdentifier: Alert.AlertIdentifier, completion: @escaping (Error?) -> Void) {
  537. self.logDeviceComms(.delegateResponse, message: "\(#function): Alert \(alertIdentifier) acknowledged.")
  538. completion(nil)
  539. }
  540. public func retractCurrentAlert() {
  541. guard hasRetractableAlert, let identifier = currentAlertIdentifier else { return }
  542. retractAlert(identifier: identifier)
  543. }
  544. public func retractAlert(identifier: Alert.AlertIdentifier) {
  545. delegate.notify { $0?.retractAlert(identifier: Alert.Identifier(managerIdentifier: self.managerIdentifier, alertIdentifier: identifier)) }
  546. // updating the status highlight
  547. if mockSensorState.cgmStatusHighlight?.alertIdentifier == identifier {
  548. setStatusHighlight(nil)
  549. }
  550. }
  551. public func setStatusHighlight(_ statusHighlight: MockCGMStatusHighlight?) {
  552. mockSensorState.cgmStatusHighlight = statusHighlight
  553. if statusHighlight == nil,
  554. case .signalLoss = dataSource.model
  555. {
  556. // restore signal loss status highlight
  557. issueSignalLossAlert()
  558. }
  559. }
  560. private func issueAlert(for glucose: NewGlucoseSample) {
  561. guard mockSensorState.glucoseAlertingEnabled else {
  562. return
  563. }
  564. let alertTitle: String
  565. let glucoseAlertIdentifier: String
  566. let interruptionLevel: Alert.InterruptionLevel
  567. switch glucose.quantity {
  568. case ...mockSensorState.urgentLowGlucoseThreshold:
  569. alertTitle = "Urgent Low Glucose Alert"
  570. glucoseAlertIdentifier = "glucose.value.low.urgent"
  571. interruptionLevel = .critical
  572. case mockSensorState.urgentLowGlucoseThreshold..<mockSensorState.lowGlucoseThreshold:
  573. alertTitle = "Low Glucose Alert"
  574. glucoseAlertIdentifier = "glucose.value.low"
  575. interruptionLevel = .timeSensitive
  576. case mockSensorState.highGlucoseThreshold...:
  577. alertTitle = "High Glucose Alert"
  578. glucoseAlertIdentifier = "glucose.value.high"
  579. interruptionLevel = .timeSensitive
  580. default:
  581. return
  582. }
  583. let alertIdentifier = Alert.Identifier(managerIdentifier: self.managerIdentifier,
  584. alertIdentifier: glucoseAlertIdentifier)
  585. let alertContent = Alert.Content(title: alertTitle,
  586. body: "The glucose measurement received triggered this alert",
  587. acknowledgeActionButtonLabel: "Dismiss")
  588. let alert = Alert(identifier: alertIdentifier,
  589. foregroundContent: alertContent,
  590. backgroundContent: alertContent,
  591. trigger: .immediate,
  592. interruptionLevel: interruptionLevel)
  593. delegate.notify { delegate in
  594. delegate?.issueAlert(alert)
  595. }
  596. }
  597. }
  598. //MARK: Device Status Badge stuff
  599. extension MockCGMManager {
  600. public func requestCalibration(_ requestCalibration: Bool) {
  601. mockSensorState.cgmStatusBadge = requestCalibration ? MockCGMStatusBadge(badgeType: .calibrationRequested) : nil
  602. checkAndSetBatteryBadge()
  603. }
  604. public var cgmBatteryChargeRemaining: Double? {
  605. get {
  606. return mockSensorState.cgmBatteryChargeRemaining
  607. }
  608. set {
  609. mockSensorState.cgmBatteryChargeRemaining = newValue
  610. checkAndSetBatteryBadge()
  611. }
  612. }
  613. public var isCalibrationRequested: Bool {
  614. return mockSensorState.cgmStatusBadge?.badgeType == .calibrationRequested
  615. }
  616. private func checkAndSetBatteryBadge() {
  617. // calibration badge is the highest priority
  618. guard mockSensorState.cgmStatusBadge?.badgeType != .calibrationRequested else {
  619. return
  620. }
  621. guard let cgmBatteryChargeRemaining = mockSensorState.cgmBatteryChargeRemaining,
  622. cgmBatteryChargeRemaining > 0.5 else
  623. {
  624. mockSensorState.cgmStatusBadge = MockCGMStatusBadge(badgeType: .lowBattery)
  625. return
  626. }
  627. mockSensorState.cgmStatusBadge = nil
  628. }
  629. }
  630. extension MockCGMManager {
  631. public var debugDescription: String {
  632. return """
  633. ## MockCGMManager
  634. state: \(mockSensorState)
  635. dataSource: \(dataSource)
  636. """
  637. }
  638. }
  639. extension MockCGMState: RawRepresentable {
  640. public typealias RawValue = [String: Any]
  641. public init?(rawValue: RawValue) {
  642. guard let isStateValid = rawValue["isStateValid"] as? Bool,
  643. let glucoseAlertingEnabled = rawValue["glucoseAlertingEnabled"] as? Bool,
  644. let urgentLowGlucoseThresholdValue = rawValue["urgentLowGlucoseThresholdValue"] as? Double,
  645. let lowGlucoseThresholdValue = rawValue["lowGlucoseThresholdValue"] as? Double,
  646. let highGlucoseThresholdValue = rawValue["highGlucoseThresholdValue"] as? Double,
  647. let cgmLowerLimitValue = rawValue["cgmLowerLimitValue"] as? Double,
  648. let cgmUpperLimitValue = rawValue["cgmUpperLimitValue"] as? Double else
  649. {
  650. return nil
  651. }
  652. self.isStateValid = isStateValid
  653. self.glucoseAlertingEnabled = glucoseAlertingEnabled
  654. self.samplesShouldBeUploaded = rawValue["samplesShouldBeUploaded"] as? Bool ?? false
  655. self.urgentLowGlucoseThresholdValue = urgentLowGlucoseThresholdValue
  656. self.lowGlucoseThresholdValue = lowGlucoseThresholdValue
  657. self.highGlucoseThresholdValue = highGlucoseThresholdValue
  658. self.cgmLowerLimitValue = cgmLowerLimitValue
  659. self.cgmUpperLimitValue = cgmUpperLimitValue
  660. if let glucoseRangeCategoryRawValue = rawValue["glucoseRangeCategory"] as? GlucoseRangeCategory.RawValue {
  661. self.glucoseRangeCategory = GlucoseRangeCategory(rawValue: glucoseRangeCategoryRawValue)
  662. }
  663. if let localizedMessage = rawValue["localizedMessage"] as? String,
  664. let alertIdentifier = rawValue["alertIdentifier"] as? Alert.AlertIdentifier
  665. {
  666. self.cgmStatusHighlight = MockCGMStatusHighlight(localizedMessage: localizedMessage, alertIdentifier: alertIdentifier)
  667. }
  668. if let statusBadgeTypeRawValue = rawValue["statusBadgeType"] as? MockCGMStatusBadge.MockCGMStatusBadgeType.RawValue,
  669. let statusBadgeType = MockCGMStatusBadge.MockCGMStatusBadgeType(rawValue: statusBadgeTypeRawValue)
  670. {
  671. self.cgmStatusBadge = MockCGMStatusBadge(badgeType: statusBadgeType)
  672. }
  673. if let cgmLifecycleProgressRawValue = rawValue["cgmLifecycleProgress"] as? MockCGMLifecycleProgress.RawValue {
  674. self.cgmLifecycleProgress = MockCGMLifecycleProgress(rawValue: cgmLifecycleProgressRawValue)
  675. }
  676. self.progressWarningThresholdPercentValue = rawValue["progressWarningThresholdPercentValue"] as? Double
  677. self.progressCriticalThresholdPercentValue = rawValue["progressCriticalThresholdPercentValue"] as? Double
  678. self.cgmBatteryChargeRemaining = rawValue["cgmBatteryChargeRemaining"] as? Double
  679. setProgressColor()
  680. }
  681. public var rawValue: RawValue {
  682. var rawValue: RawValue = [
  683. "isStateValid": isStateValid,
  684. "glucoseAlertingEnabled": glucoseAlertingEnabled,
  685. "samplesShouldBeUploaded": samplesShouldBeUploaded,
  686. "urgentLowGlucoseThresholdValue": urgentLowGlucoseThresholdValue,
  687. "lowGlucoseThresholdValue": lowGlucoseThresholdValue,
  688. "highGlucoseThresholdValue": highGlucoseThresholdValue,
  689. "cgmLowerLimitValue": cgmLowerLimitValue,
  690. "cgmUpperLimitValue": cgmUpperLimitValue,
  691. ]
  692. if let glucoseRangeCategory = glucoseRangeCategory {
  693. rawValue["glucoseRangeCategory"] = glucoseRangeCategory.rawValue
  694. }
  695. if let cgmStatusHighlight = cgmStatusHighlight {
  696. rawValue["localizedMessage"] = cgmStatusHighlight.localizedMessage
  697. rawValue["alertIdentifier"] = cgmStatusHighlight.alertIdentifier
  698. }
  699. if let cgmStatusBadgeType = cgmStatusBadge?.badgeType {
  700. rawValue["statusBadgeType"] = cgmStatusBadgeType.rawValue
  701. }
  702. if let cgmLifecycleProgress = cgmLifecycleProgress {
  703. rawValue["cgmLifecycleProgress"] = cgmLifecycleProgress.rawValue
  704. }
  705. if let progressWarningThresholdPercentValue = progressWarningThresholdPercentValue {
  706. rawValue["progressWarningThresholdPercentValue"] = progressWarningThresholdPercentValue
  707. }
  708. if let progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue {
  709. rawValue["progressCriticalThresholdPercentValue"] = progressCriticalThresholdPercentValue
  710. }
  711. if let cgmBatteryChargeRemaining = cgmBatteryChargeRemaining {
  712. rawValue["cgmBatteryChargeRemaining"] = cgmBatteryChargeRemaining
  713. }
  714. return rawValue
  715. }
  716. }
  717. extension MockCGMState: CustomDebugStringConvertible {
  718. public var debugDescription: String {
  719. return """
  720. ## MockCGMState
  721. * isStateValid: \(isStateValid)
  722. * glucoseAlertingEnabled: \(glucoseAlertingEnabled)
  723. * samplesShouldBeUploaded: \(samplesShouldBeUploaded)
  724. * urgentLowGlucoseThresholdValue: \(urgentLowGlucoseThresholdValue)
  725. * lowGlucoseThresholdValue: \(lowGlucoseThresholdValue)
  726. * highGlucoseThresholdValue: \(highGlucoseThresholdValue)
  727. * cgmLowerLimitValue: \(cgmLowerLimitValue)
  728. * cgmUpperLimitValue: \(cgmUpperLimitValue)
  729. * highGlucoseThresholdValue: \(highGlucoseThresholdValue)
  730. * glucoseRangeCategory: \(glucoseRangeCategory as Any)
  731. * cgmStatusHighlight: \(cgmStatusHighlight as Any)
  732. * cgmStatusBadge: \(cgmStatusBadge as Any)
  733. * cgmLifecycleProgress: \(cgmLifecycleProgress as Any)
  734. * progressWarningThresholdPercentValue: \(progressWarningThresholdPercentValue as Any)
  735. * progressCriticalThresholdPercentValue: \(progressCriticalThresholdPercentValue as Any)
  736. * cgmBatteryChargeRemaining: \(cgmBatteryChargeRemaining as Any)
  737. """
  738. }
  739. }