DeviceStatusOpenAPS.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // DeviceStatusOpenAPS.swift
  2. // LoopFollow
  3. // Created by Jonas Björkert on 2024-05-19.
  4. // Copyright © 2024 Jon Fawcett. All rights reserved.
  5. import Foundation
  6. import UIKit
  7. import HealthKit
  8. extension MainViewController {
  9. func DeviceStatusOpenAPS(formatter: ISO8601DateFormatter, lastDeviceStatus: [String: AnyObject]?, lastLoopRecord: [String: AnyObject]) {
  10. if let createdAtString = lastDeviceStatus?["created_at"] as? String,
  11. let lastLoopTime = formatter.date(from: createdAtString)?.timeIntervalSince1970 {
  12. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  13. ObservableUserDefaults.shared.device.value = lastDeviceStatus?["device"] as? String ?? ""
  14. if lastLoopRecord["failureReason"] != nil {
  15. LoopStatusLabel.text = "X"
  16. latestLoopStatusString = "X"
  17. } else {
  18. guard let enacted = lastLoopRecord["enacted"] as? [String: AnyObject] else {
  19. LoopStatusLabel.text = "↻"
  20. latestLoopStatusString = "↻"
  21. evaluateNotLooping(lastLoopTime: lastLoopTime)
  22. return
  23. }
  24. let wasEnacted = true
  25. var determinedUnit: HKUnit = .milligramsPerDeciliter
  26. // Determine the unit based on the threshold value since no unit is provided
  27. if let enactedThresholdValue = enacted["threshold"] as? Double {
  28. if enactedThresholdValue < 40 {
  29. determinedUnit = .millimolesPerLiter
  30. }
  31. }
  32. // Updated
  33. if let enactedTimestamp = enacted["timestamp"] as? String,
  34. let enactedTime = formatter.date(from: enactedTimestamp)?.timeIntervalSince1970 {
  35. let formattedTime = Localizer.formatTimestampToLocalString(enactedTime)
  36. infoManager.updateInfoData(type: .updated, value: formattedTime)
  37. }
  38. // ISF
  39. let profileISF = profileManager.currentISF()
  40. var enactedISF: HKQuantity?
  41. if let enactedISFValue = enacted["ISF"] as? Double {
  42. enactedISF = HKQuantity(unit: determinedUnit, doubleValue: enactedISFValue)
  43. }
  44. if let profileISF = profileISF, let enactedISF = enactedISF, profileISF != enactedISF {
  45. infoManager.updateInfoData(type: .isf, firstValue: profileISF, secondValue: enactedISF, separator: .arrow)
  46. } else if let profileISF = profileISF {
  47. infoManager.updateInfoData(type: .isf, value: profileISF)
  48. }
  49. // Carb Ratio (CR)
  50. let profileCR = profileManager.currentCarbRatio()
  51. var enactedCR: Double?
  52. if let reasonString = enacted["reason"] as? String {
  53. let pattern = "CR: (\\d+(?:\\.\\d+)?)"
  54. if let regex = try? NSRegularExpression(pattern: pattern) {
  55. let nsString = reasonString as NSString
  56. if let match = regex.firstMatch(in: reasonString, range: NSRange(location: 0, length: nsString.length)) {
  57. let crString = nsString.substring(with: match.range(at: 1))
  58. enactedCR = Double(crString)
  59. }
  60. }
  61. }
  62. if let profileCR = profileCR, let enactedCR = enactedCR, profileCR != enactedCR {
  63. infoManager.updateInfoData(type: .carbRatio, value: profileCR, enactedValue: enactedCR, separator: .arrow)
  64. } else if let profileCR = profileCR {
  65. infoManager.updateInfoData(type: .carbRatio, value: profileCR)
  66. }
  67. // IOB
  68. if let iobMetric = InsulinMetric(from: lastLoopRecord["iob"], key: "iob") {
  69. infoManager.updateInfoData(type: .iob, value: iobMetric)
  70. latestIOB = iobMetric
  71. }
  72. // COB
  73. if let cobMetric = CarbMetric(from: enacted, key: "COB") {
  74. infoManager.updateInfoData(type: .cob, value: cobMetric)
  75. latestCOB = cobMetric
  76. }
  77. // Insulin Required
  78. if let insulinReqMetric = InsulinMetric(from: enacted, key: "insulinReq") {
  79. infoManager.updateInfoData(type: .recBolus, value: insulinReqMetric)
  80. UserDefaultsRepository.deviceRecBolus.value = insulinReqMetric.value
  81. } else {
  82. UserDefaultsRepository.deviceRecBolus.value = 0
  83. }
  84. // Autosens
  85. if let sens = enacted["sensitivityRatio"] as? Double {
  86. let formattedSens = String(format: "%.0f", sens * 100.0) + "%"
  87. infoManager.updateInfoData(type: .autosens, value: formattedSens)
  88. }
  89. // Eventual BG
  90. if let eventualBGValue = enacted["eventualBG"] as? Double {
  91. let eventualBGQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: eventualBGValue)
  92. PredictionLabel.text = Localizer.formatQuantity(eventualBGQuantity)
  93. }
  94. // Target
  95. let profileTargetHigh = profileManager.currentTargetHigh()
  96. var enactedTarget: HKQuantity?
  97. if let enactedTargetValue = enacted["current_target"] as? Double {
  98. var targetUnit = HKUnit.milligramsPerDeciliter
  99. if enactedTargetValue < 40 {
  100. targetUnit = .millimolesPerLiter
  101. }
  102. enactedTarget = HKQuantity(unit: targetUnit, doubleValue: enactedTargetValue)
  103. }
  104. if let profileTargetHigh = profileTargetHigh, let enactedTarget = enactedTarget {
  105. let profileTargetHighFormatted = Localizer.formatQuantity(profileTargetHigh)
  106. let enactedTargetFormatted = Localizer.formatQuantity(enactedTarget)
  107. // Compare formatted values to avoid issues with minor floating-point differences
  108. // Profile target could be in another unit than enacted target
  109. if profileTargetHighFormatted != enactedTargetFormatted {
  110. infoManager.updateInfoData(type: .target, firstValue: profileTargetHigh, secondValue: enactedTarget, separator: .arrow)
  111. } else {
  112. infoManager.updateInfoData(type: .target, value: profileTargetHigh)
  113. }
  114. }
  115. // TDD
  116. if let tddMetric = InsulinMetric(from: enacted, key: "TDD") {
  117. infoManager.updateInfoData(type: .tdd, value: tddMetric)
  118. }
  119. let predictioncolor = UIColor.systemGray
  120. PredictionLabel.textColor = predictioncolor
  121. topPredictionBG = UserDefaultsRepository.minBGScale.value
  122. if let predbgdata = enacted["predBGs"] as? [String: AnyObject] {
  123. let predictionTypes: [(type: String, colorName: String, dataIndex: Int)] = [
  124. ("ZT", "ZT", 12),
  125. ("IOB", "Insulin", 13),
  126. ("COB", "LoopYellow", 14),
  127. ("UAM", "UAM", 15)
  128. ]
  129. var minPredBG = Double.infinity
  130. var maxPredBG = -Double.infinity
  131. for (type, colorName, dataIndex) in predictionTypes {
  132. var predictionData = [ShareGlucoseData]()
  133. if let graphdata = predbgdata[type] as? [Double] {
  134. var predictionTime = lastLoopTime
  135. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  136. for i in 0...toLoad {
  137. if i < graphdata.count {
  138. let predictionValue = graphdata[i]
  139. minPredBG = min(minPredBG, predictionValue)
  140. maxPredBG = max(maxPredBG, predictionValue)
  141. let prediction = ShareGlucoseData(sgv: Int(round(predictionValue)), date: predictionTime, direction: "flat")
  142. predictionData.append(prediction)
  143. predictionTime += 300
  144. }
  145. }
  146. }
  147. let color = UIColor(named: colorName) ?? UIColor.systemPurple
  148. updatePredictionGraphGeneric(
  149. dataIndex: dataIndex,
  150. predictionData: predictionData,
  151. chartLabel: type,
  152. color: color
  153. )
  154. }
  155. if minPredBG != Double.infinity && maxPredBG != -Double.infinity {
  156. let value = "\(Localizer.toDisplayUnits(String(minPredBG)))/\(Localizer.toDisplayUnits(String(maxPredBG)))"
  157. infoManager.updateInfoData(type: .minMax, value: value)
  158. } else {
  159. infoManager.updateInfoData(type: .minMax, value: "N/A")
  160. }
  161. }
  162. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String: AnyObject] {
  163. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  164. var lastBGTime = lastLoopTime
  165. if bgData.count > 0 {
  166. lastBGTime = bgData[bgData.count - 1].date
  167. }
  168. if tempBasalTime > lastBGTime && !wasEnacted {
  169. LoopStatusLabel.text = "⏀"
  170. latestLoopStatusString = "⏀"
  171. } else {
  172. LoopStatusLabel.text = "↻"
  173. latestLoopStatusString = "↻"
  174. }
  175. }
  176. } else {
  177. LoopStatusLabel.text = "↻"
  178. latestLoopStatusString = "↻"
  179. }
  180. }
  181. evaluateNotLooping(lastLoopTime: lastLoopTime)
  182. }
  183. }
  184. }