NightScout.swift 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  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. self.sendNotification(title: "BG Timer", body: "5 Minutes")
  182. // if the reading is overdue: 10:00-19:59, re-attempt every minute
  183. } else if secondsAgo >= (10 * 60) {
  184. self.startBGTimer(time: 60)
  185. print("##### started 1 minute bg timer")
  186. self.sendNotification(title: "BG Timer", body: "1 Minute")
  187. // if the reading is overdue: 7:00-9:59, re-attempt every 30 seconds
  188. } else if secondsAgo >= (7 * 60) {
  189. self.startBGTimer(time: 30)
  190. print("##### started 30 second bg timer")
  191. self.sendNotification(title: "BG Timer", body: "30 Seconds")
  192. // if the reading is overdue: 5:00-6:59 re-attempt every 10 seconds
  193. } else if secondsAgo >= (5 * 60) {
  194. self.startBGTimer(time: 10)
  195. print("##### started 10 second bg timer")
  196. self.sendNotification(title: "BG Timer", body: "10 Seconds")
  197. // We have a current reading. Set timer to 5:10 from last reading
  198. } else {
  199. self.startBGTimer(time: 310 - secondsAgo)
  200. let timerVal = 310 - secondsAgo
  201. print("##### started 5:10 bg timer: \(timerVal)")
  202. }
  203. }
  204. // 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
  205. if !onlyPullLastRecord {
  206. bgData.removeAll()
  207. } else if bgData[bgData.count - 1].date != pullDate {
  208. bgData.removeFirst()
  209. if data.count > 0 && UserDefaultsRepository.speakBG.value {
  210. speakBG(sgv: data[data.count - 1].sgv)
  211. }
  212. } else {
  213. if data.count > 0 {
  214. self.updateBadge(val: data[data.count - 1].sgv)
  215. }
  216. return
  217. }
  218. // 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.
  219. for i in 0..<data.count{
  220. var dateString = data[data.count - 1 - i].date
  221. if isNS {
  222. dateString = data[data.count - 1 - i].date / 1000
  223. dateString.round(FloatingPointRoundingRule.toNearestOrEven)
  224. }
  225. if dateString >= dateTimeUtils.getTimeInterval24HoursAgo() {
  226. let reading = ShareGlucoseData(sgv: data[data.count - 1 - i].sgv, date: dateString, direction: data[data.count - 1 - i].direction)
  227. bgData.append(reading)
  228. }
  229. }
  230. viewUpdateNSBG(isNS: isNS)
  231. }
  232. // NS BG Data Front end updater
  233. func viewUpdateNSBG (isNS: Bool) {
  234. DispatchQueue.main.async {
  235. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Display: BG") }
  236. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  237. let entries = self.bgData
  238. if entries.count > 0 {
  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. // TODO: remove testing feature to color code arrow based on NS vs Dex
  250. if isNS {
  251. self.serverText.text = "Nightscout"
  252. } else {
  253. self.serverText.text = "Dexcom"
  254. }
  255. self.BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  256. snoozer.BGLabel.text = bgUnits.toDisplayUnits(String(latestBG))
  257. self.setBGTextColor()
  258. if let directionBG = entries[latestEntryi].direction {
  259. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  260. snoozer.DirectionLabel.text = self.bgDirectionGraphic(directionBG)
  261. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  262. }
  263. else
  264. {
  265. self.DirectionText.text = ""
  266. snoozer.DirectionLabel.text = ""
  267. self.latestDirectionString = ""
  268. }
  269. if deltaBG < 0 {
  270. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  271. snoozer.DeltaLabel.text = bgUnits.toDisplayUnits(String(deltaBG))
  272. self.latestDeltaString = String(deltaBG)
  273. }
  274. else
  275. {
  276. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  277. snoozer.DeltaLabel.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  278. self.latestDeltaString = "+" + String(deltaBG)
  279. }
  280. self.updateBadge(val: latestBG)
  281. }
  282. else
  283. {
  284. return
  285. }
  286. self.updateBGGraph()
  287. self.updateStats()
  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. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  386. } else {
  387. tableData[5].value = "50+U"
  388. }
  389. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  390. let upbat = uploader["battery"] as! Double
  391. tableData[4].value = String(format:"%.0f", upbat) + "%"
  392. }
  393. }
  394. }
  395. // Loop
  396. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  397. //print("Loop: \(lastLoopRecord)")
  398. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  399. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  400. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  401. if let failure = lastLoopRecord["failureReason"] {
  402. LoopStatusLabel.text = "X"
  403. latestLoopStatusString = "X"
  404. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  405. } else {
  406. var wasEnacted = false
  407. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  408. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  409. wasEnacted = true
  410. if let lastTempBasal = enacted["rate"] as? Double {
  411. }
  412. }
  413. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  414. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  415. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  416. }
  417. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  418. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  419. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  420. }
  421. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  422. let prediction = predictdata["values"] as! [Int]
  423. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  424. PredictionLabel.textColor = UIColor.systemPurple
  425. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  426. predictionData.removeAll()
  427. var predictionTime = lastLoopTime
  428. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  429. var i = 0
  430. while i <= toLoad {
  431. if i < prediction.count {
  432. let prediction = ShareGlucoseData(sgv: prediction[i], date: predictionTime, direction: "flat")
  433. predictionData.append(prediction)
  434. predictionTime += 300
  435. }
  436. i += 1
  437. }
  438. }
  439. let predMin = prediction.min()
  440. let predMax = prediction.max()
  441. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  442. if UserDefaultsRepository.graphPrediction.value {
  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. // cycle through basal profiles.
  1058. // TODO figure out how to deal with profile changes that happen mid-gap
  1059. for b in 0..<self.basalProfile.count {
  1060. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1061. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1062. // check the prior temp ending to the profile seconds from midnight
  1063. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeYesterday {
  1064. scheduled = basalProfile[b].value
  1065. }
  1066. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeToday {
  1067. scheduled = basalProfile[b].value
  1068. }
  1069. // This will iterate through from midnight on and set it for the highest matching one.
  1070. }
  1071. // Make the starting dot at the last ending dot
  1072. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  1073. basalData.append(startDot)
  1074. //if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Basal: Scheduled " + String(scheduled) + " " + String(dateTimeStamp)) }
  1075. // Make the ending dot at the new starting dot
  1076. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  1077. basalData.append(endDot)
  1078. }
  1079. }
  1080. // Make the starting dot
  1081. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  1082. basalData.append(startDot)
  1083. // Make the ending dot
  1084. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  1085. // duration is already set to 0 if there is no duration set on it.
  1086. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  1087. if i == tempArray.count - 1 && duration == 0.0 {
  1088. lastEndDot = dateTimeStamp + (30 * 60)
  1089. latestBasal = String(format:"%.2f", basalRate)
  1090. } else {
  1091. lastEndDot = dateTimeStamp + (duration * 60)
  1092. latestBasal = String(format:"%.2f", basalRate)
  1093. }
  1094. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  1095. if i < tempArray.count - 1 {
  1096. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  1097. var nextBasalDate: String
  1098. if nextEntry?["timestamp"] != nil {
  1099. nextBasalDate = nextEntry?["timestamp"] as! String
  1100. } else if currentEntry?["created_at"] != nil {
  1101. nextBasalDate = nextEntry?["created_at"] as! String
  1102. } else {
  1103. continue
  1104. }
  1105. var nextStrippedZone = String(nextBasalDate.dropLast())
  1106. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1107. let nextDateFormatter = DateFormatter()
  1108. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1109. nextDateFormatter.locale = Locale(identifier: "en_US")
  1110. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1111. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  1112. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  1113. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1114. lastEndDot = nextDateTimeStamp
  1115. }
  1116. }
  1117. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1118. basalData.append(endDot)
  1119. }
  1120. // If last basal was prior to right now, we need to create one last scheduled entry
  1121. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1122. var scheduled = 0.0
  1123. // cycle through basal profiles.
  1124. // TODO figure out how to deal with profile changes that happen mid-gap
  1125. for b in 0..<self.basalProfile.count {
  1126. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1127. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1128. // check the prior temp ending to the profile seconds from midnight
  1129. print("yesterday " + String(scheduleTimeYesterday))
  1130. print("today " + String(scheduleTimeToday))
  1131. if lastEndDot >= scheduleTimeToday {
  1132. scheduled = basalProfile[b].value
  1133. }
  1134. }
  1135. latestBasal = String(format:"%.2f", scheduled)
  1136. // Make the starting dot at the last ending dot
  1137. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1138. basalData.append(startDot)
  1139. // Make the ending dot 10 minutes after now
  1140. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1141. basalData.append(endDot)
  1142. }
  1143. tableData[2].value = latestBasal
  1144. infoTable.reloadData()
  1145. if UserDefaultsRepository.graphBasal.value {
  1146. updateBasalGraph()
  1147. }
  1148. infoTable.reloadData()
  1149. }
  1150. // NS Meal Bolus Response Processor
  1151. func processNSBolus(entries: [[String:AnyObject]]) {
  1152. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1153. // because it's a small array, we're going to destroy and reload every time.
  1154. bolusData.removeAll()
  1155. var lastFoundIndex = 0
  1156. for i in 0..<entries.count {
  1157. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1158. var bolusDate: String
  1159. if currentEntry?["timestamp"] != nil {
  1160. bolusDate = currentEntry?["timestamp"] as! String
  1161. } else if currentEntry?["created_at"] != nil {
  1162. bolusDate = currentEntry?["created_at"] as! String
  1163. } else {
  1164. return
  1165. }
  1166. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1167. var strippedZone = String(bolusDate.dropLast())
  1168. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1169. let dateFormatter = DateFormatter()
  1170. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1171. dateFormatter.locale = Locale(identifier: "en_US")
  1172. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1173. let dateString = dateFormatter.date(from: strippedZone)
  1174. let dateTimeStamp = dateString!.timeIntervalSince1970
  1175. do {
  1176. let bolus = try currentEntry?["insulin"] as! Double
  1177. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1178. lastFoundIndex = sgv.foundIndex
  1179. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1180. // Make the dot
  1181. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv + 20))
  1182. bolusData.append(dot)
  1183. }
  1184. } catch {
  1185. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Bolus") }
  1186. }
  1187. }
  1188. if UserDefaultsRepository.graphBolus.value {
  1189. updateBolusGraph()
  1190. }
  1191. }
  1192. // NS Carb Bolus Response Processor
  1193. func processNSCarbs(entries: [[String:AnyObject]]) {
  1194. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1195. // because it's a small array, we're going to destroy and reload every time.
  1196. carbData.removeAll()
  1197. var lastFoundIndex = 0
  1198. var lastFoundBolus = 0
  1199. for i in 0..<entries.count {
  1200. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1201. var carbDate: String
  1202. if currentEntry?["timestamp"] != nil {
  1203. carbDate = currentEntry?["timestamp"] as! String
  1204. } else if currentEntry?["created_at"] != nil {
  1205. carbDate = currentEntry?["created_at"] as! String
  1206. } else {
  1207. return
  1208. }
  1209. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1210. // Fix for FreeAPS milliseconds in timestamp
  1211. var strippedZone = String(carbDate.dropLast())
  1212. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1213. let dateFormatter = DateFormatter()
  1214. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1215. dateFormatter.locale = Locale(identifier: "en_US")
  1216. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1217. let dateString = dateFormatter.date(from: strippedZone)
  1218. var dateTimeStamp = dateString!.timeIntervalSince1970
  1219. guard let carbs = currentEntry?["carbs"] as? Double else {
  1220. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1221. break
  1222. }
  1223. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1224. lastFoundIndex = sgv.foundIndex
  1225. var offset = -50
  1226. if sgv.sgv < Double(250) {
  1227. let bolusTime = findNearestBolusbyTime(timeWithin: 300, needle: dateTimeStamp, haystack: bolusData, startingIndex: lastFoundBolus)
  1228. lastFoundBolus = bolusTime.foundIndex
  1229. if bolusTime.offset {
  1230. offset = 70
  1231. } else {
  1232. offset = 20
  1233. }
  1234. }
  1235. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1236. // Make the dot
  1237. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv + Double(offset)), absorptionTime: absorptionTime)
  1238. carbData.append(dot)
  1239. }
  1240. }
  1241. if UserDefaultsRepository.graphCarbs.value {
  1242. updateCarbGraph()
  1243. }
  1244. }
  1245. // NS Suspend Pump Response Processor
  1246. func processSuspendPump(entries: [[String:AnyObject]]) {
  1247. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Suspend Pump") }
  1248. // because it's a small array, we're going to destroy and reload every time.
  1249. suspendGraphData.removeAll()
  1250. var lastFoundIndex = 0
  1251. for i in 0..<entries.count {
  1252. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1253. var date: String
  1254. if currentEntry?["timestamp"] != nil {
  1255. date = currentEntry?["timestamp"] as! String
  1256. } else if currentEntry?["created_at"] != nil {
  1257. date = currentEntry?["created_at"] as! String
  1258. } else {
  1259. return
  1260. }
  1261. // Fix for FreeAPS milliseconds in timestamp
  1262. var strippedZone = String(date.dropLast())
  1263. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1264. let dateFormatter = DateFormatter()
  1265. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1266. dateFormatter.locale = Locale(identifier: "en_US")
  1267. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1268. let dateString = dateFormatter.date(from: strippedZone)
  1269. let dateTimeStamp = dateString!.timeIntervalSince1970
  1270. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1271. lastFoundIndex = sgv.foundIndex
  1272. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1273. // Make the dot
  1274. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1275. suspendGraphData.append(dot)
  1276. }
  1277. }
  1278. updateSuspendGraph()
  1279. }
  1280. // NS Resume Pump Response Processor
  1281. func processResumePump(entries: [[String:AnyObject]]) {
  1282. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Resume Pump") }
  1283. // because it's a small array, we're going to destroy and reload every time.
  1284. resumeGraphData.removeAll()
  1285. var lastFoundIndex = 0
  1286. for i in 0..<entries.count {
  1287. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1288. var date: String
  1289. if currentEntry?["timestamp"] != nil {
  1290. date = currentEntry?["timestamp"] as! String
  1291. } else if currentEntry?["created_at"] != nil {
  1292. date = currentEntry?["created_at"] as! String
  1293. } else {
  1294. return
  1295. }
  1296. // Fix for FreeAPS milliseconds in timestamp
  1297. var strippedZone = String(date.dropLast())
  1298. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1299. let dateFormatter = DateFormatter()
  1300. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1301. dateFormatter.locale = Locale(identifier: "en_US")
  1302. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1303. let dateString = dateFormatter.date(from: strippedZone)
  1304. let dateTimeStamp = dateString!.timeIntervalSince1970
  1305. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1306. lastFoundIndex = sgv.foundIndex
  1307. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1308. // Make the dot
  1309. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1310. resumeGraphData.append(dot)
  1311. }
  1312. }
  1313. updateResumeGraph()
  1314. }
  1315. // NS Sensor Start Response Processor
  1316. func processSensorStart(entries: [[String:AnyObject]]) {
  1317. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Sensor Start") }
  1318. // because it's a small array, we're going to destroy and reload every time.
  1319. sensorStartGraphData.removeAll()
  1320. var lastFoundIndex = 0
  1321. for i in 0..<entries.count {
  1322. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1323. var date: String
  1324. if currentEntry?["timestamp"] != nil {
  1325. date = currentEntry?["timestamp"] as! String
  1326. } else if currentEntry?["created_at"] != nil {
  1327. date = currentEntry?["created_at"] as! String
  1328. } else {
  1329. return
  1330. }
  1331. // Fix for FreeAPS milliseconds in timestamp
  1332. var strippedZone = String(date.dropLast())
  1333. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1334. let dateFormatter = DateFormatter()
  1335. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1336. dateFormatter.locale = Locale(identifier: "en_US")
  1337. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1338. let dateString = dateFormatter.date(from: strippedZone)
  1339. let dateTimeStamp = dateString!.timeIntervalSince1970
  1340. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1341. lastFoundIndex = sgv.foundIndex
  1342. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1343. // Make the dot
  1344. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1345. sensorStartGraphData.append(dot)
  1346. }
  1347. }
  1348. updateSensorStart()
  1349. }
  1350. // NS Note Response Processor
  1351. func processNotes(entries: [[String:AnyObject]]) {
  1352. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Notes") }
  1353. // because it's a small array, we're going to destroy and reload every time.
  1354. noteGraphData.removeAll()
  1355. var lastFoundIndex = 0
  1356. for i in 0..<entries.count {
  1357. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1358. var date: String
  1359. if currentEntry?["timestamp"] != nil {
  1360. date = currentEntry?["timestamp"] as! String
  1361. } else if currentEntry?["created_at"] != nil {
  1362. date = currentEntry?["created_at"] as! String
  1363. } else {
  1364. return
  1365. }
  1366. // Fix for FreeAPS milliseconds in timestamp
  1367. var strippedZone = String(date.dropLast())
  1368. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1369. let dateFormatter = DateFormatter()
  1370. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1371. dateFormatter.locale = Locale(identifier: "en_US")
  1372. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1373. let dateString = dateFormatter.date(from: strippedZone)
  1374. let dateTimeStamp = dateString!.timeIntervalSince1970
  1375. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1376. lastFoundIndex = sgv.foundIndex
  1377. guard let thisNote = currentEntry?["notes"] as? String else { continue }
  1378. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1379. // Make the dot
  1380. let dot = DataStructs.noteStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv), note: thisNote)
  1381. noteGraphData.append(dot)
  1382. }
  1383. }
  1384. updateNotes()
  1385. }
  1386. // NS BG Check Response Processor
  1387. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1388. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1389. // because it's a small array, we're going to destroy and reload every time.
  1390. bgCheckData.removeAll()
  1391. for i in 0..<entries.count {
  1392. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1393. var date: String
  1394. if currentEntry?["timestamp"] != nil {
  1395. date = currentEntry?["timestamp"] as! String
  1396. } else if currentEntry?["created_at"] != nil {
  1397. date = currentEntry?["created_at"] as! String
  1398. } else {
  1399. return
  1400. }
  1401. // Fix for FreeAPS milliseconds in timestamp
  1402. var strippedZone = String(date.dropLast())
  1403. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1404. let dateFormatter = DateFormatter()
  1405. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1406. dateFormatter.locale = Locale(identifier: "en_US")
  1407. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1408. let dateString = dateFormatter.date(from: strippedZone)
  1409. let dateTimeStamp = dateString!.timeIntervalSince1970
  1410. guard let sgv = currentEntry?["glucose"] as? Int else {
  1411. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1412. continue
  1413. }
  1414. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1415. // Make the dot
  1416. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1417. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1418. bgCheckData.append(dot)
  1419. }
  1420. }
  1421. if UserDefaultsRepository.graphCarbs.value {
  1422. updateBGCheckGraph()
  1423. }
  1424. }
  1425. // NS Override Response Processor
  1426. func processNSOverrides(entries: [[String:AnyObject]]) {
  1427. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1428. // because it's a small array, we're going to destroy and reload every time.
  1429. overrideGraphData.removeAll()
  1430. for i in 0..<entries.count {
  1431. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1432. var date: String
  1433. if currentEntry?["timestamp"] != nil {
  1434. date = currentEntry?["timestamp"] as! String
  1435. } else if currentEntry?["created_at"] != nil {
  1436. date = currentEntry?["created_at"] as! String
  1437. } else {
  1438. return
  1439. }
  1440. // Fix for FreeAPS milliseconds in timestamp
  1441. var strippedZone = String(date.dropLast())
  1442. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1443. let dateFormatter = DateFormatter()
  1444. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1445. dateFormatter.locale = Locale(identifier: "en_US")
  1446. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1447. let dateString = dateFormatter.date(from: strippedZone)
  1448. var dateTimeStamp = dateString!.timeIntervalSince1970
  1449. if dateTimeStamp < dateTimeUtils.getTimeInterval24HoursAgo() {
  1450. dateTimeStamp = dateTimeUtils.getTimeInterval24HoursAgo()
  1451. }
  1452. var multiplier: Double = 1.0
  1453. if currentEntry?["insulinNeedsScaleFactor"] != nil {
  1454. multiplier = currentEntry?["insulinNeedsScaleFactor"] as! Double
  1455. }
  1456. var duration: Double = 5.0
  1457. if let durationType = currentEntry?["durationType"] as? String {
  1458. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1459. } else {
  1460. duration = (currentEntry?["duration"] as? Double)!
  1461. duration = duration * 60
  1462. }
  1463. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1464. guard let reason = currentEntry?["reason"] as? String else { continue }
  1465. var range: [Int] = []
  1466. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1467. if ranges.count == 2 {
  1468. guard let low = ranges[0] as? Int else { continue }
  1469. guard let high = ranges[1] as? Int else { continue }
  1470. range.append(low)
  1471. range.append(high)
  1472. }
  1473. }
  1474. let endDate = dateTimeStamp + (duration)
  1475. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multiplier, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1476. overrideGraphData.append(dot)
  1477. }
  1478. updateOverrideGraph()
  1479. }
  1480. }