DeviceStatusOpenAPS.swift 12 KB

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