DeviceStatusOpenAPS.swift 14 KB

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