BGData.swift 12 KB

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