DeviceStatusOpenAPS.swift 11 KB

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