BGData.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. //
  2. // BGData.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2023-10-05.
  6. // Copyright © 2023 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension MainViewController {
  11. // Dex Share Web Call
  12. func webLoadDexShare() {
  13. // Dexcom Share only returns 24 hrs of data as of now
  14. // Requesting more just for consistency with NS
  15. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  16. let count = graphHours * 12
  17. dexShare?.fetchData(count) { (err, result) -> () in
  18. if let error = err {
  19. print("Error fetching Dexcom data: \(error.localizedDescription)")
  20. // If we get an error, immediately try to pull NS BG Data
  21. if IsNightscoutEnabled() {
  22. self.webLoadNSBGData()
  23. }
  24. return
  25. }
  26. guard let data = result else {
  27. print("Received nil data from Dexcom")
  28. return
  29. }
  30. // If Dex data is old, load from NS instead
  31. let latestDate = data[0].date
  32. let now = dateTimeUtils.getNowTimeIntervalUTC()
  33. if (latestDate + 330) < now && IsNightscoutEnabled() {
  34. self.webLoadNSBGData()
  35. print("Dex data is old, loading from NS instead")
  36. return
  37. }
  38. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  39. if graphHours > 24 && IsNightscoutEnabled() {
  40. self.webLoadNSBGData(dexData: data)
  41. } else {
  42. self.ProcessDexBGData(data: data, sourceName: "Dexcom")
  43. }
  44. }
  45. }
  46. // NS BG Data Web call
  47. func webLoadNSBGData(dexData: [ShareGlucoseData] = []) {
  48. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  49. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  50. if !IsNightscoutEnabled() {
  51. self.startBGTimer(time: 10)
  52. return
  53. }
  54. var parameters: [String: String] = [:]
  55. let utcISODateFormatter = ISO8601DateFormatter()
  56. let date = Calendar.current.date(byAdding: .day, value: -1 * UserDefaultsRepository.downloadDays.value, to: Date())!
  57. parameters["count"] = "\(UserDefaultsRepository.downloadDays.value * 2 * 24 * 60 / 5)"
  58. parameters["find[dateString][$gte]"] = utcISODateFormatter.string(from: date)
  59. // Exclude 'cal' entries
  60. parameters["find[type][$ne]"] = "cal"
  61. NightscoutUtils.executeRequest(eventType: .sgv, parameters: parameters) { (result: Result<[ShareGlucoseData], Error>) in
  62. switch result {
  63. case .success(let entriesResponse):
  64. var nsData = entriesResponse
  65. DispatchQueue.main.async {
  66. // transform NS data to look like Dex data
  67. for i in 0..<nsData.count {
  68. // convert the NS timestamp to seconds instead of milliseconds
  69. nsData[i].date /= 1000
  70. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  71. }
  72. print(nsData.count)
  73. //Avoid duplicate entries messing up the graph, only use one reading per 5 minutes.
  74. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  75. let points = graphHours * 12 + 1
  76. var nsData2 = [ShareGlucoseData]()
  77. let timestamp = Date().timeIntervalSince1970
  78. for i in 0..<points {
  79. //Starting with "now" and then step 5 minutes back in time
  80. let target = timestamp - Double(i) * 60 * 5
  81. //Find the reading closest to the target, but not too far away
  82. let closest = nsData.filter{ abs($0.date - target) < 3 * 60 }.min { abs($0.date - target) < abs($1.date - target) }
  83. //If a reading is found, add it to the new array
  84. if let item = closest {
  85. nsData2.append(item)
  86. }
  87. }
  88. print(nsData2.count)
  89. // merge NS and Dex data if needed; use recent Dex data and older NS data
  90. var sourceName = "Nightscout"
  91. if !dexData.isEmpty {
  92. let oldestDexDate = dexData[dexData.count - 1].date
  93. var itemsToRemove = 0
  94. while itemsToRemove < nsData2.count && nsData2[itemsToRemove].date >= oldestDexDate {
  95. itemsToRemove += 1
  96. }
  97. nsData2.removeFirst(itemsToRemove)
  98. nsData2 = dexData + nsData2
  99. sourceName = "Dexcom"
  100. }
  101. // trigger the processor for the data after downloading.
  102. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  103. }
  104. case .failure(let error):
  105. print("Failed to fetch data: \(error)")
  106. DispatchQueue.main.async {
  107. if self.bgTimer.isValid {
  108. self.bgTimer.invalidate()
  109. }
  110. self.startBGTimer(time: 10)
  111. }
  112. // if we have Dex data, use it
  113. if !dexData.isEmpty {
  114. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  115. }
  116. return
  117. }
  118. }
  119. }
  120. // Dexcom BG Data Response processor
  121. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String){
  122. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  123. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  124. if data.count == 0 {
  125. return
  126. }
  127. let pullDate = data[data.count - 1].date
  128. let latestDate = data[0].date
  129. let now = dateTimeUtils.getNowTimeIntervalUTC()
  130. // Start the BG timer based on the reading
  131. let secondsAgo = now - latestDate
  132. DispatchQueue.main.async {
  133. // if reading is overdue over: 20:00, re-attempt every 5 minutes
  134. if secondsAgo >= (20 * 60) {
  135. self.startBGTimer(time: (5 * 60))
  136. print("##### started 5 minute bg timer")
  137. // if the reading is overdue: 10:00-19:59, re-attempt every minute
  138. } else if secondsAgo >= (10 * 60) {
  139. self.startBGTimer(time: 60)
  140. print("##### started 1 minute bg timer")
  141. // if the reading is overdue: 7:00-9:59, re-attempt every 30 seconds
  142. } else if secondsAgo >= (7 * 60) {
  143. self.startBGTimer(time: 30)
  144. print("##### started 30 second bg timer")
  145. // if the reading is overdue: 5:00-6:59 re-attempt every 10 seconds
  146. } else if secondsAgo >= (5 * 60) {
  147. self.startBGTimer(time: 10)
  148. print("##### started 10 second bg timer")
  149. // We have a current reading. Set timer to 5:10 from last reading
  150. } else {
  151. self.startBGTimer(time: 300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value))
  152. let timerVal = 310 - secondsAgo
  153. print("##### started 5:10 bg timer: \(timerVal)")
  154. if data.count > 1 {
  155. self.evaluateSpeakConditions(currentValue: data[0].sgv, previousValue: data[1].sgv)
  156. }
  157. }
  158. }
  159. bgData.removeAll()
  160. // loop through the data so we can reverse the order to oldest first for the graph
  161. for i in 0..<data.count {
  162. let dateString = data[data.count - 1 - i].date
  163. if dateString >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  164. let sgvValue = data[data.count - 1 - i].sgv
  165. // Skip the current iteration if the sgv value is over 600
  166. // First time a user starts a G7, they get a value of 4000
  167. if sgvValue > 600 {
  168. continue
  169. }
  170. let reading = ShareGlucoseData(sgv: sgvValue, date: dateString, direction: data[data.count - 1 - i].direction)
  171. bgData.append(reading)
  172. }
  173. }
  174. viewUpdateNSBG(sourceName: sourceName)
  175. }
  176. func updateServerText(with serverText: String? = nil) {
  177. if UserDefaultsRepository.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  178. self.serverText.text = displayName
  179. } else if let serverText = serverText {
  180. self.serverText.text = serverText
  181. }
  182. }
  183. // NS BG Data Front end updater
  184. func viewUpdateNSBG(sourceName: String) {
  185. DispatchQueue.main.async {
  186. if UserDefaultsRepository.debugLog.value {
  187. self.writeDebugLog(value: "Display: BG")
  188. self.writeDebugLog(value: "Num BG: " + self.bgData.count.description)
  189. }
  190. let entries = self.bgData
  191. if entries.count < 2 { return } // Protect index out of bounds
  192. self.updateBGGraph()
  193. self.updateStats()
  194. let latestEntryIndex = entries.count - 1
  195. let latestBG = entries[latestEntryIndex].sgv
  196. let priorBG = entries[latestEntryIndex - 1].sgv
  197. let deltaBG = latestBG - priorBG
  198. let lastBGTime = entries[latestEntryIndex].date
  199. let deltaTime = (TimeInterval(Date().timeIntervalSince1970) - lastBGTime) / 60
  200. var userUnit = " mg/dL"
  201. if self.mmol {
  202. userUnit = " mmol/L"
  203. }
  204. self.updateServerText(with: sourceName)
  205. var snoozerBG = ""
  206. var snoozerDirection = ""
  207. var snoozerDelta = ""
  208. // Set BGText with the latest BG value
  209. self.BGText.text = Localizer.toDisplayUnits(String(latestBG))
  210. snoozerBG = Localizer.toDisplayUnits(String(latestBG))
  211. self.setBGTextColor()
  212. // Direction handling
  213. if let directionBG = entries[latestEntryIndex].direction {
  214. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  215. snoozerDirection = self.bgDirectionGraphic(directionBG)
  216. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  217. } else {
  218. self.DirectionText.text = ""
  219. snoozerDirection = ""
  220. self.latestDirectionString = ""
  221. }
  222. // Delta handling
  223. if deltaBG < 0 {
  224. self.DeltaText.text = Localizer.toDisplayUnits(String(deltaBG))
  225. snoozerDelta = Localizer.toDisplayUnits(String(deltaBG))
  226. self.latestDeltaString = String(deltaBG)
  227. } else {
  228. self.DeltaText.text = "+" + Localizer.toDisplayUnits(String(deltaBG))
  229. snoozerDelta = "+" + Localizer.toDisplayUnits(String(deltaBG))
  230. self.latestDeltaString = "+" + String(deltaBG)
  231. }
  232. // Apply strikethrough to BGText based on the staleness of the data
  233. let bgTextStr = self.BGText.text ?? ""
  234. let attributeString = NSMutableAttributedString(string: bgTextStr)
  235. attributeString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributeString.length))
  236. if deltaTime >= 12 { // Data is stale
  237. attributeString.addAttribute(.strikethroughColor, value: UIColor.systemRed, range: NSRange(location: 0, length: attributeString.length))
  238. self.updateBadge(val: 0)
  239. } else { // Data is fresh
  240. attributeString.addAttribute(.strikethroughColor, value: UIColor.clear, range: NSRange(location: 0, length: attributeString.length))
  241. self.updateBadge(val: latestBG)
  242. }
  243. self.BGText.attributedText = attributeString
  244. // Snoozer Display
  245. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  246. snoozer.BGLabel.text = snoozerBG
  247. snoozer.DirectionLabel.text = snoozerDirection
  248. snoozer.DeltaLabel.text = snoozerDelta
  249. // Update contact
  250. if ObservableUserDefaults.shared.contactEnabled.value {
  251. var extra: String = ""
  252. if ObservableUserDefaults.shared.contactTrend.value {
  253. extra = snoozerDirection
  254. } else if ObservableUserDefaults.shared.contactDelta.value {
  255. extra = snoozerDelta
  256. }
  257. self.contactImageUpdater.updateContactImage(bgValue: bgTextStr, extra: extra, stale: deltaTime >= 12)
  258. }
  259. }
  260. }
  261. }