DeviceStatusOpenAPS.swift 12 KB

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