BGData.swift 13 KB

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