RileyLinkDevicesTableViewDataSource.swift 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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.rileyLinkConnectionManager?.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. guard let connectionManager = rileyLinkPumpManager.rileyLinkConnectionManager else {
  73. return nil
  74. }
  75. let isAutoConnectDevice = connectionManager.shouldConnect(to: device.peripheralIdentifier.uuidString)
  76. var state = device.peripheralState
  77. switch state {
  78. case .disconnected, .disconnecting:
  79. break
  80. case .connecting, .connected:
  81. if !isAutoConnectDevice {
  82. state = .disconnected
  83. }
  84. @unknown default:
  85. break
  86. }
  87. return state
  88. }
  89. private var deviceRSSI: [UUID: Int] = [:]
  90. private var rssiFetchTimer: Timer? {
  91. willSet {
  92. rssiFetchTimer?.invalidate()
  93. }
  94. }
  95. @objc private func reloadDevices() {
  96. rileyLinkPumpManager.rileyLinkDeviceProvider.getDevices { (devices) in
  97. DispatchQueue.main.async { [weak self] in
  98. self?.devices = devices
  99. }
  100. }
  101. }
  102. @objc private func deviceDidUpdate(_ note: Notification) {
  103. DispatchQueue.main.async {
  104. if let device = note.object as? RileyLinkDevice, let index = self.devices.firstIndex(where: { $0 === device }) {
  105. if let rssi = note.userInfo?[RileyLinkDevice.notificationRSSIKey] as? Int {
  106. self.deviceRSSI[device.peripheralIdentifier] = rssi
  107. }
  108. if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: self.devicesSectionIndex)) as? RileyLinkDeviceTableViewCell {
  109. cell.configureCellWithName(
  110. device.name,
  111. signal: self.decimalFormatter.decibleString(from: self.deviceRSSI[device.peripheralIdentifier]),
  112. peripheralState: self.preferenceStateForDevice(device)
  113. )
  114. }
  115. }
  116. }
  117. }
  118. @objc public func updateRSSI() {
  119. for device in devices {
  120. device.readRSSI()
  121. }
  122. }
  123. @objc private func deviceConnectionChanged(_ connectSwitch: UISwitch) {
  124. let switchOrigin = connectSwitch.convert(CGPoint.zero, to: tableView)
  125. if let indexPath = tableView.indexPathForRow(at: switchOrigin), indexPath.section == devicesSectionIndex
  126. {
  127. let device = devices[indexPath.row]
  128. if connectSwitch.isOn {
  129. rileyLinkPumpManager.connectToRileyLink(device)
  130. } else {
  131. rileyLinkPumpManager.disconnectFromRileyLink(device)
  132. }
  133. }
  134. }
  135. }
  136. extension RileyLinkDevicesTableViewDataSource: UITableViewDataSource {
  137. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  138. return devices.count
  139. }
  140. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  141. let deviceCell = tableView.dequeueReusableCell(withIdentifier: RileyLinkDeviceTableViewCell.className) as! RileyLinkDeviceTableViewCell
  142. let device = devices[indexPath.row]
  143. deviceCell.configureCellWithName(
  144. device.name,
  145. signal: decimalFormatter.decibleString(from: deviceRSSI[device.peripheralIdentifier]),
  146. peripheralState: self.preferenceStateForDevice(device)
  147. )
  148. deviceCell.connectSwitch?.addTarget(self, action: #selector(deviceConnectionChanged(_:)), for: .valueChanged)
  149. return deviceCell
  150. }
  151. public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  152. return LocalizedString("Devices", comment: "The title of the devices table section in RileyLink settings")
  153. }
  154. }
  155. extension RileyLinkDevicesTableViewDataSource: UITableViewDelegate {
  156. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  157. return tableView.dequeueReusableHeaderFooterView(withIdentifier: RileyLinkDevicesHeaderView.className)
  158. }
  159. public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  160. return 44
  161. }
  162. public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  163. return UITableView.automaticDimension
  164. }
  165. public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
  166. return 55
  167. }
  168. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  169. return UITableView.automaticDimension
  170. }
  171. }