NightScout.swift 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  1. //
  2. // NightScout.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 6/16/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension MainViewController {
  11. //NS Carbs Struct
  12. struct carbsData: Codable {
  13. var carbs: Double?
  14. }
  15. //NS Cage Struct
  16. struct cageData: Codable {
  17. var created_at: String
  18. }
  19. //NS Basal Profile Struct
  20. struct basalProfileStruct: Codable {
  21. var value: Double
  22. var time: String
  23. var timeAsSeconds: Double
  24. }
  25. //NS Basal Data Struct
  26. struct basalGraphStruct: Codable {
  27. var basalRate: Double
  28. var date: TimeInterval
  29. }
  30. //NS Bolus Data Struct
  31. struct bolusGraphStruct: Codable {
  32. var value: Double
  33. var date: TimeInterval
  34. var sgv: Int
  35. }
  36. //NS Bolus Data Struct
  37. struct carbGraphStruct: Codable {
  38. var value: Double
  39. var date: TimeInterval
  40. var sgv: Int
  41. var absorptionTime: Int
  42. }
  43. func isStaleData() -> Bool {
  44. if bgData.count > 0 {
  45. let now = dateTimeUtils.getNowTimeIntervalUTC()
  46. let lastReadingTime = bgData.last!.date
  47. let secondsAgo = now - lastReadingTime
  48. if secondsAgo >= 20*60 {
  49. return true
  50. } else {
  51. return false
  52. }
  53. } else {
  54. return false
  55. }
  56. }
  57. // Dex Share Web Call
  58. func webLoadDexShare(onlyPullLastRecord: Bool = false) {
  59. // Dexcom Share only returns 24 hrs of data as of now
  60. // Requesting more just for consistency with NS
  61. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  62. var count = graphHours * 12
  63. if onlyPullLastRecord { count = 1 }
  64. dexShare?.fetchData(count) { (err, result) -> () in
  65. // TODO: add error checking
  66. if(err == nil) {
  67. var data = result!
  68. // If Dex data is old, load from NS instead
  69. let latestDate = data[0].date
  70. let now = dateTimeUtils.getNowTimeIntervalUTC()
  71. if (latestDate + 330) < now && UserDefaultsRepository.url.value != "" {
  72. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  73. print("dex didn't load, triggered NS attempt")
  74. return
  75. }
  76. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  77. if graphHours > 24 && !onlyPullLastRecord && UserDefaultsRepository.url.value != "" {
  78. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord, dexData: data)
  79. } else {
  80. self.ProcessDexBGData(data: data, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  81. }
  82. } else {
  83. // If we get an error, immediately try to pull NS BG Data
  84. if UserDefaultsRepository.url.value != "" {
  85. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  86. }
  87. if globalVariables.dexVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  88. globalVariables.dexVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  89. DispatchQueue.main.async {
  90. //self.sendNotification(title: "Dexcom Share Error", body: "Please double check user name and password, internet connection, and sharing status.")
  91. }
  92. }
  93. }
  94. }
  95. }
  96. // NS BG Data Web call
  97. func webLoadNSBGData(onlyPullLastRecord: Bool = false, dexData: [ShareGlucoseData] = []) {
  98. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  99. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  100. if UserDefaultsRepository.url.value == "" {
  101. self.startBGTimer(time: 10)
  102. return
  103. }
  104. // URL processor
  105. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  106. if onlyPullLastRecord {
  107. urlBGDataPath = urlBGDataPath + "count=1"
  108. } else {
  109. //Fetch entries for the time period of "downloadDays"
  110. let utcISODateFormatter = ISO8601DateFormatter()
  111. let date = Calendar.current.date(byAdding: .day, value: -1 * UserDefaultsRepository.downloadDays.value, to: Date())!
  112. urlBGDataPath = urlBGDataPath + "count=1000&find[dateString][$gte]=" + utcISODateFormatter.string(from: date)
  113. }
  114. if !token.isEmpty {
  115. urlBGDataPath = urlBGDataPath + "&token=" + token
  116. }
  117. guard let urlBGData = URL(string: urlBGDataPath) else {
  118. // if we have Dex data, use it
  119. if !dexData.isEmpty {
  120. self.ProcessDexBGData(data: dexData, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  121. return
  122. }
  123. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  124. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  125. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  126. }
  127. DispatchQueue.main.async {
  128. if self.bgTimer.isValid {
  129. self.bgTimer.invalidate()
  130. }
  131. self.startBGTimer(time: 10)
  132. }
  133. return
  134. }
  135. var request = URLRequest(url: urlBGData)
  136. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  137. // Downloader
  138. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  139. guard error == nil else {
  140. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  141. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  142. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  143. }
  144. DispatchQueue.main.async {
  145. if self.bgTimer.isValid {
  146. self.bgTimer.invalidate()
  147. }
  148. self.startBGTimer(time: 10)
  149. }
  150. // if we have Dex data, use it
  151. if !dexData.isEmpty {
  152. self.ProcessDexBGData(data: dexData, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  153. }
  154. return
  155. }
  156. guard let data = data else {
  157. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  158. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  159. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  160. }
  161. DispatchQueue.main.async {
  162. if self.bgTimer.isValid {
  163. self.bgTimer.invalidate()
  164. }
  165. self.startBGTimer(time: 10)
  166. }
  167. return
  168. }
  169. var entriesResponse: [ShareGlucoseData]?
  170. let decoder = JSONDecoder()
  171. do {
  172. entriesResponse = try decoder.decode([ShareGlucoseData].self, from: data)
  173. } catch let DecodingError.dataCorrupted(context) {
  174. print("Data corrupted: \(context)")
  175. } catch let DecodingError.keyNotFound(key, context) {
  176. print("Key '\(key)' not found: \(context.debugDescription)")
  177. print("codingPath: \(context.codingPath)")
  178. } catch let DecodingError.valueNotFound(value, context) {
  179. print("Value '\(value)' not found: \(context.debugDescription)")
  180. print("codingPath: \(context.codingPath)")
  181. } catch let DecodingError.typeMismatch(type, context) {
  182. print("Type '\(type)' mismatch: \(context.debugDescription)")
  183. print("codingPath: \(context.codingPath)")
  184. } catch {
  185. print("Error decoding JSON: \(error)")
  186. }
  187. if var nsData = entriesResponse {
  188. DispatchQueue.main.async {
  189. // transform NS data to look like Dex data
  190. for i in 0..<nsData.count {
  191. // convert the NS timestamp to seconds instead of milliseconds
  192. nsData[i].date /= 1000
  193. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  194. }
  195. print(nsData.count)
  196. //Avoid duplicate entries messing up the graph, only use one reading per 5 minutes.
  197. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  198. let points = graphHours * 12 + 1
  199. var nsData2 = [ShareGlucoseData]()
  200. let timestamp = Date().timeIntervalSince1970
  201. for i in 0..<points {
  202. //Starting with "now" and then step 5 minutes back in time
  203. let target = timestamp - Double(i) * 60 * 5
  204. //Find the reading closest to the target, but not too far away
  205. let closest = nsData.filter{ abs($0.date - target) < 3 * 60 }.min { abs($0.date - target) < abs($1.date - target) }
  206. //If a reading is found, add it to the new array
  207. if let item = closest {
  208. nsData2.append(item)
  209. }
  210. }
  211. print(nsData2.count)
  212. // merge NS and Dex data if needed; use recent Dex data and older NS data
  213. var sourceName = "Nightscout"
  214. if !dexData.isEmpty {
  215. let oldestDexDate = dexData[dexData.count - 1].date
  216. var itemsToRemove = 0
  217. while itemsToRemove < nsData2.count && nsData2[itemsToRemove].date >= oldestDexDate {
  218. itemsToRemove += 1
  219. }
  220. nsData2.removeFirst(itemsToRemove)
  221. nsData2 = dexData + nsData2
  222. sourceName = "Dexcom"
  223. }
  224. // trigger the processor for the data after downloading.
  225. self.ProcessDexBGData(data: nsData2, onlyPullLastRecord: onlyPullLastRecord, sourceName: sourceName)
  226. }
  227. } else {
  228. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  229. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  230. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  231. }
  232. DispatchQueue.main.async {
  233. if self.bgTimer.isValid {
  234. self.bgTimer.invalidate()
  235. }
  236. self.startBGTimer(time: 10)
  237. }
  238. return
  239. }
  240. }
  241. getBGTask.resume()
  242. }
  243. // Dexcom BG Data Response processor
  244. func ProcessDexBGData(data: [ShareGlucoseData], onlyPullLastRecord: Bool, sourceName: String){
  245. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  246. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  247. let pullDate = data[data.count - 1].date
  248. let latestDate = data[0].date
  249. let now = dateTimeUtils.getNowTimeIntervalUTC()
  250. // Start the BG timer based on the reading
  251. let secondsAgo = now - latestDate
  252. DispatchQueue.main.async {
  253. // if reading is overdue over: 20:00, re-attempt every 5 minutes
  254. if secondsAgo >= (20 * 60) {
  255. self.startBGTimer(time: (5 * 60))
  256. print("##### started 5 minute bg timer")
  257. // if the reading is overdue: 10:00-19:59, re-attempt every minute
  258. } else if secondsAgo >= (10 * 60) {
  259. self.startBGTimer(time: 60)
  260. print("##### started 1 minute bg timer")
  261. // if the reading is overdue: 7:00-9:59, re-attempt every 30 seconds
  262. } else if secondsAgo >= (7 * 60) {
  263. self.startBGTimer(time: 30)
  264. print("##### started 30 second bg timer")
  265. // if the reading is overdue: 5:00-6:59 re-attempt every 10 seconds
  266. } else if secondsAgo >= (5 * 60) {
  267. self.startBGTimer(time: 10)
  268. print("##### started 10 second bg timer")
  269. // We have a current reading. Set timer to 5:10 from last reading
  270. } else {
  271. self.startBGTimer(time: 300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value))
  272. let timerVal = 310 - secondsAgo
  273. print("##### started 5:10 bg timer: \(timerVal)")
  274. self.updateBadge(val: data[0].sgv)
  275. if UserDefaultsRepository.speakBG.value {
  276. self.speakBG(currentValue: data[0].sgv, previousValue: data[1].sgv)
  277. }
  278. }
  279. }
  280. // If we already have data, we're going to pop it to the end and remove the first. If we have old or no data, we'll destroy the whole array and start over. This is simpler than determining how far back we need to get new data from in case Dex back-filled readings
  281. if !onlyPullLastRecord {
  282. bgData.removeAll()
  283. } else if bgData[bgData.count - 1].date != pullDate {
  284. bgData.removeFirst()
  285. } else {
  286. return
  287. }
  288. // loop through the data so we can reverse the order to oldest first for the graph
  289. for i in 0..<data.count{
  290. let dateString = data[data.count - 1 - i].date
  291. if dateString >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  292. let reading = ShareGlucoseData(sgv: data[data.count - 1 - i].sgv, date: dateString, direction: data[data.count - 1 - i].direction)
  293. bgData.append(reading)
  294. }
  295. }
  296. viewUpdateNSBG(sourceName: sourceName)
  297. }
  298. // NS BG Data Front end updater
  299. func viewUpdateNSBG (sourceName: String) {
  300. DispatchQueue.main.async {
  301. if UserDefaultsRepository.debugLog.value {
  302. self.writeDebugLog(value: "Display: BG")
  303. self.writeDebugLog(value: "Num BG: " + self.bgData.count.description)
  304. }
  305. let entries = self.bgData
  306. if entries.count < 1 { return }
  307. self.updateBGGraph()
  308. self.updateStats()
  309. let latestEntryi = entries.count - 1
  310. let latestBG = entries[latestEntryi].sgv
  311. let priorBG = entries[latestEntryi - 1].sgv
  312. let deltaBG = latestBG - priorBG as Int
  313. let lastBGTime = entries[latestEntryi].date
  314. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  315. var userUnit = " mg/dL"
  316. if self.mmol {
  317. userUnit = " mmol/L"
  318. }
  319. self.serverText.text = sourceName
  320. var snoozerBG = ""
  321. var snoozerDirection = ""
  322. var snoozerDelta = ""
  323. self.BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  324. snoozerBG = bgUnits.toDisplayUnits(String(latestBG))
  325. self.setBGTextColor()
  326. if let directionBG = entries[latestEntryi].direction {
  327. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  328. snoozerDirection = self.bgDirectionGraphic(directionBG)
  329. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  330. }
  331. else
  332. {
  333. self.DirectionText.text = ""
  334. snoozerDirection = ""
  335. self.latestDirectionString = ""
  336. }
  337. if deltaBG < 0 {
  338. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  339. snoozerDelta = bgUnits.toDisplayUnits(String(deltaBG))
  340. self.latestDeltaString = String(deltaBG)
  341. }
  342. else
  343. {
  344. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  345. snoozerDelta = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  346. self.latestDeltaString = "+" + String(deltaBG)
  347. }
  348. // Snoozer Display
  349. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  350. snoozer.BGLabel.text = snoozerBG
  351. snoozer.DirectionLabel.text = snoozerDirection
  352. snoozer.DeltaLabel.text = snoozerDelta
  353. }
  354. }
  355. // NS Device Status Web Call
  356. func webLoadNSDeviceStatus() {
  357. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: device status") }
  358. let urlUser = UserDefaultsRepository.url.value
  359. // NS Api is not working to find by greater than date
  360. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288"
  361. if token != "" {
  362. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288&token=" + token
  363. }
  364. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  365. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  366. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  367. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  368. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  369. }
  370. DispatchQueue.main.async {
  371. if self.deviceStatusTimer.isValid {
  372. self.deviceStatusTimer.invalidate()
  373. }
  374. self.startDeviceStatusTimer(time: 10)
  375. }
  376. return
  377. }
  378. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  379. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  380. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  381. guard error == nil else {
  382. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  383. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  384. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  385. }
  386. DispatchQueue.main.async {
  387. if self.deviceStatusTimer.isValid {
  388. self.deviceStatusTimer.invalidate()
  389. }
  390. self.startDeviceStatusTimer(time: 10)
  391. }
  392. return
  393. }
  394. guard let data = data else {
  395. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  396. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  397. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  398. }
  399. DispatchQueue.main.async {
  400. if self.deviceStatusTimer.isValid {
  401. self.deviceStatusTimer.invalidate()
  402. }
  403. self.startDeviceStatusTimer(time: 10)
  404. }
  405. return
  406. }
  407. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  408. if let json = json {
  409. DispatchQueue.main.async {
  410. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  411. }
  412. } else {
  413. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  414. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  415. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  416. }
  417. DispatchQueue.main.async {
  418. if self.deviceStatusTimer.isValid {
  419. self.deviceStatusTimer.invalidate()
  420. }
  421. self.startDeviceStatusTimer(time: 10)
  422. }
  423. return
  424. }
  425. }
  426. deviceStatusTask.resume()
  427. }
  428. // NS Device Status Response Processor
  429. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  430. self.clearLastInfoData(index: 0)
  431. self.clearLastInfoData(index: 1)
  432. self.clearLastInfoData(index: 3)
  433. self.clearLastInfoData(index: 4)
  434. self.clearLastInfoData(index: 5)
  435. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  436. if jsonDeviceStatus.count == 0 {
  437. return
  438. }
  439. //Process the current data first
  440. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  441. //pump and uploader
  442. let formatter = ISO8601DateFormatter()
  443. formatter.formatOptions = [.withFullDate,
  444. .withTime,
  445. .withDashSeparatorInDate,
  446. .withColonSeparatorInTime]
  447. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  448. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  449. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  450. latestPumpVolume = reservoirData
  451. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  452. } else {
  453. latestPumpVolume = 50.0
  454. tableData[5].value = "50+U"
  455. }
  456. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  457. let upbat = uploader["battery"] as! Double
  458. tableData[4].value = String(format:"%.0f", upbat) + "%"
  459. UserDefaultsRepository.deviceBatteryLevel.value = upbat
  460. }
  461. }
  462. }
  463. // Loop
  464. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  465. //print("Loop: \(lastLoopRecord)")
  466. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  467. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  468. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  469. if let failure = lastLoopRecord["failureReason"] {
  470. LoopStatusLabel.text = "X"
  471. latestLoopStatusString = "X"
  472. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  473. } else {
  474. var wasEnacted = false
  475. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  476. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  477. wasEnacted = true
  478. if let lastTempBasal = enacted["rate"] as? Double {
  479. }
  480. }
  481. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  482. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  483. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  484. }
  485. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  486. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  487. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  488. }
  489. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  490. let prediction = predictdata["values"] as! [Double]
  491. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  492. PredictionLabel.textColor = UIColor.systemPurple
  493. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  494. predictionData.removeAll()
  495. var predictionTime = lastLoopTime
  496. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  497. var i = 0
  498. while i <= toLoad {
  499. if i < prediction.count {
  500. let prediction = ShareGlucoseData(sgv: Int(round(prediction[i])), date: predictionTime, direction: "flat")
  501. predictionData.append(prediction)
  502. predictionTime += 300
  503. }
  504. i += 1
  505. }
  506. let predMin = prediction.min()
  507. let predMax = prediction.max()
  508. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  509. updatePredictionGraph()
  510. }
  511. }
  512. if let recBolus = lastLoopRecord["recommendedBolus"] as? Double {
  513. tableData[8].value = String(format:"%.2fU", recBolus)
  514. }
  515. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  516. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  517. var lastBGTime = lastLoopTime
  518. if bgData.count > 0 {
  519. lastBGTime = bgData[bgData.count - 1].date
  520. }
  521. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  522. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  523. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  524. if tempBasalTime > lastBGTime && !wasEnacted {
  525. LoopStatusLabel.text = "⏀"
  526. latestLoopStatusString = "⏀"
  527. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  528. } else {
  529. LoopStatusLabel.text = "↻"
  530. latestLoopStatusString = "↻"
  531. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  532. }
  533. }
  534. } else {
  535. LoopStatusLabel.text = "↻"
  536. latestLoopStatusString = "↻"
  537. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  538. }
  539. }
  540. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  541. LoopStatusLabel.text = "⚠"
  542. latestLoopStatusString = "⚠"
  543. }
  544. latestLoopTime = lastLoopTime
  545. } // end lastLoopTime
  546. } // end lastLoop Record
  547. var oText = "" as String
  548. currentOverride = 1.0
  549. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  550. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  551. }
  552. if lastOverride["active"] as! Bool {
  553. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  554. if let multiplier = lastOverride["multiplier"] as? Double {
  555. currentOverride = multiplier
  556. oText += String(format: "%.0f%%", (multiplier * 100))
  557. }
  558. else
  559. {
  560. oText += "100%"
  561. }
  562. oText += " ("
  563. let minValue = lastCorrection["minValue"] as! Double
  564. let maxValue = lastCorrection["maxValue"] as! Double
  565. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  566. tableData[3].value = oText
  567. }
  568. }
  569. infoTable.reloadData()
  570. // Start the timer based on the timestamp
  571. let now = dateTimeUtils.getNowTimeIntervalUTC()
  572. let secondsAgo = now - latestLoopTime
  573. DispatchQueue.main.async {
  574. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  575. if secondsAgo >= (20 * 60) {
  576. self.startDeviceStatusTimer(time: (5 * 60))
  577. print("started 5 minute device status timer")
  578. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  579. } else if secondsAgo >= (10 * 60) {
  580. self.startDeviceStatusTimer(time: 60)
  581. print("started 1 minute device status timer")
  582. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  583. } else if secondsAgo >= (7 * 60) {
  584. self.startDeviceStatusTimer(time: 30)
  585. print("started 30 second device status timer")
  586. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  587. } else if secondsAgo >= (5 * 60) {
  588. self.startDeviceStatusTimer(time: 10)
  589. print("started 10 second device status timer")
  590. // We have a current Loop. Set timer to 5:10 from last reading
  591. } else {
  592. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  593. let timerVal = 310 - secondsAgo
  594. print("started 5:10 device status timer: \(timerVal)")
  595. }
  596. }
  597. }
  598. // NS Carbs Today Web Call
  599. func webLoadNSCarbsToday() {
  600. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs Today") }
  601. let urlUser = UserDefaultsRepository.url.value
  602. let now = Date()
  603. let timeZone = TimeZone.current
  604. var calendar = Calendar(identifier: .gregorian)
  605. calendar.timeZone = timeZone
  606. var dateComponents = calendar.dateComponents(in: timeZone, from: now)
  607. dateComponents.hour = 0
  608. dateComponents.minute = 0
  609. dateComponents.second = 0
  610. guard let date = dateComponents.date else { fatalError("Invalid date components") }
  611. let dateFormatter = DateFormatter()
  612. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  613. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  614. let utcDateString = dateFormatter.string(from: date)
  615. var urlString = urlUser + "/api/v1/treatments.json?count=1000&find[eventType]=Carb+Correction&find[timestamp][$gte]=" + utcDateString
  616. if token != "" {
  617. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&count=1000&find[eventType]=Carb+Correction&find[timestamp][$gte]=" + utcDateString
  618. }
  619. guard let urlData = URL(string: urlString) else {
  620. return
  621. }
  622. var request = URLRequest(url: urlData)
  623. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  624. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  625. guard error == nil else {
  626. return
  627. }
  628. guard let data = data else {
  629. return
  630. }
  631. let decoder = JSONDecoder()
  632. let entriesResponse = try? decoder.decode([carbsData].self, from: data)
  633. if let entriesResponse = entriesResponse {
  634. DispatchQueue.main.async {
  635. self.updateCarbsToday(data: entriesResponse)
  636. }
  637. } else {
  638. return
  639. }
  640. }
  641. task.resume()
  642. }
  643. // NS CarbsToday Response Processor
  644. func updateCarbsToday(data: [carbsData]) {
  645. self.clearLastInfoData(index: 10)
  646. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: carbs") }
  647. if data.count == 0 {
  648. return
  649. }
  650. let totalCarbs = data.reduce(0.0) { $0 + ($1.carbs ?? 0.0) }
  651. let resultString = String(format: "%.0f", totalCarbs)
  652. tableData[10].value = resultString
  653. infoTable.reloadData()
  654. }
  655. // NS Cage Web Call
  656. func webLoadNSCage() {
  657. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  658. let urlUser = UserDefaultsRepository.url.value
  659. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  660. if token != "" {
  661. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  662. }
  663. guard let urlData = URL(string: urlString) else {
  664. return
  665. }
  666. var request = URLRequest(url: urlData)
  667. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  668. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  669. guard error == nil else {
  670. return
  671. }
  672. guard let data = data else {
  673. return
  674. }
  675. let decoder = JSONDecoder()
  676. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  677. if let entriesResponse = entriesResponse {
  678. DispatchQueue.main.async {
  679. self.updateCage(data: entriesResponse)
  680. }
  681. } else {
  682. return
  683. }
  684. }
  685. task.resume()
  686. }
  687. // NS Cage Response Processor
  688. func updateCage(data: [cageData]) {
  689. self.clearLastInfoData(index: 7)
  690. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  691. if data.count == 0 {
  692. return
  693. }
  694. let lastCageString = data[0].created_at
  695. let formatter = ISO8601DateFormatter()
  696. formatter.formatOptions = [.withFullDate,
  697. .withTime,
  698. .withDashSeparatorInDate,
  699. .withColonSeparatorInTime]
  700. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  701. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  702. let now = dateTimeUtils.getNowTimeIntervalUTC()
  703. let secondsAgo = now - cageTime
  704. //let days = 24 * 60 * 60
  705. let formatter = DateComponentsFormatter()
  706. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  707. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  708. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  709. let formattedDuration = formatter.string(from: secondsAgo)
  710. tableData[7].value = formattedDuration ?? ""
  711. }
  712. infoTable.reloadData()
  713. }
  714. // NS Sage Web Call
  715. func webLoadNSSage() {
  716. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  717. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  718. let urlUser = UserDefaultsRepository.url.value
  719. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  720. if token != "" {
  721. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  722. }
  723. guard let urlData = URL(string: urlString) else {
  724. return
  725. }
  726. var request = URLRequest(url: urlData)
  727. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  728. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  729. guard error == nil else {
  730. return
  731. }
  732. guard let data = data else {
  733. return
  734. }
  735. let decoder = JSONDecoder()
  736. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  737. if let entriesResponse = entriesResponse {
  738. DispatchQueue.main.async {
  739. self.updateSage(data: entriesResponse)
  740. }
  741. } else {
  742. return
  743. }
  744. }
  745. task.resume()
  746. }
  747. // NS Sage Response Processor
  748. func updateSage(data: [cageData]) {
  749. self.clearLastInfoData(index: 6)
  750. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  751. if data.count == 0 {
  752. return
  753. }
  754. var lastSageString = data[0].created_at
  755. let formatter = ISO8601DateFormatter()
  756. formatter.formatOptions = [.withFullDate,
  757. .withTime,
  758. .withDashSeparatorInDate,
  759. .withColonSeparatorInTime]
  760. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  761. if UserDefaultsRepository.alertAutoSnoozeCGMStart.value && (dateTimeUtils.getNowTimeIntervalUTC() - UserDefaultsRepository.alertSageInsertTime.value < 7200){
  762. let snoozeTime = Date(timeIntervalSince1970: UserDefaultsRepository.alertSageInsertTime.value + 7200)
  763. UserDefaultsRepository.alertSnoozeAllTime.value = snoozeTime
  764. UserDefaultsRepository.alertSnoozeAllIsSnoozed.value = true
  765. guard let alarms = self.tabBarController!.viewControllers?[1] as? AlarmViewController else { return }
  766. alarms.reloadIsSnoozed(key: "alertSnoozeAllIsSnoozed", value: true)
  767. alarms.reloadSnoozeTime(key: "alertSnoozeAllTime", setNil: false, value: snoozeTime)
  768. }
  769. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  770. let now = dateTimeUtils.getNowTimeIntervalUTC()
  771. let secondsAgo = now - sageTime
  772. let days = 24 * 60 * 60
  773. let formatter = DateComponentsFormatter()
  774. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  775. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  776. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  777. let formattedDuration = formatter.string(from: secondsAgo)
  778. tableData[6].value = formattedDuration ?? ""
  779. }
  780. infoTable.reloadData()
  781. }
  782. // NS Profile Web Call
  783. func webLoadNSProfile() {
  784. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  785. let urlUser = UserDefaultsRepository.url.value
  786. var urlString = urlUser + "/api/v1/profile/current.json"
  787. if token != "" {
  788. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  789. }
  790. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  791. guard let url = URL(string: escapedAddress!) else {
  792. return
  793. }
  794. var request = URLRequest(url: url)
  795. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  796. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  797. guard error == nil else {
  798. return
  799. }
  800. guard let data = data else {
  801. return
  802. }
  803. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  804. if let json = json {
  805. DispatchQueue.main.async {
  806. self.updateProfile(jsonDeviceStatus: json)
  807. }
  808. } else {
  809. return
  810. }
  811. }
  812. task.resume()
  813. }
  814. // NS Profile Response Processor
  815. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  816. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  817. if jsonDeviceStatus.count == 0 {
  818. return
  819. }
  820. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  821. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  822. basalProfile.removeAll()
  823. for i in 0..<basal.count {
  824. let dict = basal[i] as! Dictionary<String, Any>
  825. do {
  826. let thisValue = try dict[keyPath: "value"] as! Double
  827. let thisTime = dict[keyPath: "time"] as! String
  828. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  829. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  830. basalProfile.append(entry)
  831. } catch {
  832. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  833. }
  834. }
  835. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  836. if firstGraphLoad { return }
  837. var basalSegments: [DataStructs.basalProfileSegment] = []
  838. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  839. // Build scheduled basal segments from right to left by
  840. // moving pointers to the current midnight and current basal
  841. var midnight = dateTimeUtils.getTimeIntervalMidnightToday()
  842. var basalProfileIndex = basalProfile.count - 1
  843. var start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  844. var end = dateTimeUtils.getNowTimeIntervalUTC()
  845. // Move back until we're in the graph range
  846. while start > end {
  847. basalProfileIndex -= 1
  848. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  849. }
  850. // Add records while they're still within the graph
  851. let graphStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  852. while end >= graphStart {
  853. let entry = DataStructs.basalProfileSegment(
  854. basalRate: basalProfile[basalProfileIndex].value, startDate: start, endDate: end)
  855. basalSegments.append(entry)
  856. basalProfileIndex -= 1
  857. if basalProfileIndex < 0 {
  858. basalProfileIndex = basalProfile.count - 1
  859. midnight = midnight.advanced(by: -24*60*60)
  860. }
  861. end = start - 1
  862. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  863. }
  864. // reverse the result to get chronological order
  865. basalSegments.reverse()
  866. var firstPass = true
  867. // Runs the scheduled basal to the end of the prediction line
  868. var predictionEndTime = dateTimeUtils.getNowTimeIntervalUTC() + (3600 * UserDefaultsRepository.predictionToLoad.value)
  869. basalScheduleData.removeAll()
  870. for i in 0..<basalSegments.count {
  871. let timeStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  872. // This processed everything after the first one.
  873. if firstPass == false
  874. && basalSegments[i].startDate <= predictionEndTime {
  875. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: basalSegments[i].startDate)
  876. basalScheduleData.append(startDot)
  877. var endDate = basalSegments[i].endDate
  878. // if it's the last one needed, set it to end at the prediction end time
  879. if endDate > predictionEndTime || i == basalSegments.count - 1 {
  880. endDate = Double(predictionEndTime)
  881. }
  882. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  883. basalScheduleData.append(endDot)
  884. }
  885. // we need to manually set the first one
  886. // Check that this is the first one and there are no existing entries
  887. if firstPass == true {
  888. // check that the timestamp is > the current entry and < the next entry
  889. if timeStart >= basalSegments[i].startDate && timeStart < basalSegments[i].endDate {
  890. // Set the start time to match the BG start
  891. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: Double(timeStart + (60 * 5)))
  892. basalScheduleData.append(startDot)
  893. // set the enddot where the next one will start
  894. var endDate = basalSegments[i].endDate
  895. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  896. basalScheduleData.append(endDot)
  897. firstPass = false
  898. }
  899. }
  900. }
  901. if UserDefaultsRepository.graphBasal.value {
  902. updateBasalScheduledGraph()
  903. }
  904. }
  905. // NS Treatments Web Call
  906. // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
  907. func WebLoadNSTreatments() {
  908. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Treatments") }
  909. if !UserDefaultsRepository.downloadTreatments.value { return }
  910. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  911. let startTimeString = dateTimeUtils.nowMinusNHoursTimeInterval(N: graphHours)
  912. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[created_at][$gte]=" + startTimeString
  913. if token != "" {
  914. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[created_at][$gte]=" + startTimeString
  915. }
  916. guard let urlData = URL(string: urlString) else {
  917. return
  918. }
  919. var request = URLRequest(url: urlData)
  920. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  921. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  922. guard error == nil else {
  923. return
  924. }
  925. guard let data = data else {
  926. return
  927. }
  928. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  929. if let json = json {
  930. DispatchQueue.main.async {
  931. self.updateTreatments(entries: json)
  932. }
  933. } else {
  934. return
  935. }
  936. }
  937. task.resume()
  938. }
  939. // Process and split out treatments to individual tasks
  940. func updateTreatments(entries: [[String:AnyObject]]) {
  941. var tempBasal: [[String:AnyObject]] = []
  942. var bolus: [[String:AnyObject]] = []
  943. var carbs: [[String:AnyObject]] = []
  944. var temporaryOverride: [[String:AnyObject]] = []
  945. var note: [[String:AnyObject]] = []
  946. var bgCheck: [[String:AnyObject]] = []
  947. var suspendPump: [[String:AnyObject]] = []
  948. var resumePump: [[String:AnyObject]] = []
  949. var pumpSiteChange: [[String:AnyObject]] = []
  950. var cgmSensorStart: [[String:AnyObject]] = []
  951. for i in 0..<entries.count {
  952. let entry = entries[i] as [String : AnyObject]?
  953. switch entry?["eventType"] as! String {
  954. case "Temp Basal":
  955. tempBasal.append(entry!)
  956. case "Correction Bolus":
  957. bolus.append(entry!)
  958. case "Meal Bolus":
  959. carbs.append(entry!)
  960. bolus.append(entry!)
  961. case "Carb Correction":
  962. carbs.append(entry!)
  963. case "Temporary Override":
  964. temporaryOverride.append(entry!)
  965. case "Note":
  966. note.append(entry!)
  967. print("Note: \(String(describing: entry))")
  968. case "BG Check":
  969. bgCheck.append(entry!)
  970. case "Suspend Pump":
  971. suspendPump.append(entry!)
  972. case "Resume Pump":
  973. resumePump.append(entry!)
  974. case "Pump Site Change":
  975. pumpSiteChange.append(entry!)
  976. case "Sensor Start":
  977. cgmSensorStart.append(entry!)
  978. default:
  979. print("No Match: \(String(describing: entry))")
  980. }
  981. }
  982. // end of for loop
  983. if tempBasal.count > 0 {
  984. processNSBasals(entries: tempBasal)
  985. } else {
  986. if basalData.count < 0 {
  987. clearOldTempBasal()
  988. }
  989. }
  990. if bolus.count > 0 {
  991. processNSBolus(entries: bolus)
  992. } else {
  993. if bolusData.count > 0 {
  994. clearOldBolus()
  995. }
  996. }
  997. if carbs.count > 0 {
  998. processNSCarbs(entries: carbs)
  999. } else {
  1000. if carbData.count > 0 {
  1001. clearOldCarb()
  1002. }
  1003. }
  1004. if bgCheck.count > 0 {
  1005. processNSBGCheck(entries: bgCheck)
  1006. } else {
  1007. if bgCheckData.count > 0 {
  1008. clearOldBGCheck()
  1009. }
  1010. }
  1011. if temporaryOverride.count > 0 {
  1012. processNSOverrides(entries: temporaryOverride)
  1013. } else {
  1014. if overrideGraphData.count > 0 {
  1015. clearOldOverride()
  1016. }
  1017. }
  1018. if suspendPump.count > 0 {
  1019. processSuspendPump(entries: suspendPump)
  1020. } else {
  1021. if suspendGraphData.count > 0 {
  1022. clearOldSuspend()
  1023. }
  1024. }
  1025. if resumePump.count > 0 {
  1026. processResumePump(entries: resumePump)
  1027. } else {
  1028. if resumeGraphData.count > 0 {
  1029. clearOldResume()
  1030. }
  1031. }
  1032. if cgmSensorStart.count > 0 {
  1033. processSensorStart(entries: cgmSensorStart)
  1034. } else {
  1035. if sensorStartGraphData.count > 0 {
  1036. clearOldSensor()
  1037. }
  1038. }
  1039. if note.count > 0 {
  1040. processNotes(entries: note)
  1041. } else {
  1042. if noteGraphData.count > 0 {
  1043. clearOldNotes()
  1044. }
  1045. }
  1046. }
  1047. func clearOldTempBasal()
  1048. {
  1049. basalData.removeAll()
  1050. updateBasalGraph()
  1051. }
  1052. func clearOldBolus()
  1053. {
  1054. bolusData.removeAll()
  1055. updateBolusGraph()
  1056. }
  1057. func clearOldCarb()
  1058. {
  1059. carbData.removeAll()
  1060. updateCarbGraph()
  1061. }
  1062. func clearOldBGCheck()
  1063. {
  1064. bgCheckData.removeAll()
  1065. updateBGCheckGraph()
  1066. }
  1067. func clearOldOverride()
  1068. {
  1069. overrideGraphData.removeAll()
  1070. updateOverrideGraph()
  1071. }
  1072. func clearOldSuspend()
  1073. {
  1074. suspendGraphData.removeAll()
  1075. updateSuspendGraph()
  1076. }
  1077. func clearOldResume()
  1078. {
  1079. resumeGraphData.removeAll()
  1080. updateResumeGraph()
  1081. }
  1082. func clearOldSensor()
  1083. {
  1084. sensorStartGraphData.removeAll()
  1085. updateSensorStart()
  1086. }
  1087. func clearOldNotes()
  1088. {
  1089. noteGraphData.removeAll()
  1090. updateNotes()
  1091. }
  1092. // NS Temp Basal Response Processor
  1093. func processNSBasals(entries: [[String:AnyObject]]) {
  1094. self.clearLastInfoData(index: 2)
  1095. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  1096. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  1097. basalData.removeAll()
  1098. var lastEndDot = 0.0
  1099. var tempArray = entries
  1100. tempArray.reverse()
  1101. for i in 0..<tempArray.count {
  1102. let currentEntry = tempArray[i] as [String : AnyObject]?
  1103. var basalDate: String
  1104. if currentEntry?["timestamp"] != nil {
  1105. basalDate = currentEntry?["timestamp"] as! String
  1106. } else if currentEntry?["created_at"] != nil {
  1107. basalDate = currentEntry?["created_at"] as! String
  1108. } else {
  1109. continue
  1110. }
  1111. var strippedZone = String(basalDate.dropLast())
  1112. strippedZone = strippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1113. let dateFormatter = DateFormatter()
  1114. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1115. dateFormatter.locale = Locale(identifier: "en_US")
  1116. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1117. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1118. let dateTimeStamp = dateString.timeIntervalSince1970
  1119. guard let basalRate = currentEntry?["absolute"] as? Double else {
  1120. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Basal entry")}
  1121. continue
  1122. }
  1123. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  1124. // Setting end dots
  1125. var duration = 0.0
  1126. do {
  1127. duration = try currentEntry?["duration"] as! Double
  1128. } catch {
  1129. print("No Duration Found")
  1130. }
  1131. // This adds scheduled basal wherever there is a break between temps. can't check the prior ending on the first item. it is 24 hours old, so it isn't important for display anyway
  1132. if i > 0 {
  1133. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  1134. var priorBasalDate: String
  1135. if priorEntry?["timestamp"] != nil {
  1136. priorBasalDate = priorEntry?["timestamp"] as! String
  1137. } else if currentEntry?["created_at"] != nil {
  1138. priorBasalDate = priorEntry?["created_at"] as! String
  1139. } else {
  1140. continue
  1141. }
  1142. var priorStrippedZone = String(priorBasalDate.dropLast())
  1143. priorStrippedZone = priorStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1144. let priorDateFormatter = DateFormatter()
  1145. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1146. priorDateFormatter.locale = Locale(identifier: "en_US")
  1147. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1148. guard let priorDateString = dateFormatter.date(from: priorStrippedZone) else { continue }
  1149. let priorDateTimeStamp = priorDateString.timeIntervalSince1970
  1150. let priorDuration = priorEntry?["duration"] as! Double
  1151. // if difference between time stamps is greater than the duration of the last entry, there is a gap. Give a 15 second leeway on the timestamp
  1152. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  1153. var scheduled = 0.0
  1154. var midGap = false
  1155. var midGapTime: TimeInterval = 0
  1156. var midGapValue: Double = 0
  1157. // cycle through basal profiles.
  1158. // TODO figure out how to deal with profile changes that happen mid-gap
  1159. for b in 0..<self.basalScheduleData.count {
  1160. if (priorDateTimeStamp + (priorDuration * 60)) >= basalScheduleData[b].date {
  1161. scheduled = basalScheduleData[b].basalRate
  1162. // deal with mid-gap scheduled basal change
  1163. // don't do it on the last scheudled basal entry
  1164. if b < self.basalScheduleData.count - 1 {
  1165. if dateTimeStamp > self.basalScheduleData[b + 1].date {
  1166. // midGap = true
  1167. // TODO: finish this to handle mid-gap items without crashing from overlapping entries
  1168. midGapTime = self.basalScheduleData[b + 1].date
  1169. midGapValue = self.basalScheduleData[b + 1].basalRate
  1170. }
  1171. }
  1172. }
  1173. }
  1174. // Make the starting dot at the last ending dot
  1175. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  1176. basalData.append(startDot)
  1177. if midGap {
  1178. // Make the ending dot at the new scheduled basal
  1179. let endDot1 = basalGraphStruct(basalRate: scheduled, date: Double(midGapTime))
  1180. basalData.append(endDot1)
  1181. // Make the starting dot at the scheduled Time
  1182. let startDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(midGapTime))
  1183. basalData.append(startDot2)
  1184. // Make the ending dot at the new basal value
  1185. let endDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(dateTimeStamp))
  1186. basalData.append(endDot2)
  1187. } else {
  1188. // Make the ending dot at the new starting dot
  1189. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  1190. basalData.append(endDot)
  1191. }
  1192. }
  1193. }
  1194. // Make the starting dot
  1195. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  1196. basalData.append(startDot)
  1197. // Make the ending dot
  1198. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  1199. // duration is already set to 0 if there is no duration set on it.
  1200. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  1201. if i == tempArray.count - 1 && duration == 0.0 {
  1202. lastEndDot = dateTimeStamp + (30 * 60)
  1203. latestBasal = String(format:"%.2f", basalRate)
  1204. } else {
  1205. lastEndDot = dateTimeStamp + (duration * 60)
  1206. latestBasal = String(format:"%.2f", basalRate)
  1207. }
  1208. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  1209. if i < tempArray.count - 1 {
  1210. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  1211. var nextBasalDate: String
  1212. if nextEntry?["timestamp"] != nil {
  1213. nextBasalDate = nextEntry?["timestamp"] as! String
  1214. } else if currentEntry?["created_at"] != nil {
  1215. nextBasalDate = nextEntry?["created_at"] as! String
  1216. } else {
  1217. continue
  1218. }
  1219. var nextStrippedZone = String(nextBasalDate.dropLast())
  1220. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1221. let nextDateFormatter = DateFormatter()
  1222. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1223. nextDateFormatter.locale = Locale(identifier: "en_US")
  1224. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1225. guard let nextDateString = dateFormatter.date(from: nextStrippedZone) else { continue }
  1226. let nextDateTimeStamp = nextDateString.timeIntervalSince1970
  1227. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1228. lastEndDot = nextDateTimeStamp
  1229. }
  1230. }
  1231. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1232. basalData.append(endDot)
  1233. }
  1234. // If last basal was prior to right now, we need to create one last scheduled entry
  1235. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1236. var scheduled = 0.0
  1237. // cycle through basal profiles.
  1238. // TODO figure out how to deal with profile changes that happen mid-gap
  1239. for b in 0..<self.basalProfile.count {
  1240. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1241. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1242. // check the prior temp ending to the profile seconds from midnight
  1243. print("yesterday " + String(scheduleTimeYesterday))
  1244. print("today " + String(scheduleTimeToday))
  1245. if lastEndDot >= scheduleTimeToday {
  1246. scheduled = basalProfile[b].value
  1247. }
  1248. }
  1249. latestBasal = String(format:"%.2f", scheduled)
  1250. // Make the starting dot at the last ending dot
  1251. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1252. basalData.append(startDot)
  1253. // Make the ending dot 10 minutes after now
  1254. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1255. basalData.append(endDot)
  1256. }
  1257. tableData[2].value = latestBasal
  1258. infoTable.reloadData()
  1259. if UserDefaultsRepository.graphBasal.value {
  1260. updateBasalGraph()
  1261. }
  1262. infoTable.reloadData()
  1263. }
  1264. // NS Meal Bolus Response Processor
  1265. func processNSBolus(entries: [[String:AnyObject]]) {
  1266. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1267. // because it's a small array, we're going to destroy and reload every time.
  1268. bolusData.removeAll()
  1269. var lastFoundIndex = 0
  1270. for i in 0..<entries.count {
  1271. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1272. var bolusDate: String
  1273. if currentEntry?["timestamp"] != nil {
  1274. bolusDate = currentEntry?["timestamp"] as! String
  1275. } else if currentEntry?["created_at"] != nil {
  1276. bolusDate = currentEntry?["created_at"] as! String
  1277. } else {
  1278. continue
  1279. }
  1280. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1281. var strippedZone = String(bolusDate.dropLast())
  1282. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1283. let dateFormatter = DateFormatter()
  1284. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1285. dateFormatter.locale = Locale(identifier: "en_US")
  1286. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1287. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1288. let dateTimeStamp = dateString.timeIntervalSince1970
  1289. guard let bolus = currentEntry?["insulin"] as? Double else { continue }
  1290. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1291. lastFoundIndex = sgv.foundIndex
  1292. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1293. // Make the dot
  1294. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv + 20))
  1295. bolusData.append(dot)
  1296. }
  1297. }
  1298. if UserDefaultsRepository.graphBolus.value {
  1299. updateBolusGraph()
  1300. }
  1301. }
  1302. // NS Carb Bolus Response Processor
  1303. func processNSCarbs(entries: [[String:AnyObject]]) {
  1304. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1305. // because it's a small array, we're going to destroy and reload every time.
  1306. carbData.removeAll()
  1307. var lastFoundIndex = 0
  1308. var lastFoundBolus = 0
  1309. for i in 0..<entries.count {
  1310. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1311. var carbDate: String
  1312. if currentEntry?["timestamp"] != nil {
  1313. carbDate = currentEntry?["timestamp"] as! String
  1314. } else if currentEntry?["created_at"] != nil {
  1315. carbDate = currentEntry?["created_at"] as! String
  1316. } else {
  1317. continue
  1318. }
  1319. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1320. // Fix for FreeAPS milliseconds in timestamp
  1321. var strippedZone = String(carbDate.dropLast())
  1322. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1323. let dateFormatter = DateFormatter()
  1324. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1325. dateFormatter.locale = Locale(identifier: "en_US")
  1326. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1327. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1328. var dateTimeStamp = dateString.timeIntervalSince1970
  1329. guard let carbs = currentEntry?["carbs"] as? Double else {
  1330. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1331. continue
  1332. }
  1333. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1334. lastFoundIndex = sgv.foundIndex
  1335. var offset = -50
  1336. if sgv.sgv < Double(topBG - 100) {
  1337. let bolusTime = findNearestBolusbyTime(timeWithin: 300, needle: dateTimeStamp, haystack: bolusData, startingIndex: lastFoundBolus)
  1338. lastFoundBolus = bolusTime.foundIndex
  1339. if bolusTime.offset {
  1340. offset = 70
  1341. } else {
  1342. offset = 20
  1343. }
  1344. }
  1345. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1346. // Make the dot
  1347. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv + Double(offset)), absorptionTime: absorptionTime)
  1348. carbData.append(dot)
  1349. }
  1350. }
  1351. if UserDefaultsRepository.graphCarbs.value {
  1352. updateCarbGraph()
  1353. }
  1354. }
  1355. // NS Suspend Pump Response Processor
  1356. func processSuspendPump(entries: [[String:AnyObject]]) {
  1357. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Suspend Pump") }
  1358. // because it's a small array, we're going to destroy and reload every time.
  1359. suspendGraphData.removeAll()
  1360. var lastFoundIndex = 0
  1361. for i in 0..<entries.count {
  1362. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1363. var date: String
  1364. if currentEntry?["timestamp"] != nil {
  1365. date = currentEntry?["timestamp"] as! String
  1366. } else if currentEntry?["created_at"] != nil {
  1367. date = currentEntry?["created_at"] as! String
  1368. } else {
  1369. return
  1370. }
  1371. // Fix for FreeAPS milliseconds in timestamp
  1372. var strippedZone = String(date.dropLast())
  1373. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1374. let dateFormatter = DateFormatter()
  1375. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1376. dateFormatter.locale = Locale(identifier: "en_US")
  1377. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1378. let dateString = dateFormatter.date(from: strippedZone)
  1379. let dateTimeStamp = dateString!.timeIntervalSince1970
  1380. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1381. lastFoundIndex = sgv.foundIndex
  1382. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1383. // Make the dot
  1384. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1385. suspendGraphData.append(dot)
  1386. }
  1387. }
  1388. if UserDefaultsRepository.graphOtherTreatments.value {
  1389. updateSuspendGraph()
  1390. }
  1391. }
  1392. // NS Resume Pump Response Processor
  1393. func processResumePump(entries: [[String:AnyObject]]) {
  1394. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Resume Pump") }
  1395. // because it's a small array, we're going to destroy and reload every time.
  1396. resumeGraphData.removeAll()
  1397. var lastFoundIndex = 0
  1398. for i in 0..<entries.count {
  1399. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1400. var date: String
  1401. if currentEntry?["timestamp"] != nil {
  1402. date = currentEntry?["timestamp"] as! String
  1403. } else if currentEntry?["created_at"] != nil {
  1404. date = currentEntry?["created_at"] as! String
  1405. } else {
  1406. return
  1407. }
  1408. // Fix for FreeAPS milliseconds in timestamp
  1409. var strippedZone = String(date.dropLast())
  1410. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1411. let dateFormatter = DateFormatter()
  1412. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1413. dateFormatter.locale = Locale(identifier: "en_US")
  1414. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1415. let dateString = dateFormatter.date(from: strippedZone)
  1416. let dateTimeStamp = dateString!.timeIntervalSince1970
  1417. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1418. lastFoundIndex = sgv.foundIndex
  1419. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1420. // Make the dot
  1421. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1422. resumeGraphData.append(dot)
  1423. }
  1424. }
  1425. if UserDefaultsRepository.graphOtherTreatments.value {
  1426. updateResumeGraph()
  1427. }
  1428. }
  1429. // NS Sensor Start Response Processor
  1430. func processSensorStart(entries: [[String:AnyObject]]) {
  1431. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Sensor Start") }
  1432. // because it's a small array, we're going to destroy and reload every time.
  1433. sensorStartGraphData.removeAll()
  1434. var lastFoundIndex = 0
  1435. for i in 0..<entries.count {
  1436. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1437. var date: String
  1438. if currentEntry?["timestamp"] != nil {
  1439. date = currentEntry?["timestamp"] as! String
  1440. } else if currentEntry?["created_at"] != nil {
  1441. date = currentEntry?["created_at"] as! String
  1442. } else {
  1443. return
  1444. }
  1445. // Fix for FreeAPS milliseconds in timestamp
  1446. var strippedZone = String(date.dropLast())
  1447. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1448. let dateFormatter = DateFormatter()
  1449. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1450. dateFormatter.locale = Locale(identifier: "en_US")
  1451. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1452. let dateString = dateFormatter.date(from: strippedZone)
  1453. let dateTimeStamp = dateString!.timeIntervalSince1970
  1454. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1455. lastFoundIndex = sgv.foundIndex
  1456. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1457. // Make the dot
  1458. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1459. sensorStartGraphData.append(dot)
  1460. }
  1461. }
  1462. if UserDefaultsRepository.graphOtherTreatments.value {
  1463. updateSensorStart()
  1464. }
  1465. }
  1466. // NS Note Response Processor
  1467. func processNotes(entries: [[String:AnyObject]]) {
  1468. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Notes") }
  1469. // because it's a small array, we're going to destroy and reload every time.
  1470. noteGraphData.removeAll()
  1471. var lastFoundIndex = 0
  1472. for i in 0..<entries.count {
  1473. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1474. var date: String
  1475. if currentEntry?["timestamp"] != nil {
  1476. date = currentEntry?["timestamp"] as! String
  1477. } else if currentEntry?["created_at"] != nil {
  1478. date = currentEntry?["created_at"] as! String
  1479. } else {
  1480. return
  1481. }
  1482. // Fix for FreeAPS milliseconds in timestamp
  1483. var strippedZone = String(date.dropLast())
  1484. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1485. let dateFormatter = DateFormatter()
  1486. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1487. dateFormatter.locale = Locale(identifier: "en_US")
  1488. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1489. let dateString = dateFormatter.date(from: strippedZone)
  1490. let dateTimeStamp = dateString!.timeIntervalSince1970
  1491. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1492. lastFoundIndex = sgv.foundIndex
  1493. guard let thisNote = currentEntry?["notes"] as? String else { continue }
  1494. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1495. // Make the dot
  1496. let dot = DataStructs.noteStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv), note: thisNote)
  1497. noteGraphData.append(dot)
  1498. }
  1499. }
  1500. if UserDefaultsRepository.graphOtherTreatments.value {
  1501. updateNotes()
  1502. }
  1503. }
  1504. // NS BG Check Response Processor
  1505. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1506. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1507. // because it's a small array, we're going to destroy and reload every time.
  1508. bgCheckData.removeAll()
  1509. for i in 0..<entries.count {
  1510. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1511. var date: String
  1512. if currentEntry?["timestamp"] != nil {
  1513. date = currentEntry?["timestamp"] as! String
  1514. } else if currentEntry?["created_at"] != nil {
  1515. date = currentEntry?["created_at"] as! String
  1516. } else {
  1517. return
  1518. }
  1519. // Fix for FreeAPS milliseconds in timestamp
  1520. var strippedZone = String(date.dropLast())
  1521. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1522. let dateFormatter = DateFormatter()
  1523. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1524. dateFormatter.locale = Locale(identifier: "en_US")
  1525. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1526. let dateString = dateFormatter.date(from: strippedZone)
  1527. let dateTimeStamp = dateString!.timeIntervalSince1970
  1528. guard let sgv = currentEntry?["glucose"] as? Int else {
  1529. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1530. continue
  1531. }
  1532. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1533. // Make the dot
  1534. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1535. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1536. bgCheckData.append(dot)
  1537. }
  1538. }
  1539. if UserDefaultsRepository.graphOtherTreatments.value {
  1540. updateBGCheckGraph()
  1541. }
  1542. }
  1543. // NS Override Response Processor
  1544. func processNSOverrides(entries: [[String:AnyObject]]) {
  1545. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1546. // because it's a small array, we're going to destroy and reload every time.
  1547. overrideGraphData.removeAll()
  1548. for i in 0..<entries.count {
  1549. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1550. var date: String
  1551. if currentEntry?["timestamp"] != nil {
  1552. date = currentEntry?["timestamp"] as! String
  1553. } else if currentEntry?["created_at"] != nil {
  1554. date = currentEntry?["created_at"] as! String
  1555. } else {
  1556. return
  1557. }
  1558. // Fix for FreeAPS milliseconds in timestamp
  1559. var strippedZone = String(date.dropLast())
  1560. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1561. let dateFormatter = DateFormatter()
  1562. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1563. dateFormatter.locale = Locale(identifier: "en_US")
  1564. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1565. let dateString = dateFormatter.date(from: strippedZone)
  1566. var dateTimeStamp = dateString!.timeIntervalSince1970
  1567. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  1568. if dateTimeStamp < dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  1569. dateTimeStamp = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  1570. }
  1571. var multiplier: Double = 1.0
  1572. if currentEntry?["insulinNeedsScaleFactor"] != nil {
  1573. multiplier = currentEntry?["insulinNeedsScaleFactor"] as! Double
  1574. }
  1575. var duration: Double = 5.0
  1576. if let durationType = currentEntry?["durationType"] as? String {
  1577. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1578. } else {
  1579. duration = (currentEntry?["duration"] as? Double)!
  1580. duration = duration * 60
  1581. }
  1582. // Skip overrides that aren't 5 minutes long. This prevents overlapping that causes bars to not display.
  1583. if duration < 300 { continue }
  1584. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1585. guard let reason = currentEntry?["reason"] as? String else { continue }
  1586. var range: [Int] = []
  1587. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1588. if ranges.count == 2 {
  1589. guard let low = ranges[0] as? Int else { continue }
  1590. guard let high = ranges[1] as? Int else { continue }
  1591. range.append(low)
  1592. range.append(high)
  1593. }
  1594. }
  1595. let endDate = dateTimeStamp + (duration)
  1596. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multiplier, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1597. overrideGraphData.append(dot)
  1598. }
  1599. if UserDefaultsRepository.graphOtherTreatments.value {
  1600. updateOverrideGraph()
  1601. }
  1602. }
  1603. }