RileyLinkDeviceTableViewController.swift 14 KB

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