RileyLinkDeviceTableViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //
  2. // RileyLinkDeviceTableViewController.swift
  3. // Naterade
  4. //
  5. // Created by Nathan Racklyeft on 3/5/16.
  6. // Copyright © 2016 Nathan Racklyeft. All rights reserved.
  7. //
  8. import UIKit
  9. import LoopKitUI
  10. import RileyLinkBLEKit
  11. import RileyLinkKit
  12. import os.log
  13. let CellIdentifier = "Cell"
  14. public class RileyLinkDeviceTableViewController: UITableViewController {
  15. private let log = OSLog(category: "RileyLinkDeviceTableViewController")
  16. public let device: RileyLinkDevice
  17. private var bleRSSI: Int?
  18. private var firmwareVersion: String? {
  19. didSet {
  20. guard isViewLoaded else {
  21. return
  22. }
  23. cellForRow(.version)?.detailTextLabel?.text = firmwareVersion
  24. }
  25. }
  26. private var uptime: TimeInterval? {
  27. didSet {
  28. guard isViewLoaded else {
  29. return
  30. }
  31. cellForRow(.uptime)?.setDetailAge(uptime)
  32. }
  33. }
  34. private var frequency: Measurement<UnitFrequency>? {
  35. didSet {
  36. guard isViewLoaded else {
  37. return
  38. }
  39. cellForRow(.frequency)?.setDetailFrequency(frequency, formatter: frequencyFormatter)
  40. }
  41. }
  42. var rssiFetchTimer: Timer? {
  43. willSet {
  44. rssiFetchTimer?.invalidate()
  45. }
  46. }
  47. private lazy var frequencyFormatter: MeasurementFormatter = {
  48. let formatter = MeasurementFormatter()
  49. formatter.numberFormatter = decimalFormatter
  50. return formatter
  51. }()
  52. private var appeared = false
  53. public init(device: RileyLinkDevice) {
  54. self.device = device
  55. super.init(style: .grouped)
  56. updateDeviceStatus()
  57. }
  58. required public init?(coder aDecoder: NSCoder) {
  59. fatalError("init(coder:) has not been implemented")
  60. }
  61. public override func viewDidLoad() {
  62. super.viewDidLoad()
  63. title = device.name
  64. self.observe()
  65. }
  66. @objc func updateRSSI() {
  67. device.readRSSI()
  68. }
  69. func updateDeviceStatus() {
  70. device.getStatus { (status) in
  71. DispatchQueue.main.async {
  72. self.firmwareVersion = status.firmwareDescription
  73. }
  74. }
  75. }
  76. func updateUptime() {
  77. device.runSession(withName: "Get stats for uptime") { (session) in
  78. do {
  79. let statistics = try session.getRileyLinkStatistics()
  80. DispatchQueue.main.async {
  81. self.uptime = statistics.uptime
  82. }
  83. } catch let error {
  84. self.log.error("Failed to get stats for uptime: %{public}@", String(describing: error))
  85. }
  86. }
  87. }
  88. func updateFrequency() {
  89. device.runSession(withName: "Get base frequency") { (session) in
  90. do {
  91. let frequency = try session.readBaseFrequency()
  92. DispatchQueue.main.async {
  93. self.frequency = frequency
  94. }
  95. } catch let error {
  96. self.log.error("Failed to get base frequency: %{public}@", String(describing: error))
  97. }
  98. }
  99. }
  100. // References to registered notification center observers
  101. private var notificationObservers: [Any] = []
  102. deinit {
  103. for observer in notificationObservers {
  104. NotificationCenter.default.removeObserver(observer)
  105. }
  106. }
  107. private func observe() {
  108. let center = NotificationCenter.default
  109. let mainQueue = OperationQueue.main
  110. notificationObservers = [
  111. center.addObserver(forName: .DeviceNameDidChange, object: device, queue: mainQueue) { [weak self] (note) -> Void in
  112. if let cell = self?.cellForRow(.customName) {
  113. cell.detailTextLabel?.text = self?.device.name
  114. }
  115. self?.title = self?.device.name
  116. },
  117. center.addObserver(forName: .DeviceConnectionStateDidChange, object: device, queue: mainQueue) { [weak self] (note) -> Void in
  118. if let cell = self?.cellForRow(.connection) {
  119. cell.detailTextLabel?.text = self?.device.peripheralState.description
  120. }
  121. },
  122. center.addObserver(forName: .DeviceRSSIDidChange, object: device, queue: mainQueue) { [weak self] (note) -> Void in
  123. self?.bleRSSI = note.userInfo?[RileyLinkDevice.notificationRSSIKey] as? Int
  124. if let cell = self?.cellForRow(.rssi), let formatter = self?.integerFormatter {
  125. cell.setDetailRSSI(self?.bleRSSI, formatter: formatter)
  126. }
  127. },
  128. center.addObserver(forName: .DeviceDidStartIdle, object: device, queue: mainQueue) { [weak self] (note) in
  129. self?.updateDeviceStatus()
  130. },
  131. ]
  132. }
  133. public override func viewWillAppear(_ animated: Bool) {
  134. super.viewWillAppear(animated)
  135. if appeared {
  136. tableView.reloadData()
  137. }
  138. rssiFetchTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(updateRSSI), userInfo: nil, repeats: true)
  139. appeared = true
  140. updateRSSI()
  141. updateFrequency()
  142. updateUptime()
  143. }
  144. public override func viewWillDisappear(_ animated: Bool) {
  145. super.viewWillDisappear(animated)
  146. rssiFetchTimer = nil
  147. }
  148. // MARK: - Formatters
  149. private lazy var dateFormatter: DateFormatter = {
  150. let dateFormatter = DateFormatter()
  151. dateFormatter.dateStyle = .none
  152. dateFormatter.timeStyle = .medium
  153. return dateFormatter
  154. }()
  155. private lazy var integerFormatter = NumberFormatter()
  156. private lazy var measurementFormatter: MeasurementFormatter = {
  157. let formatter = MeasurementFormatter()
  158. formatter.numberFormatter = decimalFormatter
  159. return formatter
  160. }()
  161. private lazy var decimalFormatter: NumberFormatter = {
  162. let decimalFormatter = NumberFormatter()
  163. decimalFormatter.numberStyle = .decimal
  164. decimalFormatter.minimumSignificantDigits = 5
  165. return decimalFormatter
  166. }()
  167. // MARK: - Table view data source
  168. private enum Section: Int, CaseCountable {
  169. case device
  170. case commands
  171. }
  172. private enum DeviceRow: Int, CaseCountable {
  173. case customName
  174. case version
  175. case rssi
  176. case connection
  177. case uptime
  178. case frequency
  179. }
  180. private func cellForRow(_ row: DeviceRow) -> UITableViewCell? {
  181. return tableView.cellForRow(at: IndexPath(row: row.rawValue, section: Section.device.rawValue))
  182. }
  183. public override func numberOfSections(in tableView: UITableView) -> Int {
  184. return Section.count
  185. }
  186. public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  187. switch Section(rawValue: section)! {
  188. case .device:
  189. return DeviceRow.count
  190. case .commands:
  191. return 0
  192. }
  193. }
  194. public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  195. let cell: UITableViewCell
  196. if let reusableCell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) {
  197. cell = reusableCell
  198. } else {
  199. cell = UITableViewCell(style: .value1, reuseIdentifier: CellIdentifier)
  200. }
  201. cell.accessoryType = .none
  202. switch Section(rawValue: indexPath.section)! {
  203. case .device:
  204. switch DeviceRow(rawValue: indexPath.row)! {
  205. case .customName:
  206. cell.textLabel?.text = LocalizedString("Name", comment: "The title of the cell showing device name")
  207. cell.detailTextLabel?.text = device.name
  208. cell.accessoryType = .disclosureIndicator
  209. case .version:
  210. cell.textLabel?.text = LocalizedString("Firmware", comment: "The title of the cell showing firmware version")
  211. cell.detailTextLabel?.text = firmwareVersion
  212. case .connection:
  213. cell.textLabel?.text = LocalizedString("Connection State", comment: "The title of the cell showing BLE connection state")
  214. cell.detailTextLabel?.text = device.peripheralState.description
  215. case .rssi:
  216. cell.textLabel?.text = LocalizedString("Signal Strength", comment: "The title of the cell showing BLE signal strength (RSSI)")
  217. cell.setDetailRSSI(bleRSSI, formatter: integerFormatter)
  218. case .uptime:
  219. cell.textLabel?.text = LocalizedString("Uptime", comment: "The title of the cell showing uptime")
  220. cell.setDetailAge(uptime)
  221. case .frequency:
  222. cell.textLabel?.text = LocalizedString("Frequency", comment: "The title of the cell showing current rileylink frequency")
  223. cell.setDetailFrequency(frequency, formatter: frequencyFormatter)
  224. }
  225. case .commands:
  226. cell.accessoryType = .disclosureIndicator
  227. cell.detailTextLabel?.text = nil
  228. }
  229. return cell
  230. }
  231. public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  232. switch Section(rawValue: section)! {
  233. case .device:
  234. return LocalizedString("Device", comment: "The title of the section describing the device")
  235. case .commands:
  236. return LocalizedString("Commands", comment: "The title of the section describing commands")
  237. }
  238. }
  239. // MARK: - UITableViewDelegate
  240. public override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
  241. switch Section(rawValue: indexPath.section)! {
  242. case .device:
  243. switch DeviceRow(rawValue: indexPath.row)! {
  244. case .customName:
  245. return true
  246. default:
  247. return false
  248. }
  249. case .commands:
  250. return device.peripheralState == .connected
  251. }
  252. }
  253. public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  254. switch Section(rawValue: indexPath.section)! {
  255. case .device:
  256. switch DeviceRow(rawValue: indexPath.row)! {
  257. case .customName:
  258. let vc = TextFieldTableViewController()
  259. if let cell = tableView.cellForRow(at: indexPath) {
  260. vc.title = cell.textLabel?.text
  261. vc.value = device.name
  262. vc.delegate = self
  263. vc.keyboardType = .default
  264. }
  265. show(vc, sender: indexPath)
  266. default:
  267. break
  268. }
  269. case .commands:
  270. break
  271. }
  272. }
  273. }
  274. extension RileyLinkDeviceTableViewController: TextFieldTableViewControllerDelegate {
  275. public func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController) {
  276. _ = navigationController?.popViewController(animated: true)
  277. }
  278. public func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController) {
  279. if let indexPath = tableView.indexPathForSelectedRow {
  280. switch Section(rawValue: indexPath.section)! {
  281. case .device:
  282. switch DeviceRow(rawValue: indexPath.row)! {
  283. case .customName:
  284. device.setCustomName(controller.value!)
  285. default:
  286. break
  287. }
  288. default:
  289. break
  290. }
  291. }
  292. }
  293. }
  294. private extension TimeInterval {
  295. func format(using units: NSCalendar.Unit) -> String? {
  296. let formatter = DateComponentsFormatter()
  297. formatter.allowedUnits = units
  298. formatter.unitsStyle = .full
  299. formatter.zeroFormattingBehavior = .dropLeading
  300. formatter.maximumUnitCount = 2
  301. return formatter.string(from: self)
  302. }
  303. }
  304. private extension UITableViewCell {
  305. func setDetailDate(_ date: Date?, formatter: DateFormatter) {
  306. if let date = date {
  307. detailTextLabel?.text = formatter.string(from: date)
  308. } else {
  309. detailTextLabel?.text = "-"
  310. }
  311. }
  312. func setDetailRSSI(_ decibles: Int?, formatter: NumberFormatter) {
  313. detailTextLabel?.text = formatter.decibleString(from: decibles) ?? "-"
  314. }
  315. func setDetailAge(_ age: TimeInterval?) {
  316. if let age = age {
  317. detailTextLabel?.text = age.format(using: [.day, .hour, .minute])
  318. } else {
  319. detailTextLabel?.text = ""
  320. }
  321. }
  322. func setDetailFrequency(_ frequency: Measurement<UnitFrequency>?, formatter: MeasurementFormatter) {
  323. if let frequency = frequency {
  324. detailTextLabel?.text = formatter.string(from: frequency)
  325. } else {
  326. detailTextLabel?.text = ""
  327. }
  328. }
  329. }