DeviceStatusOpenAPS.swift 12 KB

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