NightScout.swift 77 KB

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