PeripheralManager.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //
  2. // PeripheralManager.swift
  3. // xDripG5
  4. //
  5. // Copyright © 2017 LoopKit Authors. All rights reserved.
  6. //
  7. import CoreBluetooth
  8. import Foundation
  9. import os.log
  10. class PeripheralManager: NSObject {
  11. private let log = OSLog(category: "PeripheralManager")
  12. ///
  13. /// This is mutable, because CBPeripheral instances can seemingly become invalid, and need to be periodically re-fetched from CBCentralManager
  14. var peripheral: CBPeripheral {
  15. didSet {
  16. guard oldValue !== peripheral else {
  17. return
  18. }
  19. log.error("Replacing peripheral reference %{public}@ -> %{public}@", oldValue, peripheral)
  20. oldValue.delegate = nil
  21. peripheral.delegate = self
  22. queue.sync {
  23. self.needsConfiguration = true
  24. }
  25. }
  26. }
  27. /// The dispatch queue used to serialize operations on the peripheral
  28. let queue: DispatchQueue
  29. /// The condition used to signal command completion
  30. private let commandLock = NSCondition()
  31. /// The required conditions for the operation to complete
  32. private var commandConditions = [CommandCondition]()
  33. /// Any error surfaced during the active operation
  34. private var commandError: Error?
  35. private(set) weak var central: CBCentralManager?
  36. let configuration: Configuration
  37. // Confined to `queue`
  38. private var needsConfiguration = true
  39. weak var delegate: PeripheralManagerDelegate? {
  40. didSet {
  41. queue.sync {
  42. needsConfiguration = true
  43. }
  44. }
  45. }
  46. // Called from RileyLinkDeviceManager.managerQueue
  47. init(peripheral: CBPeripheral, configuration: Configuration, centralManager: CBCentralManager, queue: DispatchQueue) {
  48. self.peripheral = peripheral
  49. self.central = centralManager
  50. self.configuration = configuration
  51. self.queue = queue
  52. super.init()
  53. peripheral.delegate = self
  54. assertConfiguration()
  55. }
  56. }
  57. // MARK: - Nested types
  58. extension PeripheralManager {
  59. struct Configuration {
  60. var serviceCharacteristics: [CBUUID: [CBUUID]] = [:]
  61. var notifyingCharacteristics: [CBUUID: [CBUUID]] = [:]
  62. var valueUpdateMacros: [CBUUID: (_ manager: PeripheralManager) -> Void] = [:]
  63. }
  64. enum CommandCondition {
  65. case notificationStateUpdate(characteristic: CBCharacteristic, enabled: Bool)
  66. case valueUpdate(characteristic: CBCharacteristic, matching: ((Data?) -> Bool)?)
  67. case write(characteristic: CBCharacteristic)
  68. case discoverServices
  69. case discoverCharacteristicsForService(serviceUUID: CBUUID)
  70. }
  71. }
  72. protocol PeripheralManagerDelegate: AnyObject {
  73. func peripheralManager(_ manager: PeripheralManager, didUpdateValueFor characteristic: CBCharacteristic)
  74. func peripheralManager(_ manager: PeripheralManager, didUpdateNotificationStateFor characteristic: CBCharacteristic)
  75. func peripheralManager(_ manager: PeripheralManager, didReadRSSI RSSI: NSNumber, error: Error?)
  76. func peripheralManagerDidUpdateName(_ manager: PeripheralManager)
  77. func completeConfiguration(for manager: PeripheralManager) throws
  78. }
  79. // MARK: - Operation sequence management
  80. extension PeripheralManager {
  81. func configureAndRun(_ block: @escaping (_ manager: PeripheralManager) -> Void) -> (() -> Void) {
  82. return {
  83. if self.needsConfiguration || self.peripheral.services == nil {
  84. self.log.default("Configuring peripheral %{public}@, needsConfiguration=%{public}@, has services = %{public}@", self.peripheral, String(describing: self.needsConfiguration), String(describing: self.peripheral.services != nil))
  85. do {
  86. try self.applyConfiguration()
  87. self.log.default("Peripheral configuration completed: %{public}@", self.peripheral)
  88. } catch let error {
  89. self.log.error("Error applying peripheral configuration: %{public}@", String(describing: error))
  90. // Will retry
  91. }
  92. do {
  93. if let delegate = self.delegate {
  94. try delegate.completeConfiguration(for: self)
  95. self.log.default("Delegate configuration completed")
  96. self.needsConfiguration = false
  97. } else {
  98. self.log.error("No delegate set for configuration")
  99. }
  100. } catch let error {
  101. self.log.error("Error applying delegate configuration: %{public}@", String(describing: error))
  102. // Will retry
  103. }
  104. }
  105. block(self)
  106. }
  107. }
  108. func perform(_ block: @escaping (_ manager: PeripheralManager) -> Void) {
  109. queue.async(execute: configureAndRun(block))
  110. }
  111. private func assertConfiguration() {
  112. if peripheral.state == .connected {
  113. perform { (_) in
  114. // Intentionally empty to trigger configuration if necessary
  115. }
  116. }
  117. }
  118. private func applyConfiguration(discoveryTimeout: TimeInterval = 2) throws {
  119. try discoverServices(configuration.serviceCharacteristics.keys.map { $0 }, timeout: discoveryTimeout)
  120. for service in peripheral.services ?? [] {
  121. guard let characteristics = configuration.serviceCharacteristics[service.uuid] else {
  122. // Not all services have characteristics
  123. continue
  124. }
  125. try discoverCharacteristics(characteristics, for: service, timeout: discoveryTimeout)
  126. }
  127. // Subscribe to notifying characteristics
  128. for (serviceUUID, characteristicUUIDs) in configuration.notifyingCharacteristics {
  129. guard let service = peripheral.services?.itemWithUUID(serviceUUID) else {
  130. // Not all RL's have OrangeLink service
  131. continue
  132. }
  133. for characteristicUUID in characteristicUUIDs {
  134. guard let characteristic = service.characteristics?.itemWithUUID(characteristicUUID) else {
  135. throw PeripheralManagerError.unknownCharacteristic(characteristicUUID)
  136. }
  137. guard !characteristic.isNotifying else {
  138. continue
  139. }
  140. try setNotifyValue(true, for: characteristic, timeout: discoveryTimeout)
  141. }
  142. }
  143. }
  144. }
  145. // MARK: - Synchronous Commands
  146. extension PeripheralManager {
  147. /// - Throws: PeripheralManagerError
  148. func runCommand(timeout: TimeInterval, command: () -> Void) throws {
  149. // Prelude
  150. dispatchPrecondition(condition: .onQueue(queue))
  151. guard central?.state == .poweredOn && peripheral.state == .connected else {
  152. throw PeripheralManagerError.notReady
  153. }
  154. commandLock.lock()
  155. defer {
  156. commandLock.unlock()
  157. }
  158. guard commandConditions.isEmpty else {
  159. throw PeripheralManagerError.busy
  160. }
  161. // Run
  162. command()
  163. guard !commandConditions.isEmpty else {
  164. // If the command didn't add any conditions, then finish immediately
  165. return
  166. }
  167. // Postlude
  168. let signaled = commandLock.wait(until: Date(timeIntervalSinceNow: timeout))
  169. defer {
  170. commandError = nil
  171. commandConditions = []
  172. }
  173. guard signaled else {
  174. throw PeripheralManagerError.timeout(commandConditions)
  175. }
  176. if let error = commandError {
  177. throw PeripheralManagerError.cbPeripheralError(error)
  178. }
  179. }
  180. /// It's illegal to call this without first acquiring the commandLock
  181. ///
  182. /// - Parameter condition: The condition to add
  183. func addCondition(_ condition: CommandCondition) {
  184. dispatchPrecondition(condition: .onQueue(queue))
  185. commandConditions.append(condition)
  186. }
  187. func discoverServices(_ serviceUUIDs: [CBUUID], timeout: TimeInterval) throws {
  188. let servicesToDiscover = peripheral.servicesToDiscover(from: serviceUUIDs)
  189. guard servicesToDiscover.count > 0 else {
  190. return
  191. }
  192. try runCommand(timeout: timeout) {
  193. addCondition(.discoverServices)
  194. peripheral.discoverServices(serviceUUIDs)
  195. }
  196. }
  197. func discoverCharacteristics(_ characteristicUUIDs: [CBUUID], for service: CBService, timeout: TimeInterval) throws {
  198. let characteristicsToDiscover = peripheral.characteristicsToDiscover(from: characteristicUUIDs, for: service)
  199. guard characteristicsToDiscover.count > 0 else {
  200. return
  201. }
  202. try runCommand(timeout: timeout) {
  203. addCondition(.discoverCharacteristicsForService(serviceUUID: service.uuid))
  204. peripheral.discoverCharacteristics(characteristicsToDiscover, for: service)
  205. }
  206. }
  207. /// - Throws: PeripheralManagerError
  208. func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic, timeout: TimeInterval) throws {
  209. try runCommand(timeout: timeout) {
  210. addCondition(.notificationStateUpdate(characteristic: characteristic, enabled: enabled))
  211. peripheral.setNotifyValue(enabled, for: characteristic)
  212. }
  213. }
  214. /// - Throws: PeripheralManagerError
  215. func readValue(for characteristic: CBCharacteristic, timeout: TimeInterval) throws -> Data? {
  216. try runCommand(timeout: timeout) {
  217. addCondition(.valueUpdate(characteristic: characteristic, matching: nil))
  218. peripheral.readValue(for: characteristic)
  219. }
  220. return characteristic.value
  221. }
  222. /// - Throws: PeripheralManagerError
  223. func writeValue(_ value: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType, timeout: TimeInterval) throws {
  224. try runCommand(timeout: timeout) {
  225. if case .withResponse = type {
  226. addCondition(.write(characteristic: characteristic))
  227. }
  228. peripheral.writeValue(value, for: characteristic, type: type)
  229. }
  230. }
  231. }
  232. // MARK: - Delegate methods executed on the central's queue
  233. extension PeripheralManager: CBPeripheralDelegate {
  234. func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
  235. commandLock.lock()
  236. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  237. if case .discoverServices = condition {
  238. return true
  239. } else {
  240. return false
  241. }
  242. }) {
  243. commandConditions.remove(at: index)
  244. commandError = error
  245. if commandConditions.isEmpty {
  246. commandLock.broadcast()
  247. }
  248. }
  249. commandLock.unlock()
  250. }
  251. func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
  252. commandLock.lock()
  253. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  254. if case .discoverCharacteristicsForService(serviceUUID: service.uuid) = condition {
  255. return true
  256. } else {
  257. return false
  258. }
  259. }) {
  260. commandConditions.remove(at: index)
  261. commandError = error
  262. if commandConditions.isEmpty {
  263. commandLock.broadcast()
  264. }
  265. }
  266. commandLock.unlock()
  267. }
  268. func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
  269. commandLock.lock()
  270. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  271. if case .notificationStateUpdate(characteristic: characteristic, enabled: characteristic.isNotifying) = condition {
  272. return true
  273. } else {
  274. return false
  275. }
  276. }) {
  277. commandConditions.remove(at: index)
  278. commandError = error
  279. if commandConditions.isEmpty {
  280. commandLock.broadcast()
  281. }
  282. }
  283. commandLock.unlock()
  284. delegate?.peripheralManager(self, didUpdateNotificationStateFor: characteristic)
  285. }
  286. func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
  287. commandLock.lock()
  288. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  289. if case .write(characteristic: characteristic) = condition {
  290. return true
  291. } else {
  292. return false
  293. }
  294. }) {
  295. commandConditions.remove(at: index)
  296. commandError = error
  297. if commandConditions.isEmpty {
  298. commandLock.broadcast()
  299. }
  300. }
  301. commandLock.unlock()
  302. }
  303. func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
  304. commandLock.lock()
  305. var notifyDelegate = false
  306. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  307. if case .valueUpdate(characteristic: characteristic, matching: let matching) = condition {
  308. return matching?(characteristic.value) ?? true
  309. } else {
  310. return false
  311. }
  312. }) {
  313. commandConditions.remove(at: index)
  314. commandError = error
  315. if commandConditions.isEmpty {
  316. commandLock.broadcast()
  317. }
  318. } else if let macro = configuration.valueUpdateMacros[characteristic.uuid] {
  319. macro(self)
  320. } else {
  321. notifyDelegate = true // execute after the unlock
  322. }
  323. commandLock.unlock()
  324. if notifyDelegate {
  325. // If we weren't expecting this notification, pass it along to the delegate
  326. delegate?.peripheralManager(self, didUpdateValueFor: characteristic)
  327. }
  328. }
  329. func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
  330. delegate?.peripheralManager(self, didReadRSSI: RSSI, error: error)
  331. }
  332. func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
  333. delegate?.peripheralManagerDidUpdateName(self)
  334. }
  335. }
  336. extension PeripheralManager: CBCentralManagerDelegate {
  337. func centralManagerDidUpdateState(_ central: CBCentralManager) {
  338. switch central.state {
  339. case .poweredOn:
  340. assertConfiguration()
  341. default:
  342. break
  343. }
  344. }
  345. func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
  346. switch peripheral.state {
  347. case .connected:
  348. assertConfiguration()
  349. default:
  350. break
  351. }
  352. }
  353. }
  354. extension PeripheralManager {
  355. public override var debugDescription: String {
  356. var items = [
  357. "## PeripheralManager",
  358. "peripheral: \(peripheral)"
  359. ]
  360. queue.sync {
  361. items.append("needsConfiguration: \(needsConfiguration)")
  362. }
  363. return items.joined(separator: "\n")
  364. }
  365. }