MockCGMManager.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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 logDeviceCommunication(_ message: String, type: DeviceLogEntryType = .send) {
  399. self.delegate.delegate?.deviceManager(self, logEventForDeviceIdentifier: "MockId", type: type, message: message, completion: nil)
  400. }
  401. private func logDeviceComms(_ type: DeviceLogEntryType, message: String) {
  402. self.delegate.delegate?.deviceManager(self, logEventForDeviceIdentifier: "mockcgm", type: type, message: message, completion: nil)
  403. }
  404. private func sendCGMReadingResult(_ result: CGMReadingResult) {
  405. if case .newData(let samples) = result,
  406. let currentValue = samples.first
  407. {
  408. mockSensorState.trendType = currentValue.trend
  409. mockSensorState.trendRate = currentValue.trendRate
  410. mockSensorState.glucoseRangeCategory = glucoseRangeCategory(for: currentValue.quantitySample)
  411. issueAlert(for: currentValue)
  412. }
  413. self.delegate.notify { delegate in
  414. delegate?.cgmManager(self, hasNew: result)
  415. }
  416. }
  417. public func glucoseRangeCategory(for glucose: GlucoseSampleValue) -> GlucoseRangeCategory? {
  418. switch glucose.quantity {
  419. case ...mockSensorState.cgmLowerLimit:
  420. return glucose.wasUserEntered ? .urgentLow : .belowRange
  421. case mockSensorState.cgmLowerLimit..<mockSensorState.urgentLowGlucoseThreshold:
  422. return .urgentLow
  423. case mockSensorState.urgentLowGlucoseThreshold..<mockSensorState.lowGlucoseThreshold:
  424. return .low
  425. case mockSensorState.lowGlucoseThreshold..<mockSensorState.highGlucoseThreshold:
  426. return .normal
  427. case mockSensorState.highGlucoseThreshold..<mockSensorState.cgmUpperLimit:
  428. return .high
  429. default:
  430. return glucose.wasUserEntered ? .high : .aboveRange
  431. }
  432. }
  433. public func fetchNewDataIfNeeded(_ completion: @escaping (CGMReadingResult) -> Void) {
  434. let now = Date()
  435. logDeviceComms(.send, message: "Fetch new data")
  436. dataSource.fetchNewData { (result) in
  437. switch result {
  438. case .error(let error):
  439. self.logDeviceComms(.error, message: "Error fetching new data: \(error)")
  440. case .newData(let samples):
  441. self.lastCommunicationDate = now
  442. self.logDeviceComms(.receive, message: "New data received: \(samples)")
  443. case .unreliableData:
  444. self.lastCommunicationDate = now
  445. self.logDeviceComms(.receive, message: "Unreliable data received")
  446. case .noData:
  447. self.lastCommunicationDate = now
  448. self.logDeviceComms(.receive, message: "No new data")
  449. }
  450. completion(result)
  451. }
  452. }
  453. public func backfillData(datingBack duration: TimeInterval) {
  454. let now = Date()
  455. self.logDeviceCommunication("backfillData(\(duration))")
  456. dataSource.backfillData(from: DateInterval(start: now.addingTimeInterval(-duration), end: now)) { result in
  457. switch result {
  458. case .error(let error):
  459. self.logDeviceComms(.error, message: "Backfill error: \(error)")
  460. case .newData(let samples):
  461. self.logDeviceComms(.receive, message: "Backfill data: \(samples)")
  462. case .unreliableData:
  463. self.logDeviceComms(.receive, message: "Backfill data unreliable")
  464. case .noData:
  465. self.logDeviceComms(.receive, message: "Backfill empty")
  466. }
  467. self.sendCGMReadingResult(result)
  468. }
  469. }
  470. public func updateGlucoseUpdateTimer() {
  471. glucoseUpdateTimer?.invalidate()
  472. setupGlucoseUpdateTimer()
  473. }
  474. private func setupGlucoseUpdateTimer() {
  475. glucoseUpdateTimer = Timer.scheduledTimer(withTimeInterval: dataSource.dataPointFrequency.frequency, repeats: true) { [weak self] _ in
  476. guard let self = self else { return }
  477. self.fetchNewDataIfNeeded() { result in
  478. self.sendCGMReadingResult(result)
  479. }
  480. }
  481. }
  482. public func injectGlucoseSamples(_ samples: [NewGlucoseSample]) {
  483. guard !samples.isEmpty else { return }
  484. sendCGMReadingResult(CGMReadingResult.newData(samples.map { NewGlucoseSample($0, device: device) } ))
  485. }
  486. }
  487. fileprivate extension NewGlucoseSample {
  488. init(_ other: NewGlucoseSample, device: HKDevice?) {
  489. self.init(date: other.date,
  490. quantity: other.quantity,
  491. condition: other.condition,
  492. trend: other.trend,
  493. trendRate: other.trendRate,
  494. isDisplayOnly: other.isDisplayOnly,
  495. wasUserEntered: other.wasUserEntered,
  496. syncIdentifier: other.syncIdentifier,
  497. syncVersion: other.syncVersion,
  498. device: device)
  499. }
  500. }
  501. // MARK: Alert Stuff
  502. extension MockCGMManager {
  503. public func getSoundBaseURL() -> URL? {
  504. return Bundle(for: type(of: self)).bundleURL
  505. }
  506. public func getSounds() -> [Alert.Sound] {
  507. return alerts.map { $1.sound }
  508. }
  509. public var hasRetractableAlert: Bool {
  510. // signal loss alerts can only be removed by switching the CGM data source
  511. return currentAlertIdentifier != nil && currentAlertIdentifier != MockCGMManager.signalLoss.identifier
  512. }
  513. public var currentAlertIdentifier: Alert.AlertIdentifier? {
  514. return mockSensorState.cgmStatusHighlight?.alertIdentifier
  515. }
  516. public func issueAlert(identifier: Alert.AlertIdentifier, trigger: Alert.Trigger, delay: TimeInterval?, metadata: Alert.Metadata? = nil) {
  517. guard let alert = alerts[identifier] else {
  518. return
  519. }
  520. delegate.notifyDelayed(by: delay ?? 0) { delegate in
  521. self.logDeviceComms(.delegate, message: "\(#function): \(identifier) \(trigger)")
  522. delegate?.issueAlert(Alert(identifier: Alert.Identifier(managerIdentifier: self.managerIdentifier, alertIdentifier: identifier),
  523. foregroundContent: alert.foregroundContent,
  524. backgroundContent: alert.backgroundContent,
  525. trigger: trigger,
  526. interruptionLevel: alert.interruptionLevel,
  527. sound: alert.sound,
  528. metadata: metadata))
  529. }
  530. // updating the status highlight
  531. setStatusHighlight(MockCGMStatusHighlight(localizedMessage: alert.foregroundContent.title, alertIdentifier: alert.identifier))
  532. }
  533. public func issueSignalLossAlert() {
  534. issueAlert(identifier: MockCGMManager.signalLoss.identifier, trigger: .immediate, delay: nil)
  535. }
  536. public func retractSignalLossAlert() {
  537. retractAlert(identifier: MockCGMManager.signalLoss.identifier)
  538. }
  539. public func acknowledgeAlert(alertIdentifier: Alert.AlertIdentifier, completion: @escaping (Error?) -> Void) {
  540. self.logDeviceComms(.delegateResponse, message: "\(#function): Alert \(alertIdentifier) acknowledged.")
  541. completion(nil)
  542. }
  543. public func retractCurrentAlert() {
  544. guard hasRetractableAlert, let identifier = currentAlertIdentifier else { return }
  545. retractAlert(identifier: identifier)
  546. }
  547. public func retractAlert(identifier: Alert.AlertIdentifier) {
  548. delegate.notify { $0?.retractAlert(identifier: Alert.Identifier(managerIdentifier: self.managerIdentifier, alertIdentifier: identifier)) }
  549. // updating the status highlight
  550. if mockSensorState.cgmStatusHighlight?.alertIdentifier == identifier {
  551. setStatusHighlight(nil)
  552. }
  553. }
  554. public func setStatusHighlight(_ statusHighlight: MockCGMStatusHighlight?) {
  555. mockSensorState.cgmStatusHighlight = statusHighlight
  556. if statusHighlight == nil,
  557. case .signalLoss = dataSource.model
  558. {
  559. // restore signal loss status highlight
  560. issueSignalLossAlert()
  561. }
  562. }
  563. private func issueAlert(for glucose: NewGlucoseSample) {
  564. guard mockSensorState.glucoseAlertingEnabled else {
  565. return
  566. }
  567. let alertTitle: String
  568. let glucoseAlertIdentifier: String
  569. let interruptionLevel: Alert.InterruptionLevel
  570. switch glucose.quantity {
  571. case ...mockSensorState.urgentLowGlucoseThreshold:
  572. alertTitle = "Urgent Low Glucose Alert"
  573. glucoseAlertIdentifier = "glucose.value.low.urgent"
  574. interruptionLevel = .critical
  575. case mockSensorState.urgentLowGlucoseThreshold..<mockSensorState.lowGlucoseThreshold:
  576. alertTitle = "Low Glucose Alert"
  577. glucoseAlertIdentifier = "glucose.value.low"
  578. interruptionLevel = .timeSensitive
  579. case mockSensorState.highGlucoseThreshold...:
  580. alertTitle = "High Glucose Alert"
  581. glucoseAlertIdentifier = "glucose.value.high"
  582. interruptionLevel = .timeSensitive
  583. default:
  584. return
  585. }
  586. let alertIdentifier = Alert.Identifier(managerIdentifier: self.managerIdentifier,
  587. alertIdentifier: glucoseAlertIdentifier)
  588. let alertContent = Alert.Content(title: alertTitle,
  589. body: "The glucose measurement received triggered this alert",
  590. acknowledgeActionButtonLabel: "Dismiss")
  591. let alert = Alert(identifier: alertIdentifier,
  592. foregroundContent: alertContent,
  593. backgroundContent: alertContent,
  594. trigger: .immediate,
  595. interruptionLevel: interruptionLevel)
  596. delegate.notify { delegate in
  597. delegate?.issueAlert(alert)
  598. }
  599. }
  600. }
  601. //MARK: Device Status Badge stuff
  602. extension MockCGMManager {
  603. public func requestCalibration(_ requestCalibration: Bool) {
  604. mockSensorState.cgmStatusBadge = requestCalibration ? MockCGMStatusBadge(badgeType: .calibrationRequested) : nil
  605. checkAndSetBatteryBadge()
  606. }
  607. public var cgmBatteryChargeRemaining: Double? {
  608. get {
  609. return mockSensorState.cgmBatteryChargeRemaining
  610. }
  611. set {
  612. mockSensorState.cgmBatteryChargeRemaining = newValue
  613. checkAndSetBatteryBadge()
  614. }
  615. }
  616. public var isCalibrationRequested: Bool {
  617. return mockSensorState.cgmStatusBadge?.badgeType == .calibrationRequested
  618. }
  619. private func checkAndSetBatteryBadge() {
  620. // calibration badge is the highest priority
  621. guard mockSensorState.cgmStatusBadge?.badgeType != .calibrationRequested else {
  622. return
  623. }
  624. guard let cgmBatteryChargeRemaining = mockSensorState.cgmBatteryChargeRemaining,
  625. cgmBatteryChargeRemaining > 0.5 else
  626. {
  627. mockSensorState.cgmStatusBadge = MockCGMStatusBadge(badgeType: .lowBattery)
  628. return
  629. }
  630. mockSensorState.cgmStatusBadge = nil
  631. }
  632. }
  633. extension MockCGMManager {
  634. public var debugDescription: String {
  635. return """
  636. ## MockCGMManager
  637. state: \(mockSensorState)
  638. dataSource: \(dataSource)
  639. """
  640. }
  641. }
  642. extension MockCGMState: RawRepresentable {
  643. public typealias RawValue = [String: Any]
  644. public init?(rawValue: RawValue) {
  645. guard let isStateValid = rawValue["isStateValid"] as? Bool,
  646. let glucoseAlertingEnabled = rawValue["glucoseAlertingEnabled"] as? Bool,
  647. let urgentLowGlucoseThresholdValue = rawValue["urgentLowGlucoseThresholdValue"] as? Double,
  648. let lowGlucoseThresholdValue = rawValue["lowGlucoseThresholdValue"] as? Double,
  649. let highGlucoseThresholdValue = rawValue["highGlucoseThresholdValue"] as? Double,
  650. let cgmLowerLimitValue = rawValue["cgmLowerLimitValue"] as? Double,
  651. let cgmUpperLimitValue = rawValue["cgmUpperLimitValue"] as? Double else
  652. {
  653. return nil
  654. }
  655. self.isStateValid = isStateValid
  656. self.glucoseAlertingEnabled = glucoseAlertingEnabled
  657. self.samplesShouldBeUploaded = rawValue["samplesShouldBeUploaded"] as? Bool ?? false
  658. self.urgentLowGlucoseThresholdValue = urgentLowGlucoseThresholdValue
  659. self.lowGlucoseThresholdValue = lowGlucoseThresholdValue
  660. self.highGlucoseThresholdValue = highGlucoseThresholdValue
  661. self.cgmLowerLimitValue = cgmLowerLimitValue
  662. self.cgmUpperLimitValue = cgmUpperLimitValue
  663. if let glucoseRangeCategoryRawValue = rawValue["glucoseRangeCategory"] as? GlucoseRangeCategory.RawValue {
  664. self.glucoseRangeCategory = GlucoseRangeCategory(rawValue: glucoseRangeCategoryRawValue)
  665. }
  666. if let localizedMessage = rawValue["localizedMessage"] as? String,
  667. let alertIdentifier = rawValue["alertIdentifier"] as? Alert.AlertIdentifier
  668. {
  669. self.cgmStatusHighlight = MockCGMStatusHighlight(localizedMessage: localizedMessage, alertIdentifier: alertIdentifier)
  670. }
  671. if let statusBadgeTypeRawValue = rawValue["statusBadgeType"] as? MockCGMStatusBadge.MockCGMStatusBadgeType.RawValue,
  672. let statusBadgeType = MockCGMStatusBadge.MockCGMStatusBadgeType(rawValue: statusBadgeTypeRawValue)
  673. {
  674. self.cgmStatusBadge = MockCGMStatusBadge(badgeType: statusBadgeType)
  675. }
  676. if let cgmLifecycleProgressRawValue = rawValue["cgmLifecycleProgress"] as? MockCGMLifecycleProgress.RawValue {
  677. self.cgmLifecycleProgress = MockCGMLifecycleProgress(rawValue: cgmLifecycleProgressRawValue)
  678. }
  679. self.progressWarningThresholdPercentValue = rawValue["progressWarningThresholdPercentValue"] as? Double
  680. self.progressCriticalThresholdPercentValue = rawValue["progressCriticalThresholdPercentValue"] as? Double
  681. self.cgmBatteryChargeRemaining = rawValue["cgmBatteryChargeRemaining"] as? Double
  682. setProgressColor()
  683. }
  684. public var rawValue: RawValue {
  685. var rawValue: RawValue = [
  686. "isStateValid": isStateValid,
  687. "glucoseAlertingEnabled": glucoseAlertingEnabled,
  688. "samplesShouldBeUploaded": samplesShouldBeUploaded,
  689. "urgentLowGlucoseThresholdValue": urgentLowGlucoseThresholdValue,
  690. "lowGlucoseThresholdValue": lowGlucoseThresholdValue,
  691. "highGlucoseThresholdValue": highGlucoseThresholdValue,
  692. "cgmLowerLimitValue": cgmLowerLimitValue,
  693. "cgmUpperLimitValue": cgmUpperLimitValue,
  694. ]
  695. if let glucoseRangeCategory = glucoseRangeCategory {
  696. rawValue["glucoseRangeCategory"] = glucoseRangeCategory.rawValue
  697. }
  698. if let cgmStatusHighlight = cgmStatusHighlight {
  699. rawValue["localizedMessage"] = cgmStatusHighlight.localizedMessage
  700. rawValue["alertIdentifier"] = cgmStatusHighlight.alertIdentifier
  701. }
  702. if let cgmStatusBadgeType = cgmStatusBadge?.badgeType {
  703. rawValue["statusBadgeType"] = cgmStatusBadgeType.rawValue
  704. }
  705. if let cgmLifecycleProgress = cgmLifecycleProgress {
  706. rawValue["cgmLifecycleProgress"] = cgmLifecycleProgress.rawValue
  707. }
  708. if let progressWarningThresholdPercentValue = progressWarningThresholdPercentValue {
  709. rawValue["progressWarningThresholdPercentValue"] = progressWarningThresholdPercentValue
  710. }
  711. if let progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue {
  712. rawValue["progressCriticalThresholdPercentValue"] = progressCriticalThresholdPercentValue
  713. }
  714. if let cgmBatteryChargeRemaining = cgmBatteryChargeRemaining {
  715. rawValue["cgmBatteryChargeRemaining"] = cgmBatteryChargeRemaining
  716. }
  717. return rawValue
  718. }
  719. }
  720. extension MockCGMState: CustomDebugStringConvertible {
  721. public var debugDescription: String {
  722. return """
  723. ## MockCGMState
  724. * isStateValid: \(isStateValid)
  725. * glucoseAlertingEnabled: \(glucoseAlertingEnabled)
  726. * samplesShouldBeUploaded: \(samplesShouldBeUploaded)
  727. * urgentLowGlucoseThresholdValue: \(urgentLowGlucoseThresholdValue)
  728. * lowGlucoseThresholdValue: \(lowGlucoseThresholdValue)
  729. * highGlucoseThresholdValue: \(highGlucoseThresholdValue)
  730. * cgmLowerLimitValue: \(cgmLowerLimitValue)
  731. * cgmUpperLimitValue: \(cgmUpperLimitValue)
  732. * highGlucoseThresholdValue: \(highGlucoseThresholdValue)
  733. * glucoseRangeCategory: \(glucoseRangeCategory as Any)
  734. * cgmStatusHighlight: \(cgmStatusHighlight as Any)
  735. * cgmStatusBadge: \(cgmStatusBadge as Any)
  736. * cgmLifecycleProgress: \(cgmLifecycleProgress as Any)
  737. * progressWarningThresholdPercentValue: \(progressWarningThresholdPercentValue as Any)
  738. * progressCriticalThresholdPercentValue: \(progressCriticalThresholdPercentValue as Any)
  739. * cgmBatteryChargeRemaining: \(cgmBatteryChargeRemaining as Any)
  740. """
  741. }
  742. }