ShareClientExtension.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // ShareClientExtension.swift
  3. // LoopFollow
  4. //
  5. // Created by Jose Paredes on 7/13/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import ShareClient
  10. public struct ShareGlucoseData: Decodable {
  11. var sgv: Int
  12. var date: TimeInterval
  13. var direction: String?
  14. enum CodingKeys: String, CodingKey {
  15. case sgv // Sensor Blood Glucose
  16. case mbg // Manual Blood Glucose
  17. case date
  18. case direction
  19. }
  20. // Decoder initializer for handling JSON data
  21. public init(from decoder: Decoder) throws {
  22. let container = try decoder.container(keyedBy: CodingKeys.self)
  23. if let glucoseValue = try? container.decode(Double.self, forKey: .sgv) {
  24. sgv = Int(glucoseValue.rounded())
  25. } else if let mbgValue = try? container.decode(Double.self, forKey: .mbg) {
  26. sgv = Int(mbgValue.rounded())
  27. } else {
  28. throw DecodingError.dataCorruptedError(forKey: .sgv, in: container, debugDescription: "Expected to decode Double for sgv or mbg.")
  29. }
  30. // Decode the date and optional direction
  31. date = try container.decode(TimeInterval.self, forKey: .date)
  32. direction = try container.decodeIfPresent(String.self, forKey: .direction)
  33. }
  34. public init(sgv: Int, date: TimeInterval, direction: String?) {
  35. self.sgv = sgv
  36. self.date = date
  37. self.direction = direction
  38. }
  39. }
  40. private var TrendTable: [String] = [
  41. "NONE", // 0
  42. "DoubleUp", // 1
  43. "SingleUp", // 2
  44. "FortyFiveUp", // 3
  45. "Flat", // 4
  46. "FortyFiveDown", // 5
  47. "SingleDown", // 6
  48. "DoubleDown", // 7
  49. "NOT COMPUTABLE", // 8
  50. "RATE OUT OF RANGE" // 9
  51. ]
  52. // TODO: probably better to make this an inherited class rather than an extension
  53. extension ShareClient {
  54. public func fetchData(_ entries: Int, callback: @escaping (ShareError?, [ShareGlucoseData]?) -> Void) {
  55. self.fetchLast(entries) { (error, result) -> () in
  56. guard error == nil || result != nil else {
  57. return callback(error, nil)
  58. }
  59. // parse data to conanical form
  60. var shareData = [ShareGlucoseData]()
  61. for i in 0..<result!.count {
  62. var trend = Int(result![i].trend)
  63. if(trend < 0 || trend > TrendTable.count-1) {
  64. trend = 0
  65. }
  66. let newShareData = ShareGlucoseData(
  67. sgv: Int(result![i].glucose),
  68. date: result![i].timestamp.timeIntervalSince1970,
  69. direction: TrendTable[trend]
  70. )
  71. shareData.append(newShareData)
  72. }
  73. callback(nil,shareData)
  74. }
  75. }
  76. }