NightScout.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. //
  12. // //NS BG Struct
  13. // struct sgvData: Codable {
  14. // var sgv: Int
  15. // var date: TimeInterval
  16. // var direction: String?
  17. // }
  18. //NS Cage Struct
  19. struct cageData: Codable {
  20. var created_at: String
  21. }
  22. //NS Basal Profile Struct
  23. struct basalProfileStruct: Codable {
  24. var value: Double
  25. var time: String
  26. var timeAsSeconds: Double
  27. }
  28. //NS Basal Data Struct
  29. struct basalGraphStruct: Codable {
  30. var basalRate: Double
  31. var date: TimeInterval
  32. }
  33. //NS Bolus Data Struct
  34. struct bolusCarbGraphStruct: Codable {
  35. var value: Double
  36. var date: TimeInterval
  37. var sgv: Int
  38. }
  39. // Main loader for all data
  40. func nightscoutLoader(forceLoad: Bool = false) {
  41. var needsLoaded: Bool = false
  42. var staleData: Bool = false
  43. var onlyPullLastRecord = false
  44. // If we have existing data and it's within 5 minutes, we aren't going to do a BG network call
  45. // if we have stale BG data 10 min or older, we're only going to attempt to pull BG and Loop status
  46. // to not have a full refresh every 15 seconds. The remaining data will start pulling again on the
  47. // next BG reading that comes in.
  48. if bgData.count > 0 {
  49. let now = NSDate().timeIntervalSince1970
  50. let lastReadingTime = bgData[bgData.count - 1].date
  51. let secondsAgo = now - lastReadingTime
  52. if secondsAgo >= 5*60 {
  53. needsLoaded = true
  54. if secondsAgo < 10*60 {
  55. onlyPullLastRecord = true
  56. } else {
  57. staleData = true
  58. }
  59. }
  60. } else {
  61. needsLoaded = true
  62. }
  63. if forceLoad { needsLoaded = true}
  64. // Only update if we don't have a current reading or forced to load
  65. if needsLoaded {
  66. self.clearLastInfoData()
  67. webLoadNSDeviceStatus()
  68. webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  69. if !staleData {
  70. webLoadNSProfile()
  71. if UserDefaultsRepository.downloadBasal.value {
  72. WebLoadNSTempBasals()
  73. }
  74. if UserDefaultsRepository.downloadBolus.value {
  75. webLoadNSBoluses()
  76. }
  77. if UserDefaultsRepository.downloadCarbs.value {
  78. webLoadNSCarbs()
  79. }
  80. webLoadNSCage()
  81. webLoadNSSage()
  82. }
  83. // Give the alarms and calendar 15 seconds delay to allow time for data to compile
  84. print("Start View Timer")
  85. self.startViewTimer(time: viewTimeInterval)
  86. } else {
  87. // Things to do if we already have data and don't need a network call
  88. // Leaving all downloads off for right now.
  89. /*
  90. webLoadNSDeviceStatus()
  91. if UserDefaultsRepository.downloadBolus.value {
  92. webLoadNSBoluses()
  93. }
  94. if UserDefaultsRepository.downloadCarbs.value {
  95. webLoadNSCarbs()
  96. }*/
  97. if bgData.count > 0 {
  98. self.checkAlarms(bgs: bgData)
  99. }
  100. }
  101. }
  102. // NS BG Data Web call
  103. func webLoadNSBGData(onlyPullLastRecord: Bool = false) {
  104. print("Enter BG Web Call")
  105. // Set the count= in the url either to pull 24 hours or only the last record
  106. var points = "1"
  107. if !onlyPullLastRecord {
  108. points = String(self.graphHours * 12 + 1)
  109. }
  110. // URL processor
  111. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  112. if token == "" {
  113. urlBGDataPath = urlBGDataPath + "count=" + points
  114. } else {
  115. urlBGDataPath = urlBGDataPath + "token=" + token + "&count=" + points
  116. }
  117. guard let urlBGData = URL(string: urlBGDataPath) else {
  118. return
  119. }
  120. var request = URLRequest(url: urlBGData)
  121. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  122. // Downloader
  123. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  124. if self.consoleLogging == true {print("start bg url")}
  125. guard error == nil else {
  126. return
  127. }
  128. guard let data = data else {
  129. return
  130. }
  131. let decoder = JSONDecoder()
  132. let entriesResponse = try? decoder.decode([DataStructs.sgvData].self, from: data)
  133. if let entriesResponse = entriesResponse {
  134. DispatchQueue.main.async {
  135. // trigger the processor for the data after downloading.
  136. self.ProcessNSBGData(data: entriesResponse, onlyPullLastRecord: onlyPullLastRecord)
  137. }
  138. } else {
  139. return
  140. }
  141. }
  142. getBGTask.resume()
  143. }
  144. // NS BG Data Response processor
  145. func ProcessNSBGData(data: [DataStructs.sgvData], onlyPullLastRecord: Bool){
  146. print("Enter BG Processor")
  147. var pullDate = data[data.count - 1].date / 1000
  148. pullDate.round(FloatingPointRoundingRule.toNearestOrEven)
  149. // 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
  150. if !onlyPullLastRecord {
  151. bgData.removeAll()
  152. } else if bgData[bgData.count - 1].date != pullDate {
  153. bgData.removeFirst()
  154. if data.count > 0 && UserDefaultsRepository.speakBG.value {
  155. speakBG(sgv: data[data.count - 1].sgv)
  156. }
  157. } else {
  158. if data.count > 0 {
  159. self.updateBadge(val: data[data.count - 1].sgv)
  160. }
  161. // self.viewUpdateNSBG()
  162. return
  163. }
  164. // 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.
  165. for i in 0..<data.count{
  166. var dateString = data[data.count - 1 - i].date / 1000
  167. dateString.round(FloatingPointRoundingRule.toNearestOrEven)
  168. let reading = DataStructs.sgvData(sgv: data[data.count - 1 - i].sgv, date: dateString, direction: data[data.count - 1 - i].direction)
  169. bgData.append(reading)
  170. }
  171. viewUpdateNSBG()
  172. }
  173. // NS BG Data Front end updater
  174. func viewUpdateNSBG () {
  175. print("Enter BG View Update")
  176. let entries = bgData
  177. if entries.count > 0 {
  178. let latestEntryi = entries.count - 1
  179. let latestBG = entries[latestEntryi].sgv
  180. let priorBG = entries[latestEntryi - 1].sgv
  181. let deltaBG = latestBG - priorBG as Int
  182. let lastBGTime = entries[latestEntryi].date
  183. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  184. var userUnit = " mg/dL"
  185. if mmol {
  186. userUnit = " mmol/L"
  187. }
  188. BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  189. setBGTextColor()
  190. if let directionBG = entries[latestEntryi].direction {
  191. DirectionText.text = bgDirectionGraphic(directionBG)
  192. latestDirectionString = bgDirectionGraphic(directionBG)
  193. }
  194. else
  195. {
  196. DirectionText.text = ""
  197. latestDirectionString = ""
  198. }
  199. if deltaBG < 0 {
  200. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  201. latestDeltaString = String(deltaBG)
  202. }
  203. else
  204. {
  205. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  206. latestDeltaString = "+" + String(deltaBG)
  207. }
  208. self.updateBadge(val: latestBG)
  209. }
  210. else
  211. {
  212. return
  213. }
  214. updateBGGraph()
  215. updateMinAgo()
  216. updateStats()
  217. }
  218. // NS Device Status Web Call
  219. func webLoadNSDeviceStatus() {
  220. print("Enter download device status")
  221. let urlUser = UserDefaultsRepository.url.value
  222. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=1"
  223. if token != "" {
  224. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?token=" + token + "&count=1"
  225. }
  226. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  227. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  228. return
  229. }
  230. if consoleLogging == true {print("entered device status task.")}
  231. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  232. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  233. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  234. if self.consoleLogging == true {print("in device status loop.")}
  235. guard error == nil else {
  236. return
  237. }
  238. guard let data = data else {
  239. return
  240. }
  241. let json = try? (JSONSerialization.jsonObject(with: data) as! [[String:AnyObject]])
  242. if let json = json {
  243. DispatchQueue.main.async {
  244. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  245. }
  246. } else {
  247. return
  248. }
  249. if self.consoleLogging == true {print("finish pump update")}}
  250. deviceStatusTask.resume()
  251. }
  252. // NS Device Status Response Processor
  253. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  254. print("Enter process device status")
  255. if consoleLogging == true {print("in updatePump")}
  256. if jsonDeviceStatus.count == 0 {
  257. return
  258. }
  259. //only grabbing one record since ns sorts by {created_at : -1}
  260. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  261. //pump and uploader
  262. let formatter = ISO8601DateFormatter()
  263. formatter.formatOptions = [.withFullDate,
  264. .withTime,
  265. .withDashSeparatorInDate,
  266. .withColonSeparatorInTime]
  267. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  268. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  269. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  270. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  271. } else {
  272. tableData[5].value = "50+U"
  273. }
  274. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  275. let upbat = uploader["battery"] as! Double
  276. tableData[4].value = String(format:"%.0f", upbat) + "%"
  277. }
  278. }
  279. }
  280. // Loop
  281. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  282. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  283. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  284. if let failure = lastLoopRecord["failureReason"] {
  285. LoopStatusLabel.text = "X"
  286. latestLoopStatusString = "X"
  287. } else {
  288. var wasEnacted = false
  289. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  290. wasEnacted = true
  291. if let lastTempBasal = enacted["rate"] as? Double {
  292. // tableData[2].value = String(format:"%.1f", lastTempBasal)
  293. }
  294. }
  295. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  296. tableData[0].value = String(format:"%.1f", (iobdata["iob"] as! Double))
  297. latestIOB = String(format:"%.1f", (iobdata["iob"] as! Double))
  298. }
  299. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  300. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  301. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  302. }
  303. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  304. let prediction = predictdata["values"] as! [Double]
  305. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  306. PredictionLabel.textColor = UIColor.systemPurple
  307. predictionData.removeAll()
  308. if UserDefaultsRepository.downloadPrediction.value {
  309. var i = 1
  310. while i <= 12 {
  311. predictionData.append(prediction[i])
  312. i += 1
  313. }
  314. }
  315. }
  316. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  317. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  318. var lastBGTime = lastLoopTime
  319. if bgData.count > 0 {
  320. lastBGTime = bgData[bgData.count - 1].date
  321. }
  322. if tempBasalTime > lastBGTime && !wasEnacted {
  323. LoopStatusLabel.text = "⏀"
  324. latestLoopStatusString = "⏀"
  325. } else {
  326. LoopStatusLabel.text = "↻"
  327. latestLoopStatusString = "↻"
  328. }
  329. }
  330. } else {
  331. LoopStatusLabel.text = "↻"
  332. latestLoopStatusString = "↻"
  333. }
  334. }
  335. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  336. LoopStatusLabel.text = "⚠"
  337. latestLoopStatusString = "⚠"
  338. }
  339. } // end lastLoopTime
  340. } // end lastLoop Record
  341. var oText = "" as String
  342. currentOverride = 1.0
  343. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  344. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  345. }
  346. if lastOverride["active"] as! Bool {
  347. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  348. if let multiplier = lastOverride["multiplier"] as? Double {
  349. currentOverride = multiplier
  350. oText += String(format:"%.1f", multiplier*100)
  351. }
  352. else
  353. {
  354. oText += String(format:"%.1f", 100)
  355. }
  356. oText += "% ("
  357. let minValue = lastCorrection["minValue"] as! Double
  358. let maxValue = lastCorrection["maxValue"] as! Double
  359. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  360. tableData[3].value = oText
  361. }
  362. }
  363. infoTable.reloadData()
  364. }
  365. // NS Cage Web Call
  366. func webLoadNSCage() {
  367. print("enter download cage")
  368. let urlUser = UserDefaultsRepository.url.value
  369. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  370. if token != "" {
  371. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  372. }
  373. guard let urlData = URL(string: urlString) else {
  374. return
  375. }
  376. var request = URLRequest(url: urlData)
  377. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  378. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  379. if self.consoleLogging == true {print("start cage url")}
  380. guard error == nil else {
  381. return
  382. }
  383. guard let data = data else {
  384. return
  385. }
  386. let decoder = JSONDecoder()
  387. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  388. if let entriesResponse = entriesResponse {
  389. DispatchQueue.main.async {
  390. self.updateCage(data: entriesResponse)
  391. }
  392. } else {
  393. return
  394. }
  395. }
  396. task.resume()
  397. }
  398. // NS Cage Response Processor
  399. func updateCage(data: [cageData]) {
  400. print("enter process cage")
  401. if consoleLogging == true {print("in updateCage")}
  402. if data.count == 0 {
  403. return
  404. }
  405. let lastCageString = data[0].created_at
  406. let formatter = ISO8601DateFormatter()
  407. formatter.formatOptions = [.withFullDate,
  408. .withTime,
  409. .withDashSeparatorInDate,
  410. .withColonSeparatorInTime]
  411. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  412. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  413. let now = NSDate().timeIntervalSince1970
  414. let secondsAgo = now - cageTime
  415. //let days = 24 * 60 * 60
  416. let formatter = DateComponentsFormatter()
  417. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  418. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  419. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  420. let formattedDuration = formatter.string(from: secondsAgo)
  421. tableData[7].value = formattedDuration ?? ""
  422. }
  423. infoTable.reloadData()
  424. }
  425. // NS Sage Web Call
  426. func webLoadNSSage() {
  427. print("enter download sage")
  428. var dayComponent = DateComponents()
  429. dayComponent.day = -10 // For removing 10 days
  430. let theCalendar = Calendar.current
  431. let startDate = theCalendar.date(byAdding: dayComponent, to: Date())!
  432. let dateFormatter = DateFormatter()
  433. dateFormatter.dateFormat = "yyyy-MM-dd"
  434. var startDateString = dateFormatter.string(from: startDate)
  435. let urlUser = UserDefaultsRepository.url.value
  436. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=2020-05-31&count=1"
  437. if token != "" {
  438. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=2020-05-31&count=1"
  439. }
  440. guard let urlData = URL(string: urlString) else {
  441. return
  442. }
  443. var request = URLRequest(url: urlData)
  444. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  445. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  446. if self.consoleLogging == true {print("start cage url")}
  447. guard error == nil else {
  448. return
  449. }
  450. guard let data = data else {
  451. return
  452. }
  453. let decoder = JSONDecoder()
  454. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  455. if let entriesResponse = entriesResponse {
  456. DispatchQueue.main.async {
  457. self.updateSage(data: entriesResponse)
  458. }
  459. } else {
  460. return
  461. }
  462. }
  463. task.resume()
  464. }
  465. // NS Sage Response Processor
  466. func updateSage(data: [cageData]) {
  467. print("enter update sage")
  468. if consoleLogging == true {print("in updateSage")}
  469. if data.count == 0 {
  470. return
  471. }
  472. var lastSageString = data[0].created_at
  473. let formatter = ISO8601DateFormatter()
  474. formatter.formatOptions = [.withFullDate,
  475. .withTime,
  476. .withDashSeparatorInDate,
  477. .withColonSeparatorInTime]
  478. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  479. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  480. let now = NSDate().timeIntervalSince1970
  481. let secondsAgo = now - sageTime
  482. let days = 24 * 60 * 60
  483. let formatter = DateComponentsFormatter()
  484. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  485. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  486. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  487. let formattedDuration = formatter.string(from: secondsAgo)
  488. tableData[6].value = formattedDuration ?? ""
  489. }
  490. infoTable.reloadData()
  491. }
  492. // NS Profile Web Call
  493. func webLoadNSProfile() {
  494. print("enter download profile")
  495. let urlString = UserDefaultsRepository.url.value + "/api/v1/profile/current.json"
  496. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  497. guard let url = URL(string: escapedAddress!) else {
  498. return
  499. }
  500. var request = URLRequest(url: url)
  501. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  502. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  503. guard error == nil else {
  504. return
  505. }
  506. guard let data = data else {
  507. return
  508. }
  509. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  510. if let json = json {
  511. DispatchQueue.main.async {
  512. self.updateProfile(jsonDeviceStatus: json)
  513. }
  514. } else {
  515. return
  516. }
  517. }
  518. task.resume()
  519. }
  520. // NS Profile Response Processor
  521. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  522. print("enter process profile")
  523. if jsonDeviceStatus.count == 0 {
  524. return
  525. }
  526. let basal = jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  527. for i in 0..<basal.count {
  528. let dict = basal[i] as! Dictionary<String, Any>
  529. do {
  530. let thisValue = try dict[keyPath: "value"] as! Double
  531. let thisTime = dict[keyPath: "time"] as! String
  532. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  533. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  534. basalProfile.append(entry)
  535. } catch {
  536. print("Error Catch: Profile wrapped in Quotes")
  537. }
  538. }
  539. }
  540. // NS Temp Basal Web Call
  541. func WebLoadNSTempBasals() {
  542. print("enter download basals")
  543. if !UserDefaultsRepository.downloadBasal.value { return }
  544. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  545. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  546. if token != "" {
  547. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  548. }
  549. guard let urlData = URL(string: urlString) else {
  550. return
  551. }
  552. var request = URLRequest(url: urlData)
  553. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  554. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  555. guard error == nil else {
  556. return
  557. }
  558. guard let data = data else {
  559. return
  560. }
  561. let json = try? (JSONSerialization.jsonObject(with: data) as! [[String:AnyObject]])
  562. if let json = json {
  563. DispatchQueue.main.async {
  564. self.updateBasals(entries: json)
  565. }
  566. } else {
  567. return
  568. }
  569. }
  570. task.resume()
  571. }
  572. // NS Temp Basal Response Processor
  573. func updateBasals(entries: [[String:AnyObject]]) {
  574. print("enter process basal")
  575. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  576. basalData.removeAll()
  577. var lastEndDot = 0.0
  578. var tempArray: [basalGraphStruct] = []
  579. for i in 0..<entries.count {
  580. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  581. let basalDate = currentEntry?["timestamp"] as! String
  582. let strippedZone = String(basalDate.dropLast())
  583. let dateFormatter = DateFormatter()
  584. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  585. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  586. let dateString = dateFormatter.date(from: strippedZone)
  587. let dateTimeStamp = dateString!.timeIntervalSince1970
  588. let basalRate = currentEntry?["absolute"] as! Double
  589. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  590. // Setting end dots
  591. var duration = 0.0
  592. // For all except the last we're going to use stored duration for end dot. For last we'll just put it 5 mintues after the entry
  593. if i <= entries.count - 1 {
  594. duration = currentEntry?["duration"] as! Double
  595. } else {
  596. duration = dateTimeStamp + 60
  597. }
  598. // 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
  599. if i > 0 {
  600. let priorEntry = entries[entries.count - i] as [String : AnyObject]?
  601. let priorBasalDate = priorEntry?["timestamp"] as! String
  602. let priorStrippedZone = String(priorBasalDate.dropLast())
  603. let priorDateFormatter = DateFormatter()
  604. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  605. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  606. let priorDateString = dateFormatter.date(from: priorStrippedZone)
  607. let priorDateTimeStamp = priorDateString!.timeIntervalSince1970
  608. let priorDuration = priorEntry?["duration"] as! Double
  609. // if difference between time stamps is greater than the duration of the last entry, there is a gap
  610. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( priorDuration * 60 ) {
  611. var scheduled = 0.0
  612. // cycle through basal profiles.
  613. // TODO figure out how to deal with profile changes that happen mid-gap
  614. for b in 0..<self.basalProfile.count {
  615. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  616. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  617. // check the prior temp ending to the profile seconds from midnight
  618. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeYesterday {
  619. scheduled = basalProfile[b].value
  620. }
  621. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeToday {
  622. scheduled = basalProfile[b].value
  623. }
  624. // This will iterate through from midnight on and set it for the highest matching one.
  625. }
  626. // Make the starting dot at the last ending dot
  627. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  628. basalData.append(startDot)
  629. // Make the ending dot at the new starting dot
  630. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  631. basalData.append(endDot)
  632. }
  633. }
  634. // Make the starting dot
  635. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  636. basalData.append(startDot)
  637. // Make the ending dot
  638. // If it's the last one and not ended yet, extend it for 1 hour to match the prediction length. Otherwise let it end
  639. if i == entries.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  640. lastEndDot = Date().timeIntervalSince1970 + (55 * 60)
  641. tableData[2].value = String(format:"%.1f", basalRate)
  642. latestBasal = String(format:"%.1f", basalRate)
  643. } else {
  644. lastEndDot = dateTimeStamp + (duration * 60)
  645. }
  646. // Double check for overlaps of incorrect ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  647. if i < entries.count - 1 {
  648. let nextEntry = entries[entries.count - 2 - i] as [String : AnyObject]?
  649. let nextBasalDate = nextEntry?["timestamp"] as! String
  650. let nextStrippedZone = String(nextBasalDate.dropLast())
  651. let nextDateFormatter = DateFormatter()
  652. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  653. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  654. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  655. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  656. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  657. lastEndDot = nextDateTimeStamp
  658. }
  659. }
  660. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  661. basalData.append(endDot)
  662. }
  663. // If last scheduled basal was prior to right now, we need to create one last scheduled entry
  664. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  665. var scheduled = 0.0
  666. // cycle through basal profiles.
  667. // TODO figure out how to deal with profile changes that happen mid-gap
  668. for b in 0..<self.basalProfile.count {
  669. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  670. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  671. // check the prior temp ending to the profile seconds from midnight
  672. if lastEndDot >= scheduleTimeYesterday {
  673. scheduled = basalProfile[b].value
  674. }
  675. if lastEndDot >= scheduleTimeToday {
  676. scheduled = basalProfile[b].value
  677. }
  678. }
  679. tableData[2].value = String(format:"%.1f", scheduled)
  680. latestBasal = String(format:"%.1f", scheduled)
  681. // Make the starting dot at the last ending dot
  682. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  683. basalData.append(startDot)
  684. // Make the ending dot 1 hour after now
  685. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970))
  686. basalData.append(endDot)
  687. }
  688. if UserDefaultsRepository.graphBasal.value {
  689. updateBasalGraph()
  690. }
  691. }
  692. // NS Bolus Web Call
  693. func webLoadNSBoluses(){
  694. print("enter download bolus")
  695. if !UserDefaultsRepository.downloadBolus.value { return }
  696. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  697. let urlUser = UserDefaultsRepository.url.value
  698. var searchString = "find[eventType]=Correction%20Bolus&find[created_at][$gte]=" + yesterdayString
  699. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  700. if token == "" {
  701. urlDataPath = urlDataPath + searchString
  702. }
  703. else
  704. {
  705. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  706. }
  707. guard let urlData = URL(string: urlDataPath) else {
  708. return
  709. }
  710. var request = URLRequest(url: urlData)
  711. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  712. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  713. guard error == nil else {
  714. return
  715. }
  716. guard let data = data else {
  717. return
  718. }
  719. let json = try? (JSONSerialization.jsonObject(with: data) as! [[String:AnyObject]])
  720. if let json = json {
  721. DispatchQueue.main.async {
  722. self.processNSBolus(entries: json)
  723. }
  724. } else {
  725. return
  726. }
  727. }
  728. task.resume()
  729. }
  730. // NS Meal Bolus Response Processor
  731. func processNSBolus(entries: [[String:AnyObject]]) {
  732. print("enter process bolus")
  733. // because it's a small array, we're going to destroy and reload every time.
  734. bolusData.removeAll()
  735. var lastFoundIndex = 0
  736. for i in 0..<entries.count {
  737. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  738. let bolusDate = currentEntry?["timestamp"] as! String
  739. let strippedZone = String(bolusDate.dropLast())
  740. let dateFormatter = DateFormatter()
  741. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  742. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  743. let dateString = dateFormatter.date(from: strippedZone)
  744. let dateTimeStamp = dateString!.timeIntervalSince1970
  745. let bolus = currentEntry?["insulin"] as! Double
  746. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  747. lastFoundIndex = sgv.foundIndex
  748. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  749. // Make the dot
  750. let dot = bolusCarbGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  751. bolusData.append(dot)
  752. }
  753. }
  754. if UserDefaultsRepository.graphBolus.value {
  755. updateBolusGraph()
  756. }
  757. }
  758. // NS Carb Web Call
  759. func webLoadNSCarbs(){
  760. print("enter download carbs")
  761. if !UserDefaultsRepository.downloadCarbs.value { return }
  762. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  763. let urlUser = UserDefaultsRepository.url.value
  764. var searchString = "find[eventType]=Meal%20Bolus&find[created_at][$gte]=" + yesterdayString
  765. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  766. if token == "" {
  767. urlDataPath = urlDataPath + searchString
  768. }
  769. else
  770. {
  771. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  772. }
  773. guard let urlData = URL(string: urlDataPath) else {
  774. return
  775. }
  776. var request = URLRequest(url: urlData)
  777. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  778. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  779. guard error == nil else {
  780. return
  781. }
  782. guard let data = data else {
  783. return
  784. }
  785. let json = try? (JSONSerialization.jsonObject(with: data) as! [[String:AnyObject]])
  786. if let json = json {
  787. DispatchQueue.main.async {
  788. self.processNSCarbs(entries: json)
  789. }
  790. } else {
  791. return
  792. }
  793. }
  794. task.resume()
  795. }
  796. // NS Carb Bolus Response Processor
  797. func processNSCarbs(entries: [[String:AnyObject]]) {
  798. print("enter process carbs")
  799. // because it's a small array, we're going to destroy and reload every time.
  800. carbData.removeAll()
  801. var lastFoundIndex = 0
  802. for i in 0..<entries.count {
  803. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  804. let bolusDate = currentEntry?["timestamp"] as! String
  805. let strippedZone = String(bolusDate.dropLast())
  806. let dateFormatter = DateFormatter()
  807. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  808. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  809. let dateString = dateFormatter.date(from: strippedZone)
  810. let dateTimeStamp = dateString!.timeIntervalSince1970
  811. let carbs = currentEntry?["carbs"] as! Double
  812. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  813. lastFoundIndex = sgv.foundIndex
  814. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  815. // Make the dot
  816. let dot = bolusCarbGraphStruct(value: carbs, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  817. carbData.append(dot)
  818. }
  819. }
  820. if UserDefaultsRepository.graphCarbs.value {
  821. updateCarbGraph()
  822. }
  823. }
  824. }