BGData.swift 13 KB

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