NightScout.swift 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  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. let predMin = prediction.min()
  439. let predMax = prediction.max()
  440. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  441. updatePredictionGraph()
  442. }
  443. }
  444. if let recBolus = lastLoopRecord["recommendedBolus"] as? Double {
  445. tableData[8].value = String(format:"%.2fU", recBolus)
  446. }
  447. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  448. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  449. var lastBGTime = lastLoopTime
  450. if bgData.count > 0 {
  451. lastBGTime = bgData[bgData.count - 1].date
  452. }
  453. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  454. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  455. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  456. if tempBasalTime > lastBGTime && !wasEnacted {
  457. LoopStatusLabel.text = "⏀"
  458. latestLoopStatusString = "⏀"
  459. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  460. } else {
  461. LoopStatusLabel.text = "↻"
  462. latestLoopStatusString = "↻"
  463. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  464. }
  465. }
  466. } else {
  467. LoopStatusLabel.text = "↻"
  468. latestLoopStatusString = "↻"
  469. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  470. }
  471. }
  472. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  473. LoopStatusLabel.text = "⚠"
  474. latestLoopStatusString = "⚠"
  475. }
  476. latestLoopTime = lastLoopTime
  477. } // end lastLoopTime
  478. } // end lastLoop Record
  479. var oText = "" as String
  480. currentOverride = 1.0
  481. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  482. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  483. }
  484. if lastOverride["active"] as! Bool {
  485. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  486. if let multiplier = lastOverride["multiplier"] as? Double {
  487. currentOverride = multiplier
  488. oText += String(format: "%.0f%%", (multiplier * 100))
  489. }
  490. else
  491. {
  492. oText += "100%"
  493. }
  494. oText += " ("
  495. let minValue = lastCorrection["minValue"] as! Double
  496. let maxValue = lastCorrection["maxValue"] as! Double
  497. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  498. tableData[3].value = oText
  499. }
  500. }
  501. infoTable.reloadData()
  502. // Start the timer based on the timestamp
  503. let now = dateTimeUtils.getNowTimeIntervalUTC()
  504. let secondsAgo = now - latestLoopTime
  505. DispatchQueue.main.async {
  506. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  507. if secondsAgo >= (20 * 60) {
  508. self.startDeviceStatusTimer(time: (5 * 60))
  509. print("started 5 minute device status timer")
  510. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  511. } else if secondsAgo >= (10 * 60) {
  512. self.startDeviceStatusTimer(time: 60)
  513. print("started 1 minute device status timer")
  514. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  515. } else if secondsAgo >= (7 * 60) {
  516. self.startDeviceStatusTimer(time: 30)
  517. print("started 30 second device status timer")
  518. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  519. } else if secondsAgo >= (5 * 60) {
  520. self.startDeviceStatusTimer(time: 10)
  521. print("started 10 second device status timer")
  522. // We have a current Loop. Set timer to 5:10 from last reading
  523. } else {
  524. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  525. let timerVal = 310 - secondsAgo
  526. print("started 5:10 device status timer: \(timerVal)")
  527. }
  528. }
  529. }
  530. // NS Cage Web Call
  531. func webLoadNSCage() {
  532. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  533. let urlUser = UserDefaultsRepository.url.value
  534. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  535. if token != "" {
  536. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  537. }
  538. guard let urlData = URL(string: urlString) else {
  539. return
  540. }
  541. var request = URLRequest(url: urlData)
  542. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  543. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  544. guard error == nil else {
  545. return
  546. }
  547. guard let data = data else {
  548. return
  549. }
  550. let decoder = JSONDecoder()
  551. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  552. if let entriesResponse = entriesResponse {
  553. DispatchQueue.main.async {
  554. self.updateCage(data: entriesResponse)
  555. }
  556. } else {
  557. return
  558. }
  559. }
  560. task.resume()
  561. }
  562. // NS Cage Response Processor
  563. func updateCage(data: [cageData]) {
  564. self.clearLastInfoData(index: 7)
  565. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  566. if data.count == 0 {
  567. return
  568. }
  569. let lastCageString = data[0].created_at
  570. let formatter = ISO8601DateFormatter()
  571. formatter.formatOptions = [.withFullDate,
  572. .withTime,
  573. .withDashSeparatorInDate,
  574. .withColonSeparatorInTime]
  575. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  576. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  577. let now = dateTimeUtils.getNowTimeIntervalUTC()
  578. let secondsAgo = now - cageTime
  579. //let days = 24 * 60 * 60
  580. let formatter = DateComponentsFormatter()
  581. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  582. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  583. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  584. let formattedDuration = formatter.string(from: secondsAgo)
  585. tableData[7].value = formattedDuration ?? ""
  586. }
  587. infoTable.reloadData()
  588. }
  589. // NS Sage Web Call
  590. func webLoadNSSage() {
  591. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  592. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  593. let urlUser = UserDefaultsRepository.url.value
  594. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  595. if token != "" {
  596. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  597. }
  598. guard let urlData = URL(string: urlString) else {
  599. return
  600. }
  601. var request = URLRequest(url: urlData)
  602. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  603. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  604. guard error == nil else {
  605. return
  606. }
  607. guard let data = data else {
  608. return
  609. }
  610. let decoder = JSONDecoder()
  611. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  612. if let entriesResponse = entriesResponse {
  613. DispatchQueue.main.async {
  614. self.updateSage(data: entriesResponse)
  615. }
  616. } else {
  617. return
  618. }
  619. }
  620. task.resume()
  621. }
  622. // NS Sage Response Processor
  623. func updateSage(data: [cageData]) {
  624. self.clearLastInfoData(index: 6)
  625. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  626. if data.count == 0 {
  627. return
  628. }
  629. var lastSageString = data[0].created_at
  630. let formatter = ISO8601DateFormatter()
  631. formatter.formatOptions = [.withFullDate,
  632. .withTime,
  633. .withDashSeparatorInDate,
  634. .withColonSeparatorInTime]
  635. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  636. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  637. let now = dateTimeUtils.getNowTimeIntervalUTC()
  638. let secondsAgo = now - sageTime
  639. let days = 24 * 60 * 60
  640. let formatter = DateComponentsFormatter()
  641. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  642. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  643. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  644. let formattedDuration = formatter.string(from: secondsAgo)
  645. tableData[6].value = formattedDuration ?? ""
  646. }
  647. infoTable.reloadData()
  648. }
  649. // NS Profile Web Call
  650. func webLoadNSProfile() {
  651. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  652. let urlUser = UserDefaultsRepository.url.value
  653. var urlString = urlUser + "/api/v1/profile/current.json"
  654. if token != "" {
  655. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  656. }
  657. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  658. guard let url = URL(string: escapedAddress!) else {
  659. return
  660. }
  661. var request = URLRequest(url: url)
  662. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  663. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  664. guard error == nil else {
  665. return
  666. }
  667. guard let data = data else {
  668. return
  669. }
  670. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  671. if let json = json {
  672. DispatchQueue.main.async {
  673. self.updateProfile(jsonDeviceStatus: json)
  674. }
  675. } else {
  676. return
  677. }
  678. }
  679. task.resume()
  680. }
  681. // NS Profile Response Processor
  682. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  683. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  684. if jsonDeviceStatus.count == 0 {
  685. return
  686. }
  687. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  688. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  689. basalProfile.removeAll()
  690. for i in 0..<basal.count {
  691. let dict = basal[i] as! Dictionary<String, Any>
  692. do {
  693. let thisValue = try dict[keyPath: "value"] as! Double
  694. let thisTime = dict[keyPath: "time"] as! String
  695. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  696. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  697. basalProfile.append(entry)
  698. } catch {
  699. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  700. }
  701. }
  702. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  703. if firstGraphLoad { return }
  704. // Make temporary array with all values of yesterday and today
  705. let yesterdayStart = dateTimeUtils.getTimeIntervalMidnightYesterday()
  706. let todayStart = dateTimeUtils.getTimeIntervalMidnightToday()
  707. var basal2Day: [DataStructs.basal2DayProfile] = []
  708. // Run twice to add in order yesterday then today.
  709. for p in 0..<basalProfile.count {
  710. let start = yesterdayStart + basalProfile[p].timeAsSeconds
  711. var end = yesterdayStart
  712. // set the endings 1 second before the next one starts
  713. if p < basalProfile.count - 1 {
  714. end = yesterdayStart + basalProfile[p + 1].timeAsSeconds - 1
  715. } else {
  716. // set the end 1 second before midnight
  717. end = yesterdayStart + 86399
  718. }
  719. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  720. basal2Day.append(entry)
  721. }
  722. for p in 0..<basalProfile.count {
  723. let start = todayStart + basalProfile[p].timeAsSeconds
  724. var end = todayStart
  725. // set the endings 1 second before the next one starts
  726. if p < basalProfile.count - 1 {
  727. end = todayStart + basalProfile[p + 1].timeAsSeconds - 1
  728. } else {
  729. // set the end 1 second before midnight
  730. end = todayStart + 86399
  731. }
  732. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  733. basal2Day.append(entry)
  734. }
  735. var firstPass = true
  736. // Runs the scheduled basal to the end of the prediction line
  737. var predictionEndTime = dateTimeUtils.getNowTimeIntervalUTC() + (3600 * UserDefaultsRepository.predictionToLoad.value)
  738. basalScheduleData.removeAll()
  739. for i in 0..<basal2Day.count {
  740. let timeYesterday = dateTimeUtils.getTimeInterval24HoursAgo()
  741. // This processed everything after the first one.
  742. if firstPass == false
  743. && basal2Day[i].startDate <= predictionEndTime {
  744. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: basal2Day[i].startDate)
  745. basalScheduleData.append(startDot)
  746. var endDate = basal2Day[i].endDate
  747. // if it's the last one needed, set it to end at the prediction end time
  748. if endDate > predictionEndTime || i == basal2Day.count - 1 {
  749. endDate = Double(predictionEndTime)
  750. }
  751. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  752. basalScheduleData.append(endDot)
  753. }
  754. // we need to manually set the first one
  755. // Check that this is the first one and there are no existing entries
  756. if firstPass == true {
  757. // check that the timestamp is > the current entry and < the next entry
  758. if timeYesterday >= basal2Day[i].startDate && timeYesterday < basal2Day[i].endDate {
  759. // Set the start time to match the BG start
  760. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: Double(dateTimeUtils.getTimeInterval24HoursAgo() + (60 * 5)))
  761. basalScheduleData.append(startDot)
  762. // set the enddot where the next one will start
  763. var endDate = basal2Day[i].endDate
  764. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  765. basalScheduleData.append(endDot)
  766. firstPass = false
  767. }
  768. }
  769. }
  770. if UserDefaultsRepository.graphBasal.value {
  771. updateBasalScheduledGraph()
  772. }
  773. }
  774. // NS Treatments Web Call
  775. // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
  776. func WebLoadNSTreatments() {
  777. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Treatments") }
  778. if !UserDefaultsRepository.downloadTreatments.value { return }
  779. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  780. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[created_at][$gte]=" + yesterdayString
  781. if token != "" {
  782. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[created_at][$gte]=" + yesterdayString
  783. }
  784. guard let urlData = URL(string: urlString) else {
  785. return
  786. }
  787. var request = URLRequest(url: urlData)
  788. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  789. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  790. guard error == nil else {
  791. return
  792. }
  793. guard let data = data else {
  794. return
  795. }
  796. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  797. if let json = json {
  798. DispatchQueue.main.async {
  799. self.updateTreatments(entries: json)
  800. }
  801. } else {
  802. return
  803. }
  804. }
  805. task.resume()
  806. }
  807. // Process and split out treatments to individual tasks
  808. func updateTreatments(entries: [[String:AnyObject]]) {
  809. var tempBasal: [[String:AnyObject]] = []
  810. var bolus: [[String:AnyObject]] = []
  811. var carbs: [[String:AnyObject]] = []
  812. var temporaryOverride: [[String:AnyObject]] = []
  813. var note: [[String:AnyObject]] = []
  814. var bgCheck: [[String:AnyObject]] = []
  815. var suspendPump: [[String:AnyObject]] = []
  816. var resumePump: [[String:AnyObject]] = []
  817. var pumpSiteChange: [[String:AnyObject]] = []
  818. var cgmSensorStart: [[String:AnyObject]] = []
  819. for i in 0..<entries.count {
  820. let entry = entries[i] as [String : AnyObject]?
  821. switch entry?["eventType"] as! String {
  822. case "Temp Basal":
  823. tempBasal.append(entry!)
  824. case "Correction Bolus":
  825. bolus.append(entry!)
  826. case "Meal Bolus":
  827. carbs.append(entry!)
  828. case "Temporary Override":
  829. temporaryOverride.append(entry!)
  830. case "Note":
  831. note.append(entry!)
  832. print("Note: \(String(describing: entry))")
  833. case "BG Check":
  834. bgCheck.append(entry!)
  835. case "Suspend Pump":
  836. suspendPump.append(entry!)
  837. case "Resume Pump":
  838. resumePump.append(entry!)
  839. case "Pump Site Change":
  840. pumpSiteChange.append(entry!)
  841. case "Sensor Start":
  842. cgmSensorStart.append(entry!)
  843. default:
  844. print("No Match: \(String(describing: entry))")
  845. }
  846. }
  847. // end of for loop
  848. if tempBasal.count > 0 {
  849. processNSBasals(entries: tempBasal)
  850. } else {
  851. if basalData.count < 0 {
  852. clearOldTempBasal()
  853. }
  854. }
  855. if bolus.count > 0 {
  856. processNSBolus(entries: bolus)
  857. } else {
  858. if bolusData.count > 0 {
  859. clearOldBolus()
  860. }
  861. }
  862. if carbs.count > 0 {
  863. processNSCarbs(entries: carbs)
  864. } else {
  865. if carbData.count > 0 {
  866. clearOldCarb()
  867. }
  868. }
  869. if bgCheck.count > 0 {
  870. processNSBGCheck(entries: bgCheck)
  871. } else {
  872. if bgCheckData.count > 0 {
  873. clearOldBGCheck()
  874. }
  875. }
  876. if temporaryOverride.count > 0 {
  877. processNSOverrides(entries: temporaryOverride)
  878. } else {
  879. if overrideGraphData.count > 0 {
  880. clearOldOverride()
  881. }
  882. }
  883. if suspendPump.count > 0 {
  884. processSuspendPump(entries: suspendPump)
  885. } else {
  886. if suspendGraphData.count > 0 {
  887. clearOldSuspend()
  888. }
  889. }
  890. if resumePump.count > 0 {
  891. processResumePump(entries: resumePump)
  892. } else {
  893. if resumeGraphData.count > 0 {
  894. clearOldResume()
  895. }
  896. }
  897. if cgmSensorStart.count > 0 {
  898. processSensorStart(entries: cgmSensorStart)
  899. } else {
  900. if sensorStartGraphData.count > 0 {
  901. clearOldSensor()
  902. }
  903. }
  904. if note.count > 0 {
  905. processNotes(entries: note)
  906. } else {
  907. if noteGraphData.count > 0 {
  908. clearOldNotes()
  909. }
  910. }
  911. }
  912. func clearOldTempBasal()
  913. {
  914. for i in 0..<basalData.count {
  915. if basalData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  916. basalData.remove(at: i)
  917. }
  918. }
  919. updateBasalGraph()
  920. }
  921. func clearOldBolus()
  922. {
  923. for i in 0..<bolusData.count {
  924. if bolusData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  925. bolusData.remove(at: i)
  926. }
  927. }
  928. updateBolusGraph()
  929. }
  930. func clearOldCarb()
  931. {
  932. for i in 0..<carbData.count {
  933. if carbData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  934. carbData.remove(at: i)
  935. }
  936. }
  937. updateCarbGraph()
  938. }
  939. func clearOldBGCheck()
  940. {
  941. for i in 0..<bgCheckData.count {
  942. if bgCheckData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  943. bgCheckData.remove(at: i)
  944. }
  945. }
  946. updateBGCheckGraph()
  947. }
  948. func clearOldOverride()
  949. {
  950. for i in 0..<overrideGraphData.count {
  951. if overrideGraphData[i].endDate < dateTimeUtils.getTimeInterval24HoursAgo() {
  952. overrideGraphData.remove(at: i)
  953. }
  954. }
  955. updateOverrideGraph()
  956. }
  957. func clearOldSuspend()
  958. {
  959. for i in 0..<suspendGraphData.count {
  960. if suspendGraphData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  961. suspendGraphData.remove(at: i)
  962. }
  963. }
  964. updateSuspendGraph()
  965. }
  966. func clearOldResume()
  967. {
  968. for i in 0..<resumeGraphData.count {
  969. if resumeGraphData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  970. resumeGraphData.remove(at: i)
  971. }
  972. }
  973. updateResumeGraph()
  974. }
  975. func clearOldSensor()
  976. {
  977. for i in 0..<sensorStartGraphData.count {
  978. if sensorStartGraphData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  979. sensorStartGraphData.remove(at: i)
  980. }
  981. }
  982. updateSensorStart()
  983. }
  984. func clearOldNotes()
  985. {
  986. for i in 0..<noteGraphData.count {
  987. if noteGraphData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() {
  988. noteGraphData.remove(at: i)
  989. }
  990. }
  991. updateNotes()
  992. }
  993. // NS Temp Basal Response Processor
  994. func processNSBasals(entries: [[String:AnyObject]]) {
  995. self.clearLastInfoData(index: 2)
  996. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  997. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  998. basalData.removeAll()
  999. var lastEndDot = 0.0
  1000. var tempArray = entries
  1001. tempArray.reverse()
  1002. for i in 0..<tempArray.count {
  1003. let currentEntry = tempArray[i] as [String : AnyObject]?
  1004. var basalDate: String
  1005. if currentEntry?["timestamp"] != nil {
  1006. basalDate = currentEntry?["timestamp"] as! String
  1007. } else if currentEntry?["created_at"] != nil {
  1008. basalDate = currentEntry?["created_at"] as! String
  1009. } else {
  1010. return
  1011. }
  1012. var strippedZone = String(basalDate.dropLast())
  1013. strippedZone = strippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1014. let dateFormatter = DateFormatter()
  1015. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1016. dateFormatter.locale = Locale(identifier: "en_US")
  1017. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1018. let dateString = dateFormatter.date(from: strippedZone)
  1019. let dateTimeStamp = dateString!.timeIntervalSince1970
  1020. guard let basalRate = currentEntry?["absolute"] as? Double else {
  1021. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Basal entry")}
  1022. continue
  1023. }
  1024. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  1025. // Setting end dots
  1026. var duration = 0.0
  1027. do {
  1028. duration = try currentEntry?["duration"] as! Double
  1029. } catch {
  1030. print("No Duration Found")
  1031. }
  1032. // 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
  1033. if i > 0 {
  1034. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  1035. var priorBasalDate: String
  1036. if priorEntry?["timestamp"] != nil {
  1037. priorBasalDate = priorEntry?["timestamp"] as! String
  1038. } else if currentEntry?["created_at"] != nil {
  1039. priorBasalDate = priorEntry?["created_at"] as! String
  1040. } else {
  1041. continue
  1042. }
  1043. var priorStrippedZone = String(priorBasalDate.dropLast())
  1044. priorStrippedZone = priorStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1045. let priorDateFormatter = DateFormatter()
  1046. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1047. priorDateFormatter.locale = Locale(identifier: "en_US")
  1048. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1049. let priorDateString = dateFormatter.date(from: priorStrippedZone)
  1050. let priorDateTimeStamp = priorDateString!.timeIntervalSince1970
  1051. let priorDuration = priorEntry?["duration"] as! Double
  1052. // 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
  1053. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  1054. var scheduled = 0.0
  1055. // cycle through basal profiles.
  1056. // TODO figure out how to deal with profile changes that happen mid-gap
  1057. for b in 0..<self.basalScheduleData.count {
  1058. if (priorDateTimeStamp + (priorDuration * 60)) >= basalScheduleData[b].date {
  1059. scheduled = basalScheduleData[b].basalRate
  1060. }
  1061. }
  1062. // Make the starting dot at the last ending dot
  1063. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  1064. basalData.append(startDot)
  1065. //if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Basal: Scheduled " + String(scheduled) + " " + String(dateTimeStamp)) }
  1066. // Make the ending dot at the new starting dot
  1067. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  1068. basalData.append(endDot)
  1069. }
  1070. }
  1071. // Make the starting dot
  1072. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  1073. basalData.append(startDot)
  1074. // Make the ending dot
  1075. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  1076. // duration is already set to 0 if there is no duration set on it.
  1077. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  1078. if i == tempArray.count - 1 && duration == 0.0 {
  1079. lastEndDot = dateTimeStamp + (30 * 60)
  1080. latestBasal = String(format:"%.2f", basalRate)
  1081. } else {
  1082. lastEndDot = dateTimeStamp + (duration * 60)
  1083. latestBasal = String(format:"%.2f", basalRate)
  1084. }
  1085. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  1086. if i < tempArray.count - 1 {
  1087. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  1088. var nextBasalDate: String
  1089. if nextEntry?["timestamp"] != nil {
  1090. nextBasalDate = nextEntry?["timestamp"] as! String
  1091. } else if currentEntry?["created_at"] != nil {
  1092. nextBasalDate = nextEntry?["created_at"] as! String
  1093. } else {
  1094. continue
  1095. }
  1096. var nextStrippedZone = String(nextBasalDate.dropLast())
  1097. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1098. let nextDateFormatter = DateFormatter()
  1099. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1100. nextDateFormatter.locale = Locale(identifier: "en_US")
  1101. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1102. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  1103. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  1104. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1105. lastEndDot = nextDateTimeStamp
  1106. }
  1107. }
  1108. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1109. basalData.append(endDot)
  1110. }
  1111. // If last basal was prior to right now, we need to create one last scheduled entry
  1112. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1113. var scheduled = 0.0
  1114. // cycle through basal profiles.
  1115. // TODO figure out how to deal with profile changes that happen mid-gap
  1116. for b in 0..<self.basalProfile.count {
  1117. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1118. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1119. // check the prior temp ending to the profile seconds from midnight
  1120. print("yesterday " + String(scheduleTimeYesterday))
  1121. print("today " + String(scheduleTimeToday))
  1122. if lastEndDot >= scheduleTimeToday {
  1123. scheduled = basalProfile[b].value
  1124. }
  1125. }
  1126. latestBasal = String(format:"%.2f", scheduled)
  1127. // Make the starting dot at the last ending dot
  1128. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1129. basalData.append(startDot)
  1130. // Make the ending dot 10 minutes after now
  1131. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1132. basalData.append(endDot)
  1133. }
  1134. tableData[2].value = latestBasal
  1135. infoTable.reloadData()
  1136. if UserDefaultsRepository.graphBasal.value {
  1137. updateBasalGraph()
  1138. }
  1139. infoTable.reloadData()
  1140. }
  1141. // NS Meal Bolus Response Processor
  1142. func processNSBolus(entries: [[String:AnyObject]]) {
  1143. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1144. // because it's a small array, we're going to destroy and reload every time.
  1145. bolusData.removeAll()
  1146. var lastFoundIndex = 0
  1147. for i in 0..<entries.count {
  1148. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1149. var bolusDate: String
  1150. if currentEntry?["timestamp"] != nil {
  1151. bolusDate = currentEntry?["timestamp"] as! String
  1152. } else if currentEntry?["created_at"] != nil {
  1153. bolusDate = currentEntry?["created_at"] as! String
  1154. } else {
  1155. return
  1156. }
  1157. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1158. var strippedZone = String(bolusDate.dropLast())
  1159. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1160. let dateFormatter = DateFormatter()
  1161. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1162. dateFormatter.locale = Locale(identifier: "en_US")
  1163. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1164. let dateString = dateFormatter.date(from: strippedZone)
  1165. let dateTimeStamp = dateString!.timeIntervalSince1970
  1166. do {
  1167. let bolus = try currentEntry?["insulin"] as! Double
  1168. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1169. lastFoundIndex = sgv.foundIndex
  1170. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1171. // Make the dot
  1172. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv + 20))
  1173. bolusData.append(dot)
  1174. }
  1175. } catch {
  1176. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Bolus") }
  1177. }
  1178. }
  1179. if UserDefaultsRepository.graphBolus.value {
  1180. updateBolusGraph()
  1181. }
  1182. }
  1183. // NS Carb Bolus Response Processor
  1184. func processNSCarbs(entries: [[String:AnyObject]]) {
  1185. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1186. // because it's a small array, we're going to destroy and reload every time.
  1187. carbData.removeAll()
  1188. var lastFoundIndex = 0
  1189. var lastFoundBolus = 0
  1190. for i in 0..<entries.count {
  1191. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1192. var carbDate: String
  1193. if currentEntry?["timestamp"] != nil {
  1194. carbDate = currentEntry?["timestamp"] as! String
  1195. } else if currentEntry?["created_at"] != nil {
  1196. carbDate = currentEntry?["created_at"] as! String
  1197. } else {
  1198. return
  1199. }
  1200. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1201. // Fix for FreeAPS milliseconds in timestamp
  1202. var strippedZone = String(carbDate.dropLast())
  1203. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1204. let dateFormatter = DateFormatter()
  1205. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1206. dateFormatter.locale = Locale(identifier: "en_US")
  1207. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1208. let dateString = dateFormatter.date(from: strippedZone)
  1209. var dateTimeStamp = dateString!.timeIntervalSince1970
  1210. guard let carbs = currentEntry?["carbs"] as? Double else {
  1211. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1212. break
  1213. }
  1214. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1215. lastFoundIndex = sgv.foundIndex
  1216. var offset = -50
  1217. if sgv.sgv < Double(250) {
  1218. let bolusTime = findNearestBolusbyTime(timeWithin: 300, needle: dateTimeStamp, haystack: bolusData, startingIndex: lastFoundBolus)
  1219. lastFoundBolus = bolusTime.foundIndex
  1220. if bolusTime.offset {
  1221. offset = 70
  1222. } else {
  1223. offset = 20
  1224. }
  1225. }
  1226. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1227. // Make the dot
  1228. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv + Double(offset)), absorptionTime: absorptionTime)
  1229. carbData.append(dot)
  1230. }
  1231. }
  1232. if UserDefaultsRepository.graphCarbs.value {
  1233. updateCarbGraph()
  1234. }
  1235. }
  1236. // NS Suspend Pump Response Processor
  1237. func processSuspendPump(entries: [[String:AnyObject]]) {
  1238. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Suspend Pump") }
  1239. // because it's a small array, we're going to destroy and reload every time.
  1240. suspendGraphData.removeAll()
  1241. var lastFoundIndex = 0
  1242. for i in 0..<entries.count {
  1243. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1244. var date: String
  1245. if currentEntry?["timestamp"] != nil {
  1246. date = currentEntry?["timestamp"] as! String
  1247. } else if currentEntry?["created_at"] != nil {
  1248. date = currentEntry?["created_at"] as! String
  1249. } else {
  1250. return
  1251. }
  1252. // Fix for FreeAPS milliseconds in timestamp
  1253. var strippedZone = String(date.dropLast())
  1254. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1255. let dateFormatter = DateFormatter()
  1256. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1257. dateFormatter.locale = Locale(identifier: "en_US")
  1258. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1259. let dateString = dateFormatter.date(from: strippedZone)
  1260. let dateTimeStamp = dateString!.timeIntervalSince1970
  1261. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1262. lastFoundIndex = sgv.foundIndex
  1263. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1264. // Make the dot
  1265. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1266. suspendGraphData.append(dot)
  1267. }
  1268. }
  1269. if UserDefaultsRepository.graphOtherTreatments.value {
  1270. updateSuspendGraph()
  1271. }
  1272. }
  1273. // NS Resume Pump Response Processor
  1274. func processResumePump(entries: [[String:AnyObject]]) {
  1275. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Resume Pump") }
  1276. // because it's a small array, we're going to destroy and reload every time.
  1277. resumeGraphData.removeAll()
  1278. var lastFoundIndex = 0
  1279. for i in 0..<entries.count {
  1280. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1281. var date: String
  1282. if currentEntry?["timestamp"] != nil {
  1283. date = currentEntry?["timestamp"] as! String
  1284. } else if currentEntry?["created_at"] != nil {
  1285. date = currentEntry?["created_at"] as! String
  1286. } else {
  1287. return
  1288. }
  1289. // Fix for FreeAPS milliseconds in timestamp
  1290. var strippedZone = String(date.dropLast())
  1291. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1292. let dateFormatter = DateFormatter()
  1293. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1294. dateFormatter.locale = Locale(identifier: "en_US")
  1295. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1296. let dateString = dateFormatter.date(from: strippedZone)
  1297. let dateTimeStamp = dateString!.timeIntervalSince1970
  1298. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1299. lastFoundIndex = sgv.foundIndex
  1300. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1301. // Make the dot
  1302. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1303. resumeGraphData.append(dot)
  1304. }
  1305. }
  1306. if UserDefaultsRepository.graphOtherTreatments.value {
  1307. updateResumeGraph()
  1308. }
  1309. }
  1310. // NS Sensor Start Response Processor
  1311. func processSensorStart(entries: [[String:AnyObject]]) {
  1312. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Sensor Start") }
  1313. // because it's a small array, we're going to destroy and reload every time.
  1314. sensorStartGraphData.removeAll()
  1315. var lastFoundIndex = 0
  1316. for i in 0..<entries.count {
  1317. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1318. var date: String
  1319. if currentEntry?["timestamp"] != nil {
  1320. date = currentEntry?["timestamp"] as! String
  1321. } else if currentEntry?["created_at"] != nil {
  1322. date = currentEntry?["created_at"] as! String
  1323. } else {
  1324. return
  1325. }
  1326. // Fix for FreeAPS milliseconds in timestamp
  1327. var strippedZone = String(date.dropLast())
  1328. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1329. let dateFormatter = DateFormatter()
  1330. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1331. dateFormatter.locale = Locale(identifier: "en_US")
  1332. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1333. let dateString = dateFormatter.date(from: strippedZone)
  1334. let dateTimeStamp = dateString!.timeIntervalSince1970
  1335. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1336. lastFoundIndex = sgv.foundIndex
  1337. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1338. // Make the dot
  1339. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1340. sensorStartGraphData.append(dot)
  1341. }
  1342. }
  1343. if UserDefaultsRepository.graphOtherTreatments.value {
  1344. updateSensorStart()
  1345. }
  1346. }
  1347. // NS Note Response Processor
  1348. func processNotes(entries: [[String:AnyObject]]) {
  1349. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Notes") }
  1350. // because it's a small array, we're going to destroy and reload every time.
  1351. noteGraphData.removeAll()
  1352. var lastFoundIndex = 0
  1353. for i in 0..<entries.count {
  1354. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1355. var date: String
  1356. if currentEntry?["timestamp"] != nil {
  1357. date = currentEntry?["timestamp"] as! String
  1358. } else if currentEntry?["created_at"] != nil {
  1359. date = currentEntry?["created_at"] as! String
  1360. } else {
  1361. return
  1362. }
  1363. // Fix for FreeAPS milliseconds in timestamp
  1364. var strippedZone = String(date.dropLast())
  1365. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1366. let dateFormatter = DateFormatter()
  1367. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1368. dateFormatter.locale = Locale(identifier: "en_US")
  1369. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1370. let dateString = dateFormatter.date(from: strippedZone)
  1371. let dateTimeStamp = dateString!.timeIntervalSince1970
  1372. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1373. lastFoundIndex = sgv.foundIndex
  1374. guard let thisNote = currentEntry?["notes"] as? String else { continue }
  1375. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1376. // Make the dot
  1377. let dot = DataStructs.noteStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv), note: thisNote)
  1378. noteGraphData.append(dot)
  1379. }
  1380. }
  1381. if UserDefaultsRepository.graphOtherTreatments.value {
  1382. updateNotes()
  1383. }
  1384. }
  1385. // NS BG Check Response Processor
  1386. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1387. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1388. // because it's a small array, we're going to destroy and reload every time.
  1389. bgCheckData.removeAll()
  1390. for i in 0..<entries.count {
  1391. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1392. var date: String
  1393. if currentEntry?["timestamp"] != nil {
  1394. date = currentEntry?["timestamp"] as! String
  1395. } else if currentEntry?["created_at"] != nil {
  1396. date = currentEntry?["created_at"] as! String
  1397. } else {
  1398. return
  1399. }
  1400. // Fix for FreeAPS milliseconds in timestamp
  1401. var strippedZone = String(date.dropLast())
  1402. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1403. let dateFormatter = DateFormatter()
  1404. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1405. dateFormatter.locale = Locale(identifier: "en_US")
  1406. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1407. let dateString = dateFormatter.date(from: strippedZone)
  1408. let dateTimeStamp = dateString!.timeIntervalSince1970
  1409. guard let sgv = currentEntry?["glucose"] as? Int else {
  1410. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1411. continue
  1412. }
  1413. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1414. // Make the dot
  1415. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1416. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1417. bgCheckData.append(dot)
  1418. }
  1419. }
  1420. if UserDefaultsRepository.graphOtherTreatments.value {
  1421. updateBGCheckGraph()
  1422. }
  1423. }
  1424. // NS Override Response Processor
  1425. func processNSOverrides(entries: [[String:AnyObject]]) {
  1426. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1427. // because it's a small array, we're going to destroy and reload every time.
  1428. overrideGraphData.removeAll()
  1429. for i in 0..<entries.count {
  1430. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1431. var date: String
  1432. if currentEntry?["timestamp"] != nil {
  1433. date = currentEntry?["timestamp"] as! String
  1434. } else if currentEntry?["created_at"] != nil {
  1435. date = currentEntry?["created_at"] as! String
  1436. } else {
  1437. return
  1438. }
  1439. // Fix for FreeAPS milliseconds in timestamp
  1440. var strippedZone = String(date.dropLast())
  1441. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1442. let dateFormatter = DateFormatter()
  1443. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1444. dateFormatter.locale = Locale(identifier: "en_US")
  1445. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1446. let dateString = dateFormatter.date(from: strippedZone)
  1447. var dateTimeStamp = dateString!.timeIntervalSince1970
  1448. if dateTimeStamp < dateTimeUtils.getTimeInterval24HoursAgo() {
  1449. dateTimeStamp = dateTimeUtils.getTimeInterval24HoursAgo()
  1450. }
  1451. var multiplier: Double = 1.0
  1452. if currentEntry?["insulinNeedsScaleFactor"] != nil {
  1453. multiplier = currentEntry?["insulinNeedsScaleFactor"] as! Double
  1454. }
  1455. var duration: Double = 5.0
  1456. if let durationType = currentEntry?["durationType"] as? String {
  1457. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1458. } else {
  1459. duration = (currentEntry?["duration"] as? Double)!
  1460. duration = duration * 60
  1461. }
  1462. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1463. guard let reason = currentEntry?["reason"] as? String else { continue }
  1464. var range: [Int] = []
  1465. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1466. if ranges.count == 2 {
  1467. guard let low = ranges[0] as? Int else { continue }
  1468. guard let high = ranges[1] as? Int else { continue }
  1469. range.append(low)
  1470. range.append(high)
  1471. }
  1472. }
  1473. let endDate = dateTimeStamp + (duration)
  1474. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multiplier, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1475. overrideGraphData.append(dot)
  1476. }
  1477. if UserDefaultsRepository.graphOtherTreatments.value {
  1478. updateOverrideGraph()
  1479. }
  1480. }
  1481. }