RileyLinkDevicesTableViewDataSource.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. //
  2. // RileyLinkDevicesTableViewDataSource.swift
  3. // RileyLinkKitUI
  4. //
  5. // Copyright © 2018 Pete Schwamb. All rights reserved.
  6. //
  7. import UIKit
  8. import CoreBluetooth
  9. import RileyLinkBLEKit
  10. import RileyLinkKit
  11. public class RileyLinkDevicesTableViewDataSource: NSObject {
  12. public let rileyLinkPumpManager: RileyLinkPumpManager
  13. public var devicesSectionIndex: Int
  14. public var tableView: UITableView! {
  15. didSet {
  16. tableView.register(RileyLinkDeviceTableViewCell.self, forCellReuseIdentifier: RileyLinkDeviceTableViewCell.className)
  17. tableView.register(RileyLinkDevicesHeaderView.self, forHeaderFooterViewReuseIdentifier: RileyLinkDevicesHeaderView.className)
  18. // Register for manager notifications
  19. NotificationCenter.default.addObserver(self, selector: #selector(reloadDevices), name: .ManagerDevicesDidChange, object: rileyLinkPumpManager.rileyLinkDeviceProvider)
  20. // Register for device notifications
  21. for name in [.DeviceConnectionStateDidChange, .DeviceRSSIDidChange, .DeviceNameDidChange] as [Notification.Name] {
  22. NotificationCenter.default.addObserver(self, selector: #selector(deviceDidUpdate(_:)), name: name, object: nil)
  23. }
  24. reloadDevices()
  25. }
  26. }
  27. public init(rileyLinkPumpManager: RileyLinkPumpManager, devicesSectionIndex: Int) {
  28. self.rileyLinkPumpManager = rileyLinkPumpManager
  29. self.devicesSectionIndex = devicesSectionIndex
  30. super.init()
  31. }
  32. // MARK: -
  33. lazy var decimalFormatter: NumberFormatter = {
  34. let formatter = NumberFormatter()
  35. formatter.numberStyle = .decimal
  36. formatter.minimumFractionDigits = 0
  37. formatter.maximumFractionDigits = 2
  38. return formatter
  39. }()
  40. public var isScanningEnabled: Bool = false {
  41. didSet {
  42. rileyLinkPumpManager.rileyLinkDeviceProvider.setScanningEnabled(isScanningEnabled)
  43. if isScanningEnabled {
  44. rssiFetchTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(updateRSSI), userInfo: nil, repeats: true)
  45. updateRSSI()
  46. } else {
  47. rssiFetchTimer = nil
  48. }
  49. }
  50. }
  51. private(set) public var devices: [RileyLinkDevice] = [] {
  52. didSet {
  53. // Assume only appends are possible when count changes for algorithmic simplicity
  54. guard oldValue.count < devices.count else {
  55. tableView.reloadSections(IndexSet(integer: devicesSectionIndex), with: .fade)
  56. return
  57. }
  58. tableView.beginUpdates()
  59. let insertedPaths = (oldValue.count..<devices.count).map { (index) -> IndexPath in
  60. return IndexPath(row: index, section: devicesSectionIndex)
  61. }
  62. tableView.insertRows(at: insertedPaths, with: .automatic)
  63. tableView.endUpdates()
  64. }
  65. }
  66. /// Returns an adjusted peripheral state reflecting the user's auto-connect preference.
  67. /// Peripherals connected to the system will show as disconnected if the user hasn't designated them
  68. ///
  69. /// - Parameter device: The peripheral
  70. /// - Returns: The adjusted connection state
  71. private func preferenceStateForDevice(_ device: RileyLinkDevice) -> CBPeripheralState? {
  72. let isAutoConnectDevice = rileyLinkPumpManager.rileyLinkDeviceProvider.shouldConnect(to: device.peripheralIdentifier.uuidString)
  73. var state = device.peripheralState
  74. switch state {
  75. case .disconnected, .disconnecting:
  76. break
  77. case .connecting, .connected:
  78. if !isAutoConnectDevice {
  79. state = .disconnected
  80. }
  81. @unknown default:
  82. break
  83. }
  84. return state
  85. }
  86. private var deviceRSSI: [UUID: Int] = [:]
  87. private var rssiFetchTimer: Timer? {
  88. willSet {
  89. rssiFetchTimer?.invalidate()
  90. }
  91. }
  92. @objc private func reloadDevices() {
  93. rileyLinkPumpManager.rileyLinkDeviceProvider.getDevices { (devices) in
  94. DispatchQueue.main.async { [weak self] in
  95. self?.devices = devices
  96. }
  97. }
  98. }
  99. @objc private func deviceDidUpdate(_ note: Notification) {
  100. DispatchQueue.main.async {
  101. if let device = note.object as? RileyLinkDevice, let index = self.devices.firstIndex(where: { $0.peripheralIdentifier == device.peripheralIdentifier }) {
  102. if let rssi = note.userInfo?[RileyLinkBluetoothDevice.notificationRSSIKey] as? Int {
  103. self.deviceRSSI[device.peripheralIdentifier] = rssi
  104. }
  105. if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: self.devicesSectionIndex)) as? RileyLinkDeviceTableViewCell {
  106. cell.configureCellWithName(
  107. device.name,
  108. signal: self.decimalFormatter.decibleString(from: self.deviceRSSI[device.peripheralIdentifier]),
  109. peripheralState: self.preferenceStateForDevice(device)
  110. )
  111. }
  112. }
  113. }
  114. }
  115. @objc public func updateRSSI() {
  116. for device in devices {
  117. device.readRSSI()
  118. }
  119. }
  120. @objc private func deviceConnectionChanged(_ connectSwitch: UISwitch) {
  121. let switchOrigin = connectSwitch.convert(CGPoint.zero, to: tableView)
  122. if let indexPath = tableView.indexPathForRow(at: switchOrigin), indexPath.section == devicesSectionIndex
  123. {
  124. let device = devices[indexPath.row]
  125. if connectSwitch.isOn {
  126. rileyLinkPumpManager.connectToRileyLink(device)
  127. } else {
  128. rileyLinkPumpManager.disconnectFromRileyLink(device)
  129. }
  130. }
  131. }
  132. }
  133. extension RileyLinkDevicesTableViewDataSource: UITableViewDataSource {
  134. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  135. return devices.count
  136. }
  137. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  138. let deviceCell = tableView.dequeueReusableCell(withIdentifier: RileyLinkDeviceTableViewCell.className) as! RileyLinkDeviceTableViewCell
  139. let device = devices[indexPath.row]
  140. deviceCell.configureCellWithName(
  141. device.name,
  142. signal: decimalFormatter.decibleString(from: deviceRSSI[device.peripheralIdentifier]),
  143. peripheralState: self.preferenceStateForDevice(device)
  144. )
  145. deviceCell.connectSwitch?.addTarget(self, action: #selector(deviceConnectionChanged(_:)), for: .valueChanged)
  146. return deviceCell
  147. }
  148. public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  149. return LocalizedString("Devices", comment: "The title of the devices table section in RileyLink settings")
  150. }
  151. }
  152. extension RileyLinkDevicesTableViewDataSource: UITableViewDelegate {
  153. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  154. return tableView.dequeueReusableHeaderFooterView(withIdentifier: RileyLinkDevicesHeaderView.className)
  155. }
  156. public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  157. return 44
  158. }
  159. public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  160. return UITableView.automaticDimension
  161. }
  162. public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
  163. return 55
  164. }
  165. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  166. return UITableView.automaticDimension
  167. }
  168. }