MockCGMManager.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 LoopTestingKit
  11. public struct MockCGMState: GlucoseDisplayable {
  12. public var isStateValid: Bool
  13. public var trendType: GlucoseTrend?
  14. public var isLocal: Bool {
  15. return true
  16. }
  17. public var glucoseRangeCategory: GlucoseRangeCategory?
  18. public let unit: HKUnit = .milligramsPerDeciliter
  19. public var glucoseAlertingEnabled: Bool
  20. private var cgmLowerLimitValue: Double
  21. // HKQuantity isn't codable
  22. public var cgmLowerLimit: HKQuantity {
  23. get {
  24. return HKQuantity.init(unit: unit, doubleValue: cgmLowerLimitValue)
  25. }
  26. set {
  27. var newDoubleValue = newValue.doubleValue(for: unit)
  28. if newDoubleValue >= urgentLowGlucoseThresholdValue {
  29. newDoubleValue = urgentLowGlucoseThresholdValue - 1
  30. }
  31. cgmLowerLimitValue = newDoubleValue
  32. }
  33. }
  34. private var urgentLowGlucoseThresholdValue: Double
  35. public var urgentLowGlucoseThreshold: HKQuantity {
  36. get {
  37. return HKQuantity.init(unit: unit, doubleValue: urgentLowGlucoseThresholdValue)
  38. }
  39. set {
  40. var newDoubleValue = newValue.doubleValue(for: unit)
  41. if newDoubleValue <= cgmLowerLimitValue {
  42. newDoubleValue = cgmLowerLimitValue + 1
  43. }
  44. if newDoubleValue >= lowGlucoseThresholdValue {
  45. newDoubleValue = lowGlucoseThresholdValue - 1
  46. }
  47. urgentLowGlucoseThresholdValue = newDoubleValue
  48. }
  49. }
  50. private var lowGlucoseThresholdValue: Double
  51. public var lowGlucoseThreshold: HKQuantity {
  52. get {
  53. return HKQuantity.init(unit: unit, doubleValue: lowGlucoseThresholdValue)
  54. }
  55. set {
  56. var newDoubleValue = newValue.doubleValue(for: unit)
  57. if newDoubleValue <= urgentLowGlucoseThresholdValue {
  58. newDoubleValue = urgentLowGlucoseThresholdValue + 1
  59. }
  60. if newDoubleValue >= highGlucoseThresholdValue {
  61. newDoubleValue = highGlucoseThresholdValue - 1
  62. }
  63. lowGlucoseThresholdValue = newDoubleValue
  64. }
  65. }
  66. private var highGlucoseThresholdValue: Double
  67. public var highGlucoseThreshold: HKQuantity {
  68. get {
  69. return HKQuantity.init(unit: unit, doubleValue: highGlucoseThresholdValue)
  70. }
  71. set {
  72. var newDoubleValue = newValue.doubleValue(for: unit)
  73. if newDoubleValue <= lowGlucoseThresholdValue {
  74. newDoubleValue = lowGlucoseThresholdValue + 1
  75. }
  76. if newDoubleValue >= cgmUpperLimitValue {
  77. newDoubleValue = cgmUpperLimitValue - 1
  78. }
  79. highGlucoseThresholdValue = newDoubleValue
  80. }
  81. }
  82. private var cgmUpperLimitValue: Double
  83. public var cgmUpperLimit: HKQuantity {
  84. get {
  85. return HKQuantity.init(unit: unit, doubleValue: cgmUpperLimitValue)
  86. }
  87. set {
  88. var newDoubleValue = newValue.doubleValue(for: unit)
  89. if newDoubleValue <= highGlucoseThresholdValue {
  90. newDoubleValue = highGlucoseThresholdValue + 1
  91. }
  92. cgmUpperLimitValue = newDoubleValue
  93. }
  94. }
  95. public var cgmStatusHighlight: MockCGMStatusHighlight?
  96. public var cgmLifecycleProgress: MockCGMLifecycleProgress? {
  97. didSet {
  98. if cgmLifecycleProgress != oldValue {
  99. setProgressColor()
  100. }
  101. }
  102. }
  103. public var progressWarningThresholdPercentValue: Double? {
  104. didSet {
  105. if progressWarningThresholdPercentValue != oldValue {
  106. setProgressColor()
  107. }
  108. }
  109. }
  110. public var progressCriticalThresholdPercentValue: Double? {
  111. didSet {
  112. if progressCriticalThresholdPercentValue != oldValue {
  113. setProgressColor()
  114. }
  115. }
  116. }
  117. private mutating func setProgressColor() {
  118. guard var cgmLifecycleProgress = cgmLifecycleProgress else {
  119. return
  120. }
  121. if let progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue,
  122. cgmLifecycleProgress.percentComplete >= progressCriticalThresholdPercentValue
  123. {
  124. cgmLifecycleProgress.progressState = .critical
  125. } else if let progressWarningThresholdPercentValue = progressWarningThresholdPercentValue,
  126. cgmLifecycleProgress.percentComplete >= progressWarningThresholdPercentValue
  127. {
  128. cgmLifecycleProgress.progressState = .warning
  129. } else {
  130. cgmLifecycleProgress.progressState = .normalCGM
  131. }
  132. self.cgmLifecycleProgress = cgmLifecycleProgress
  133. }
  134. public init(isStateValid: Bool = true,
  135. trendType: GlucoseTrend? = nil,
  136. glucoseRangeCategory: GlucoseRangeCategory? = nil,
  137. glucoseAlertingEnabled: Bool = false,
  138. urgentLowGlucoseThresholdValue: Double = 55,
  139. lowGlucoseThresholdValue: Double = 80,
  140. highGlucoseThresholdValue: Double = 200,
  141. cgmLowerLimitValue: Double = 40,
  142. cgmUpperLimitValue: Double = 400,
  143. cgmStatusHighlight: MockCGMStatusHighlight? = nil,
  144. cgmLifecycleProgress: MockCGMLifecycleProgress? = nil,
  145. progressWarningThresholdPercentValue: Double? = nil,
  146. progressCriticalThresholdPercentValue: Double? = nil)
  147. {
  148. self.isStateValid = isStateValid
  149. self.trendType = trendType
  150. self.glucoseRangeCategory = glucoseRangeCategory
  151. self.glucoseAlertingEnabled = glucoseAlertingEnabled
  152. self.urgentLowGlucoseThresholdValue = urgentLowGlucoseThresholdValue
  153. self.lowGlucoseThresholdValue = lowGlucoseThresholdValue
  154. self.highGlucoseThresholdValue = highGlucoseThresholdValue
  155. self.cgmLowerLimitValue = cgmLowerLimitValue
  156. self.cgmUpperLimitValue = cgmUpperLimitValue
  157. self.cgmStatusHighlight = cgmStatusHighlight
  158. self.cgmLifecycleProgress = cgmLifecycleProgress
  159. self.progressWarningThresholdPercentValue = progressWarningThresholdPercentValue
  160. self.progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue
  161. setProgressColor()
  162. }
  163. }
  164. public struct MockCGMStatusHighlight: DeviceStatusHighlight {
  165. public var localizedMessage: String
  166. public var imageName: String {
  167. switch alertIdentifier {
  168. case MockCGMManager.submarine.identifier:
  169. return "dot.radiowaves.left.and.right"
  170. case MockCGMManager.buzz.identifier:
  171. return "clock"
  172. default:
  173. return "exclamationmark.circle.fill"
  174. }
  175. }
  176. public var state: DeviceStatusHighlightState{
  177. switch alertIdentifier {
  178. case MockCGMManager.submarine.identifier:
  179. return .normalCGM
  180. case MockCGMManager.buzz.identifier:
  181. return .warning
  182. default:
  183. return .critical
  184. }
  185. }
  186. public var alertIdentifier: Alert.AlertIdentifier
  187. }
  188. public struct MockCGMLifecycleProgress: DeviceLifecycleProgress, Equatable {
  189. public var percentComplete: Double
  190. public var progressState: DeviceLifecycleProgressState
  191. public init(percentComplete: Double, progressState: DeviceLifecycleProgressState = .normalCGM) {
  192. self.percentComplete = percentComplete
  193. self.progressState = progressState
  194. }
  195. }
  196. extension MockCGMLifecycleProgress: RawRepresentable {
  197. public typealias RawValue = [String: Any]
  198. public init?(rawValue: RawValue) {
  199. guard let percentComplete = rawValue["percentComplete"] as? Double,
  200. let progressStateRawValue = rawValue["progressState"] as? DeviceLifecycleProgressState.RawValue,
  201. let progressState = DeviceLifecycleProgressState(rawValue: progressStateRawValue) else
  202. {
  203. return nil
  204. }
  205. self.percentComplete = percentComplete
  206. self.progressState = progressState
  207. }
  208. public var rawValue: RawValue {
  209. let rawValue: RawValue = [
  210. "percentComplete": percentComplete,
  211. "progressState": progressState.rawValue,
  212. ]
  213. return rawValue
  214. }
  215. }
  216. public final class MockCGMManager: TestingCGMManager {
  217. public static let managerIdentifier = "MockCGMManager"
  218. public static let localizedTitle = "CGM Simulator"
  219. public struct MockAlert {
  220. public let sound: Alert.Sound
  221. public let identifier: Alert.AlertIdentifier
  222. public let foregroundContent: Alert.Content
  223. public let backgroundContent: Alert.Content
  224. }
  225. let alerts: [Alert.AlertIdentifier: MockAlert] = [
  226. submarine.identifier: submarine, buzz.identifier: buzz, critical.identifier: critical, signalLoss.identifier: signalLoss
  227. ]
  228. public static let submarine = MockAlert(sound: .sound(name: "sub.caf"), identifier: "submarine",
  229. foregroundContent: Alert.Content(title: "Alert: FG Title", body: "Alert: Foreground Body", acknowledgeActionButtonLabel: "FG OK"),
  230. backgroundContent: Alert.Content(title: "Alert: BG Title", body: "Alert: Background Body", acknowledgeActionButtonLabel: "BG OK"))
  231. public static let critical = MockAlert(sound: .sound(name: "critical.caf"), identifier: "critical",
  232. foregroundContent: Alert.Content(title: "Critical Alert: FG Title", body: "Critical Alert: Foreground Body", acknowledgeActionButtonLabel: "Critical FG OK", isCritical: true),
  233. backgroundContent: Alert.Content(title: "Critical Alert: BG Title", body: "Critical Alert: Background Body", acknowledgeActionButtonLabel: "Critical BG OK", isCritical: true))
  234. public static let buzz = MockAlert(sound: .vibrate, identifier: "buzz",
  235. foregroundContent: Alert.Content(title: "Alert: FG Title", body: "FG bzzzt", acknowledgeActionButtonLabel: "Buzz"),
  236. backgroundContent: Alert.Content(title: "Alert: BG Title", body: "BG bzzzt", acknowledgeActionButtonLabel: "Buzz"))
  237. public static let signalLoss = MockAlert(sound: .sound(name: "critical.caf"),
  238. identifier: "signalLoss",
  239. foregroundContent: Alert.Content(title: "Signal Loss", body: "CGM simulator signal loss", acknowledgeActionButtonLabel: "Dismiss"),
  240. backgroundContent: Alert.Content(title: "Signal Loss", body: "CGM simulator signal loss", acknowledgeActionButtonLabel: "Dismiss"))
  241. public var mockSensorState: MockCGMState {
  242. didSet {
  243. delegate.notify { (delegate) in
  244. delegate?.cgmManagerDidUpdateState(self)
  245. }
  246. }
  247. }
  248. public var glucoseDisplay: GlucoseDisplayable? {
  249. return mockSensorState
  250. }
  251. public var cgmStatus: CGMManagerStatus {
  252. return CGMManagerStatus(hasValidSensorSession: dataSource.isValidSession)
  253. }
  254. public var testingDevice: HKDevice {
  255. return MockCGMDataSource.device
  256. }
  257. public var device: HKDevice? {
  258. return testingDevice
  259. }
  260. public weak var cgmManagerDelegate: CGMManagerDelegate? {
  261. get {
  262. return delegate.delegate
  263. }
  264. set {
  265. delegate.delegate = newValue
  266. }
  267. }
  268. public var delegateQueue: DispatchQueue! {
  269. get {
  270. return delegate.queue
  271. }
  272. set {
  273. delegate.queue = newValue
  274. }
  275. }
  276. private let delegate = WeakSynchronizedDelegate<CGMManagerDelegate>()
  277. public var dataSource: MockCGMDataSource {
  278. didSet {
  279. delegate.notify { (delegate) in
  280. delegate?.cgmManagerDidUpdateState(self)
  281. delegate?.cgmManager(self, didUpdate: self.cgmStatus)
  282. }
  283. }
  284. }
  285. private var glucoseUpdateTimer: Timer?
  286. private var backgroundTask: UIBackgroundTaskIdentifier = .invalid
  287. public init?(rawState: RawStateValue) {
  288. if let mockSensorStateRawValue = rawState["mockSensorState"] as? MockCGMState.RawValue,
  289. let mockSensorState = MockCGMState(rawValue: mockSensorStateRawValue) {
  290. self.mockSensorState = mockSensorState
  291. } else {
  292. self.mockSensorState = MockCGMState(isStateValid: true, trendType: nil)
  293. }
  294. if let dataSourceRawValue = rawState["dataSource"] as? MockCGMDataSource.RawValue,
  295. let dataSource = MockCGMDataSource(rawValue: dataSourceRawValue) {
  296. self.dataSource = dataSource
  297. } else {
  298. self.dataSource = MockCGMDataSource(model: .noData)
  299. }
  300. setupGlucoseUpdateTimer()
  301. }
  302. deinit {
  303. glucoseUpdateTimer?.invalidate()
  304. }
  305. public var rawState: RawStateValue {
  306. return [
  307. "mockSensorState": mockSensorState.rawValue,
  308. "dataSource": dataSource.rawValue
  309. ]
  310. }
  311. public let appURL: URL? = nil
  312. public let providesBLEHeartbeat = false
  313. public let managedDataInterval: TimeInterval? = nil
  314. public let shouldSyncToRemoteService = false
  315. private func logDeviceCommunication(_ message: String, type: DeviceLogEntryType = .send) {
  316. self.delegate.notify { (delegate) in
  317. delegate?.deviceManager(self, logEventForDeviceIdentifier: "MockId", type: type, message: message, completion: nil)
  318. }
  319. }
  320. private func logDeviceComms(_ type: DeviceLogEntryType, message: String) {
  321. delegate.notify { (delegate) in
  322. delegate?.deviceManager(self, logEventForDeviceIdentifier: "mockcgm", type: type, message: message, completion: nil)
  323. }
  324. }
  325. private func sendCGMReadingResult(_ result: CGMReadingResult) {
  326. if case .newData(let samples) = result,
  327. let currentValue = samples.first
  328. {
  329. mockSensorState.glucoseRangeCategory = glucoseRangeCategory(for: currentValue.quantitySample)
  330. issueAlert(for: currentValue)
  331. }
  332. self.delegate.notify { delegate in
  333. delegate?.cgmManager(self, hasNew: result)
  334. }
  335. }
  336. public func glucoseRangeCategory(for glucose: GlucoseSampleValue) -> GlucoseRangeCategory? {
  337. switch glucose.quantity {
  338. case ...mockSensorState.cgmLowerLimit:
  339. return glucose.wasUserEntered ? .urgentLow : .belowRange
  340. case mockSensorState.cgmLowerLimit..<mockSensorState.urgentLowGlucoseThreshold:
  341. return .urgentLow
  342. case mockSensorState.urgentLowGlucoseThreshold..<mockSensorState.lowGlucoseThreshold:
  343. return .low
  344. case mockSensorState.lowGlucoseThreshold..<mockSensorState.highGlucoseThreshold:
  345. return .normal
  346. case mockSensorState.highGlucoseThreshold..<mockSensorState.cgmUpperLimit:
  347. return .high
  348. default:
  349. return glucose.wasUserEntered ? .high : .aboveRange
  350. }
  351. }
  352. public func fetchNewDataIfNeeded(_ completion: @escaping (CGMReadingResult) -> Void) {
  353. logDeviceComms(.send, message: "Fetch new data")
  354. dataSource.fetchNewData { (result) in
  355. switch result {
  356. case .error(let error):
  357. self.logDeviceComms(.error, message: "Error fetching new data: \(error)")
  358. case .newData(let samples):
  359. self.logDeviceComms(.receive, message: "New data received: \(samples)")
  360. case .noData:
  361. self.logDeviceComms(.receive, message: "No new data")
  362. }
  363. completion(result)
  364. }
  365. }
  366. public func backfillData(datingBack duration: TimeInterval) {
  367. let now = Date()
  368. self.logDeviceCommunication("backfillData(\(duration))")
  369. dataSource.backfillData(from: DateInterval(start: now.addingTimeInterval(-duration), end: now)) { result in
  370. switch result {
  371. case .error(let error):
  372. self.logDeviceComms(.error, message: "Backfill error: \(error)")
  373. case .newData(let samples):
  374. self.logDeviceComms(.receive, message: "Backfill data: \(samples)")
  375. case .noData:
  376. self.logDeviceComms(.receive, message: "Backfill empty")
  377. }
  378. self.sendCGMReadingResult(result)
  379. }
  380. }
  381. public func updateGlucoseUpdateTimer() {
  382. glucoseUpdateTimer?.invalidate()
  383. setupGlucoseUpdateTimer()
  384. }
  385. private func setupGlucoseUpdateTimer() {
  386. glucoseUpdateTimer = Timer.scheduledTimer(withTimeInterval: dataSource.dataPointFrequency.frequency, repeats: true) { [weak self] _ in
  387. guard let self = self else { return }
  388. self.fetchNewDataIfNeeded() { result in
  389. self.sendCGMReadingResult(result)
  390. }
  391. }
  392. }
  393. public func injectGlucoseSamples(_ samples: [NewGlucoseSample]) {
  394. guard !samples.isEmpty else { return }
  395. var samples = samples
  396. samples.mutateEach { $0.device = device }
  397. sendCGMReadingResult(CGMReadingResult.newData(samples))
  398. }
  399. }
  400. // MARK: Alert Stuff
  401. extension MockCGMManager {
  402. public func getSoundBaseURL() -> URL? {
  403. return Bundle(for: type(of: self)).bundleURL
  404. }
  405. public func getSounds() -> [Alert.Sound] {
  406. return alerts.map { $1.sound }
  407. }
  408. public var hasRetractableAlert: Bool {
  409. // signal loss alerts can only be removed by switching the CGM data source
  410. return currentAlertIdentifier != nil && currentAlertIdentifier != MockCGMManager.signalLoss.identifier
  411. }
  412. public var currentAlertIdentifier: Alert.AlertIdentifier? {
  413. return mockSensorState.cgmStatusHighlight?.alertIdentifier
  414. }
  415. public func issueAlert(identifier: Alert.AlertIdentifier, trigger: Alert.Trigger, delay: TimeInterval?) {
  416. guard let alert = alerts[identifier] else {
  417. return
  418. }
  419. registerBackgroundTask()
  420. delegate.notifyDelayed(by: delay ?? 0) { delegate in
  421. self.logDeviceComms(.delegate, message: "\(#function): \(identifier) \(trigger)")
  422. delegate?.issueAlert(Alert(identifier: Alert.Identifier(managerIdentifier: self.managerIdentifier, alertIdentifier: identifier),
  423. foregroundContent: alert.foregroundContent,
  424. backgroundContent: alert.backgroundContent,
  425. trigger: trigger,
  426. sound: alert.sound))
  427. }
  428. // updating the status highlight
  429. setStatusHighlight(MockCGMStatusHighlight(localizedMessage: alert.foregroundContent.title, alertIdentifier: alert.identifier))
  430. }
  431. public func issueSignalLossAlert() {
  432. issueAlert(identifier: MockCGMManager.signalLoss.identifier, trigger: .immediate, delay: nil)
  433. }
  434. public func retractSignalLossAlert() {
  435. retractAlert(identifier: MockCGMManager.signalLoss.identifier)
  436. }
  437. public func acknowledgeAlert(alertIdentifier: Alert.AlertIdentifier) {
  438. endBackgroundTask()
  439. self.logDeviceComms(.delegateResponse, message: "\(#function): Alert \(alertIdentifier) acknowledged.")
  440. }
  441. public func retractCurrentAlert() {
  442. guard hasRetractableAlert, let identifier = currentAlertIdentifier else { return }
  443. retractAlert(identifier: identifier)
  444. }
  445. public func retractAlert(identifier: Alert.AlertIdentifier) {
  446. delegate.notify { $0?.retractAlert(identifier: Alert.Identifier(managerIdentifier: self.managerIdentifier, alertIdentifier: identifier)) }
  447. // updating the status highlight
  448. if mockSensorState.cgmStatusHighlight?.alertIdentifier == identifier {
  449. setStatusHighlight(nil)
  450. }
  451. }
  452. public func setStatusHighlight(_ statusHighlight: MockCGMStatusHighlight?) {
  453. mockSensorState.cgmStatusHighlight = statusHighlight
  454. if statusHighlight == nil,
  455. case .signalLoss = dataSource.model
  456. {
  457. // restore signal loss status highlight
  458. issueSignalLossAlert()
  459. }
  460. // trigger display of the status highlight
  461. sendCGMReadingResult(.noData)
  462. }
  463. private func registerBackgroundTask() {
  464. backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
  465. self?.endBackgroundTask()
  466. }
  467. assert(backgroundTask != .invalid)
  468. }
  469. private func endBackgroundTask() {
  470. UIApplication.shared.endBackgroundTask(backgroundTask)
  471. backgroundTask = .invalid
  472. }
  473. private func issueAlert(for glucose: NewGlucoseSample) {
  474. guard mockSensorState.glucoseAlertingEnabled else {
  475. return
  476. }
  477. let alertTitle: String
  478. let glucoseAlertIdentifier: String
  479. switch glucose.quantity {
  480. case ...mockSensorState.urgentLowGlucoseThreshold:
  481. alertTitle = "Urgent Low Glucose Alert"
  482. glucoseAlertIdentifier = "glucose.value.low.urgent"
  483. case mockSensorState.urgentLowGlucoseThreshold..<mockSensorState.lowGlucoseThreshold:
  484. alertTitle = "Low Glucose Alert"
  485. glucoseAlertIdentifier = "glucose.value.low"
  486. case mockSensorState.highGlucoseThreshold...:
  487. alertTitle = "High Glucose Alert"
  488. glucoseAlertIdentifier = "glucose.value.high"
  489. default:
  490. return
  491. }
  492. let alertIdentifier = Alert.Identifier(managerIdentifier: self.managerIdentifier,
  493. alertIdentifier: glucoseAlertIdentifier)
  494. let alertContent = Alert.Content(title: alertTitle,
  495. body: "The glucose measurement received triggered this alert",
  496. acknowledgeActionButtonLabel: "Dismiss")
  497. let alert = Alert(identifier: alertIdentifier,
  498. foregroundContent: alertContent,
  499. backgroundContent: alertContent,
  500. trigger: .immediate)
  501. delegate.notify { delegate in
  502. delegate?.issueAlert(alert)
  503. }
  504. }
  505. }
  506. extension MockCGMManager {
  507. public var debugDescription: String {
  508. return """
  509. ## MockCGMManager
  510. state: \(mockSensorState)
  511. dataSource: \(dataSource)
  512. """
  513. }
  514. }
  515. extension MockCGMState: RawRepresentable {
  516. public typealias RawValue = [String: Any]
  517. public init?(rawValue: RawValue) {
  518. guard let isStateValid = rawValue["isStateValid"] as? Bool,
  519. let glucoseAlertingEnabled = rawValue["glucoseAlertingEnabled"] as? Bool,
  520. let urgentLowGlucoseThresholdValue = rawValue["urgentLowGlucoseThresholdValue"] as? Double,
  521. let lowGlucoseThresholdValue = rawValue["lowGlucoseThresholdValue"] as? Double,
  522. let highGlucoseThresholdValue = rawValue["highGlucoseThresholdValue"] as? Double,
  523. let cgmLowerLimitValue = rawValue["cgmLowerLimitValue"] as? Double,
  524. let cgmUpperLimitValue = rawValue["cgmUpperLimitValue"] as? Double else
  525. {
  526. return nil
  527. }
  528. self.isStateValid = isStateValid
  529. self.glucoseAlertingEnabled = glucoseAlertingEnabled
  530. self.urgentLowGlucoseThresholdValue = urgentLowGlucoseThresholdValue
  531. self.lowGlucoseThresholdValue = lowGlucoseThresholdValue
  532. self.highGlucoseThresholdValue = highGlucoseThresholdValue
  533. self.cgmLowerLimitValue = cgmLowerLimitValue
  534. self.cgmUpperLimitValue = cgmUpperLimitValue
  535. if let trendTypeRawValue = rawValue["trendType"] as? GlucoseTrend.RawValue {
  536. self.trendType = GlucoseTrend(rawValue: trendTypeRawValue)
  537. }
  538. if let glucoseRangeCategoryRawValue = rawValue["glucoseRangeCategory"] as? GlucoseRangeCategory.RawValue {
  539. self.glucoseRangeCategory = GlucoseRangeCategory(rawValue: glucoseRangeCategoryRawValue)
  540. }
  541. if let localizedMessage = rawValue["localizedMessage"] as? String,
  542. let alertIdentifier = rawValue["alertIdentifier"] as? Alert.AlertIdentifier
  543. {
  544. self.cgmStatusHighlight = MockCGMStatusHighlight(localizedMessage: localizedMessage, alertIdentifier: alertIdentifier)
  545. }
  546. if let cgmLifecycleProgressRawValue = rawValue["cgmLifecycleProgress"] as? MockCGMLifecycleProgress.RawValue {
  547. self.cgmLifecycleProgress = MockCGMLifecycleProgress(rawValue: cgmLifecycleProgressRawValue)
  548. }
  549. self.progressWarningThresholdPercentValue = rawValue["progressWarningThresholdPercentValue"] as? Double
  550. self.progressCriticalThresholdPercentValue = rawValue["progressCriticalThresholdPercentValue"] as? Double
  551. setProgressColor()
  552. }
  553. public var rawValue: RawValue {
  554. var rawValue: RawValue = [
  555. "isStateValid": isStateValid,
  556. "glucoseAlertingEnabled": glucoseAlertingEnabled,
  557. "urgentLowGlucoseThresholdValue": urgentLowGlucoseThresholdValue,
  558. "lowGlucoseThresholdValue": lowGlucoseThresholdValue,
  559. "highGlucoseThresholdValue": highGlucoseThresholdValue,
  560. "cgmLowerLimitValue": cgmLowerLimitValue,
  561. "cgmUpperLimitValue": cgmUpperLimitValue,
  562. ]
  563. if let trendType = trendType {
  564. rawValue["trendType"] = trendType.rawValue
  565. }
  566. if let glucoseRangeCategory = glucoseRangeCategory {
  567. rawValue["glucoseRangeCategory"] = glucoseRangeCategory.rawValue
  568. }
  569. if let cgmStatusHighlight = cgmStatusHighlight {
  570. rawValue["localizedMessage"] = cgmStatusHighlight.localizedMessage
  571. rawValue["alertIdentifier"] = cgmStatusHighlight.alertIdentifier
  572. }
  573. if let cgmLifecycleProgress = cgmLifecycleProgress {
  574. rawValue["cgmLifecycleProgress"] = cgmLifecycleProgress.rawValue
  575. }
  576. if let progressWarningThresholdPercentValue = progressWarningThresholdPercentValue {
  577. rawValue["progressWarningThresholdPercentValue"] = progressWarningThresholdPercentValue
  578. }
  579. if let progressCriticalThresholdPercentValue = progressCriticalThresholdPercentValue {
  580. rawValue["progressCriticalThresholdPercentValue"] = progressCriticalThresholdPercentValue
  581. }
  582. return rawValue
  583. }
  584. }
  585. extension MockCGMState: CustomDebugStringConvertible {
  586. public var debugDescription: String {
  587. return """
  588. ## MockCGMState
  589. * isStateValid: \(isStateValid)
  590. * trendType: \(trendType as Any)
  591. * glucoseAlertingEnabled: \(glucoseAlertingEnabled)
  592. * urgentLowGlucoseThresholdValue: \(urgentLowGlucoseThresholdValue)
  593. * lowGlucoseThresholdValue: \(lowGlucoseThresholdValue)
  594. * highGlucoseThresholdValue: \(highGlucoseThresholdValue)
  595. * cgmLowerLimitValue: \(cgmLowerLimitValue)
  596. * cgmUpperLimitValue: \(cgmUpperLimitValue)
  597. * highGlucoseThresholdValue: \(highGlucoseThresholdValue)
  598. * glucoseRangeCategory: \(glucoseRangeCategory as Any)
  599. * cgmStatusHighlight: \(cgmStatusHighlight as Any)
  600. * cgmLifecycleProgress: \(cgmLifecycleProgress as Any)
  601. * progressWarningThresholdPercentValue: \(progressWarningThresholdPercentValue as Any)
  602. * progressCriticalThresholdPercentValue: \(progressCriticalThresholdPercentValue as Any)
  603. """
  604. }
  605. }