BGData.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // LoopFollow
  2. // BGData.swift
  3. import Foundation
  4. import UIKit
  5. extension MainViewController {
  6. // Dex Share Web Call
  7. func webLoadDexShare() {
  8. // Dexcom Share only returns 24 hrs of data as of now
  9. // Requesting more just for consistency with NS
  10. let graphHours = 24 * Storage.shared.downloadDays.value
  11. let count = graphHours * 12
  12. dexShare?.fetchData(count) { err, result in
  13. if let error = err {
  14. LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)", limitIdentifier: "Error fetching Dexcom data")
  15. self.webLoadNSBGData()
  16. return
  17. }
  18. guard let data = result, !data.isEmpty else {
  19. LogManager.shared.log(category: .dexcom, message: "Received empty data array from Dexcom", limitIdentifier: "Received empty data array from Dexcom")
  20. self.webLoadNSBGData()
  21. return
  22. }
  23. // If Dex data is old, load from NS instead
  24. let latestDate = data[0].date
  25. let now = dateTimeUtils.getNowTimeIntervalUTC()
  26. if (latestDate + 330) < now, IsNightscoutEnabled() {
  27. LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead", limitIdentifier: "Dexcom data is old, loading from NS instead")
  28. self.webLoadNSBGData()
  29. return
  30. }
  31. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  32. if graphHours > 24, IsNightscoutEnabled() {
  33. self.webLoadNSBGData(dexData: data)
  34. } else {
  35. self.ProcessDexBGData(data: data, sourceName: "Dexcom")
  36. }
  37. }
  38. }
  39. // NS BG Data Web call
  40. func webLoadNSBGData(dexData: [ShareGlucoseData] = []) {
  41. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  42. if !IsNightscoutEnabled() {
  43. return
  44. }
  45. var parameters: [String: String] = [:]
  46. let utcISODateFormatter = ISO8601DateFormatter()
  47. let date = Calendar.current.date(byAdding: .day, value: -1 * Storage.shared.downloadDays.value, to: Date())!
  48. parameters["count"] = "\(Storage.shared.downloadDays.value * 2 * 24 * 60 / 5)"
  49. parameters["find[dateString][$gte]"] = utcISODateFormatter.string(from: date)
  50. // Exclude 'cal' entries
  51. parameters["find[type][$ne]"] = "cal"
  52. NightscoutUtils.executeRequest(eventType: .sgv, parameters: parameters) { (result: Result<[ShareGlucoseData], Error>) in
  53. switch result {
  54. case let .success(entriesResponse):
  55. var nsData = entriesResponse
  56. DispatchQueue.main.async {
  57. // transform NS data to look like Dex data
  58. for i in 0 ..< nsData.count {
  59. // convert the NS timestamp to seconds instead of milliseconds
  60. nsData[i].date /= 1000
  61. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  62. }
  63. var nsData2: [ShareGlucoseData] = []
  64. var lastAddedTime = Double.infinity
  65. var lastAddedSGV: Int?
  66. let minInterval: Double = 30
  67. for reading in nsData {
  68. if (lastAddedSGV == nil || lastAddedSGV != reading.sgv) || (lastAddedTime - reading.date >= minInterval) {
  69. nsData2.append(reading)
  70. lastAddedTime = reading.date
  71. lastAddedSGV = reading.sgv
  72. }
  73. }
  74. // merge NS and Dex data if needed; use recent Dex data and older NS data
  75. var sourceName = "Nightscout"
  76. if !dexData.isEmpty {
  77. let oldestDexDate = dexData[dexData.count - 1].date
  78. var itemsToRemove = 0
  79. while itemsToRemove < nsData2.count, nsData2[itemsToRemove].date >= oldestDexDate {
  80. itemsToRemove += 1
  81. }
  82. nsData2.removeFirst(itemsToRemove)
  83. nsData2 = dexData + nsData2
  84. sourceName = "Dexcom"
  85. }
  86. // trigger the processor for the data after downloading.
  87. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  88. }
  89. case let .failure(error):
  90. LogManager.shared.log(category: .nightscout, message: "Failed to fetch bg data: \(error)", limitIdentifier: "Failed to fetch bg data")
  91. DispatchQueue.main.async {
  92. TaskScheduler.shared.rescheduleTask(
  93. id: .fetchBG,
  94. to: Date().addingTimeInterval(10)
  95. )
  96. }
  97. // if we have Dex data, use it
  98. if !dexData.isEmpty {
  99. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  100. }
  101. return
  102. }
  103. }
  104. }
  105. /// Processes incoming BG data.
  106. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String) {
  107. let graphHours = 24 * Storage.shared.downloadDays.value
  108. guard !data.isEmpty else {
  109. LogManager.shared.log(category: .nightscout, message: "No bg data received. Skipping processing.", limitIdentifier: "No bg data received. Skipping processing.")
  110. return
  111. }
  112. let latestReading = data[0]
  113. let sensorTimestamp = latestReading.date
  114. let now = dateTimeUtils.getNowTimeIntervalUTC()
  115. // secondsAgo is how old the newest reading is
  116. let secondsAgo = now - sensorTimestamp
  117. // Compute the current sensor schedule offset
  118. let currentOffset = CycleHelper.cycleOffset(for: sensorTimestamp, interval: 5 * 60)
  119. if Storage.shared.sensorScheduleOffset.value != currentOffset {
  120. Storage.shared.sensorScheduleOffset.value = currentOffset
  121. LogManager.shared.log(category: .nightscout,
  122. message: "Sensor schedule offset: \(currentOffset) seconds.",
  123. isDebug: true)
  124. }
  125. // Determine the next polling delay.
  126. var delayToSchedule: Double = 0
  127. DispatchQueue.main.async {
  128. // Fallback scheduling for older readings.
  129. if secondsAgo >= (20 * 60) {
  130. delayToSchedule = 5 * 60
  131. LogManager.shared.log(category: .nightscout,
  132. message: "Reading is very old (\(secondsAgo) sec). Scheduling next fetch in 5 minutes.",
  133. isDebug: true)
  134. } else if secondsAgo >= (10 * 60) {
  135. delayToSchedule = 60
  136. LogManager.shared.log(category: .nightscout,
  137. message: "Reading is moderately old (\(secondsAgo) sec). Scheduling next fetch in 60 seconds.",
  138. isDebug: true)
  139. } else if secondsAgo >= (7 * 60) {
  140. delayToSchedule = 30
  141. LogManager.shared.log(category: .nightscout,
  142. message: "Reading is a bit old (\(secondsAgo) sec). Scheduling next fetch in 30 seconds.",
  143. isDebug: true)
  144. } else if secondsAgo >= (5 * 60) {
  145. delayToSchedule = 5
  146. LogManager.shared.log(category: .nightscout,
  147. message: "Reading is close to 5 minutes old (\(secondsAgo) sec). Scheduling next fetch in 5 seconds.",
  148. isDebug: true)
  149. } else {
  150. delayToSchedule = 300 - secondsAgo + Double(Storage.shared.bgUpdateDelay.value)
  151. LogManager.shared.log(category: .nightscout,
  152. message: "Fresh reading. Scheduling next fetch in \(delayToSchedule) seconds.",
  153. isDebug: true)
  154. TaskScheduler.shared.rescheduleTask(id: .alarmCheck, to: Date().addingTimeInterval(3))
  155. }
  156. TaskScheduler.shared.rescheduleTask(id: .fetchBG, to: Date().addingTimeInterval(delayToSchedule))
  157. // Evaluate speak conditions if there is a previous value.
  158. if data.count > 1 {
  159. self.evaluateSpeakConditions(currentValue: data[0].sgv, previousValue: data[1].sgv)
  160. }
  161. }
  162. // Process data for graph display.
  163. bgData.removeAll()
  164. for i in 0 ..< data.count {
  165. let readingTimestamp = data[data.count - 1 - i].date
  166. if readingTimestamp >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  167. let sgvValue = data[data.count - 1 - i].sgv
  168. // Skip outlier values (e.g. first reading of a new sensor might be abnormally high).
  169. if sgvValue > 600 {
  170. LogManager.shared.log(category: .nightscout,
  171. message: "Skipping reading with sgv \(sgvValue) as it exceeds threshold.",
  172. isDebug: true)
  173. continue
  174. }
  175. let reading = ShareGlucoseData(sgv: sgvValue, date: readingTimestamp, direction: data[data.count - 1 - i].direction)
  176. bgData.append(reading)
  177. }
  178. }
  179. LogManager.shared.log(category: .nightscout,
  180. message: "Graph data updated with \(bgData.count) entries.",
  181. isDebug: true)
  182. viewUpdateNSBG(sourceName: sourceName)
  183. }
  184. func updateServerText(with serverText: String? = nil) {
  185. if Storage.shared.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  186. self.serverText.text = displayName
  187. } else if let serverText = serverText {
  188. self.serverText.text = serverText
  189. }
  190. }
  191. // NS BG Data Front end updater
  192. func viewUpdateNSBG(sourceName: String) {
  193. DispatchQueue.main.async {
  194. TaskScheduler.shared.rescheduleTask(id: .minAgoUpdate, to: Date())
  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. self.updateServerText(with: sourceName)
  205. // Set BGText with the latest BG value
  206. self.setBGTextColor()
  207. Observable.shared.bgText.value = Localizer.toDisplayUnits(String(latestBG))
  208. Observable.shared.bg.value = latestBG
  209. // Direction handling
  210. if let directionBG = entries[latestEntryIndex].direction {
  211. Observable.shared.directionText.value = self.bgDirectionGraphic(directionBG)
  212. } else {
  213. Observable.shared.directionText.value = ""
  214. }
  215. // Delta handling
  216. if deltaBG < 0 {
  217. Observable.shared.deltaText.value = Localizer.toDisplayUnits(String(deltaBG))
  218. } else {
  219. Observable.shared.deltaText.value = "+" + Localizer.toDisplayUnits(String(deltaBG))
  220. }
  221. // Update contact
  222. if Storage.shared.contactEnabled.value {
  223. self.contactImageUpdater
  224. .updateContactImage(
  225. bgValue: Observable.shared.bgText.value,
  226. trend: Observable.shared.directionText.value,
  227. delta: Observable.shared.deltaText.value,
  228. stale: Observable.shared.bgStale.value
  229. )
  230. }
  231. }
  232. }
  233. }