PeripheralManager.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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: class {
  73. func peripheralManager(_ manager: PeripheralManager, didUpdateValueFor characteristic: CBCharacteristic)
  74. func peripheralManager(_ manager: PeripheralManager, didReadRSSI RSSI: NSNumber, error: Error?)
  75. func peripheralManagerDidUpdateName(_ manager: PeripheralManager)
  76. func completeConfiguration(for manager: PeripheralManager) throws
  77. }
  78. // MARK: - Operation sequence management
  79. extension PeripheralManager {
  80. func configureAndRun(_ block: @escaping (_ manager: PeripheralManager) -> Void) -> (() -> Void) {
  81. return {
  82. // TODO: Accessing self might be a race on initialization
  83. if !self.needsConfiguration && self.peripheral.services == nil {
  84. self.log.error("Configured peripheral has no services. Reconfiguring…")
  85. }
  86. if self.needsConfiguration || self.peripheral.services == nil {
  87. do {
  88. try self.applyConfiguration()
  89. self.log.default("Peripheral configuration completed")
  90. } catch let error {
  91. self.log.error("Error applying peripheral configuration: %@", String(describing: error))
  92. // Will retry
  93. }
  94. do {
  95. if let delegate = self.delegate {
  96. try delegate.completeConfiguration(for: self)
  97. self.log.default("Delegate configuration completed")
  98. self.needsConfiguration = false
  99. } else {
  100. self.log.error("No delegate set for configuration")
  101. }
  102. } catch let error {
  103. self.log.error("Error applying delegate configuration: %@", String(describing: error))
  104. // Will retry
  105. }
  106. }
  107. block(self)
  108. }
  109. }
  110. func perform(_ block: @escaping (_ manager: PeripheralManager) -> Void) {
  111. queue.async(execute: configureAndRun(block))
  112. }
  113. private func assertConfiguration() {
  114. perform { (_) in
  115. // Intentionally empty to trigger configuration if necessary
  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 may have characteristics
  123. continue
  124. }
  125. try discoverCharacteristics(characteristics, for: service, timeout: discoveryTimeout)
  126. }
  127. for (serviceUUID, characteristicUUIDs) in configuration.notifyingCharacteristics {
  128. guard let service = peripheral.services?.itemWithUUID(serviceUUID) else {
  129. throw PeripheralManagerError.unknownCharacteristic
  130. }
  131. for characteristicUUID in characteristicUUIDs {
  132. guard let characteristic = service.characteristics?.itemWithUUID(characteristicUUID) else {
  133. throw PeripheralManagerError.unknownCharacteristic
  134. }
  135. guard !characteristic.isNotifying else {
  136. continue
  137. }
  138. try setNotifyValue(true, for: characteristic, timeout: discoveryTimeout)
  139. }
  140. }
  141. }
  142. }
  143. // MARK: - Synchronous Commands
  144. extension PeripheralManager {
  145. /// - Throws: PeripheralManagerError
  146. func runCommand(timeout: TimeInterval, command: () -> Void) throws {
  147. // Prelude
  148. dispatchPrecondition(condition: .onQueue(queue))
  149. guard central?.state == .poweredOn && peripheral.state == .connected else {
  150. throw PeripheralManagerError.notReady
  151. }
  152. commandLock.lock()
  153. defer {
  154. commandLock.unlock()
  155. }
  156. guard commandConditions.isEmpty else {
  157. throw PeripheralManagerError.notReady
  158. }
  159. // Run
  160. command()
  161. guard !commandConditions.isEmpty else {
  162. // If the command didn't add any conditions, then finish immediately
  163. return
  164. }
  165. // Postlude
  166. let signaled = commandLock.wait(until: Date(timeIntervalSinceNow: timeout))
  167. defer {
  168. commandError = nil
  169. commandConditions = []
  170. }
  171. guard signaled else {
  172. throw PeripheralManagerError.timeout
  173. }
  174. if let error = commandError {
  175. throw PeripheralManagerError.cbPeripheralError(error)
  176. }
  177. }
  178. /// It's illegal to call this without first acquiring the commandLock
  179. ///
  180. /// - Parameter condition: The condition to add
  181. func addCondition(_ condition: CommandCondition) {
  182. dispatchPrecondition(condition: .onQueue(queue))
  183. commandConditions.append(condition)
  184. }
  185. func discoverServices(_ serviceUUIDs: [CBUUID], timeout: TimeInterval) throws {
  186. let servicesToDiscover = peripheral.servicesToDiscover(from: serviceUUIDs)
  187. guard servicesToDiscover.count > 0 else {
  188. return
  189. }
  190. try runCommand(timeout: timeout) {
  191. addCondition(.discoverServices)
  192. peripheral.discoverServices(serviceUUIDs)
  193. }
  194. }
  195. func discoverCharacteristics(_ characteristicUUIDs: [CBUUID], for service: CBService, timeout: TimeInterval) throws {
  196. let characteristicsToDiscover = peripheral.characteristicsToDiscover(from: characteristicUUIDs, for: service)
  197. guard characteristicsToDiscover.count > 0 else {
  198. return
  199. }
  200. try runCommand(timeout: timeout) {
  201. addCondition(.discoverCharacteristicsForService(serviceUUID: service.uuid))
  202. peripheral.discoverCharacteristics(characteristicsToDiscover, for: service)
  203. }
  204. }
  205. /// - Throws: PeripheralManagerError
  206. func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic, timeout: TimeInterval) throws {
  207. try runCommand(timeout: timeout) {
  208. addCondition(.notificationStateUpdate(characteristic: characteristic, enabled: enabled))
  209. peripheral.setNotifyValue(enabled, for: characteristic)
  210. }
  211. }
  212. /// - Throws: PeripheralManagerError
  213. func readValue(for characteristic: CBCharacteristic, timeout: TimeInterval) throws -> Data? {
  214. try runCommand(timeout: timeout) {
  215. addCondition(.valueUpdate(characteristic: characteristic, matching: nil))
  216. peripheral.readValue(for: characteristic)
  217. }
  218. return characteristic.value
  219. }
  220. /// - Throws: PeripheralManagerError
  221. func wait(for characteristic: CBCharacteristic, timeout: TimeInterval) throws -> Data {
  222. try runCommand(timeout: timeout) {
  223. addCondition(.valueUpdate(characteristic: characteristic, matching: nil))
  224. }
  225. guard let value = characteristic.value else {
  226. throw PeripheralManagerError.timeout
  227. }
  228. return value
  229. }
  230. /// - Throws: PeripheralManagerError
  231. func writeValue(_ value: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType, timeout: TimeInterval) throws {
  232. try runCommand(timeout: timeout) {
  233. if case .withResponse = type {
  234. addCondition(.write(characteristic: characteristic))
  235. }
  236. peripheral.writeValue(value, for: characteristic, type: type)
  237. }
  238. }
  239. }
  240. // MARK: - Delegate methods executed on the central's queue
  241. extension PeripheralManager: CBPeripheralDelegate {
  242. func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
  243. commandLock.lock()
  244. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  245. if case .discoverServices = condition {
  246. return true
  247. } else {
  248. return false
  249. }
  250. }) {
  251. commandConditions.remove(at: index)
  252. commandError = error
  253. if commandConditions.isEmpty {
  254. commandLock.broadcast()
  255. }
  256. }
  257. commandLock.unlock()
  258. }
  259. func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
  260. commandLock.lock()
  261. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  262. if case .discoverCharacteristicsForService(serviceUUID: service.uuid) = condition {
  263. return true
  264. } else {
  265. return false
  266. }
  267. }) {
  268. commandConditions.remove(at: index)
  269. commandError = error
  270. if commandConditions.isEmpty {
  271. commandLock.broadcast()
  272. }
  273. }
  274. commandLock.unlock()
  275. }
  276. func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
  277. commandLock.lock()
  278. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  279. if case .notificationStateUpdate(characteristic: characteristic, enabled: characteristic.isNotifying) = condition {
  280. return true
  281. } else {
  282. return false
  283. }
  284. }) {
  285. commandConditions.remove(at: index)
  286. commandError = error
  287. if commandConditions.isEmpty {
  288. commandLock.broadcast()
  289. }
  290. }
  291. commandLock.unlock()
  292. }
  293. func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
  294. commandLock.lock()
  295. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  296. if case .write(characteristic: characteristic) = condition {
  297. return true
  298. } else {
  299. return false
  300. }
  301. }) {
  302. commandConditions.remove(at: index)
  303. commandError = error
  304. if commandConditions.isEmpty {
  305. commandLock.broadcast()
  306. }
  307. }
  308. commandLock.unlock()
  309. }
  310. func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
  311. commandLock.lock()
  312. var notifyDelegate = false
  313. if let index = commandConditions.firstIndex(where: { (condition) -> Bool in
  314. if case .valueUpdate(characteristic: characteristic, matching: let matching) = condition {
  315. return matching?(characteristic.value) ?? true
  316. } else {
  317. return false
  318. }
  319. }) {
  320. commandConditions.remove(at: index)
  321. commandError = error
  322. if commandConditions.isEmpty {
  323. commandLock.broadcast()
  324. }
  325. } else if let macro = configuration.valueUpdateMacros[characteristic.uuid] {
  326. macro(self)
  327. } else if commandConditions.isEmpty {
  328. notifyDelegate = true // execute after the unlock
  329. }
  330. commandLock.unlock()
  331. if notifyDelegate {
  332. // If we weren't expecting this notification, pass it along to the delegate
  333. delegate?.peripheralManager(self, didUpdateValueFor: characteristic)
  334. }
  335. }
  336. func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
  337. delegate?.peripheralManager(self, didReadRSSI: RSSI, error: error)
  338. }
  339. func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
  340. delegate?.peripheralManagerDidUpdateName(self)
  341. }
  342. }
  343. extension PeripheralManager: CBCentralManagerDelegate {
  344. func centralManagerDidUpdateState(_ central: CBCentralManager) {
  345. switch central.state {
  346. case .poweredOn:
  347. assertConfiguration()
  348. default:
  349. break
  350. }
  351. }
  352. func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
  353. switch peripheral.state {
  354. case .connected:
  355. assertConfiguration()
  356. default:
  357. break
  358. }
  359. }
  360. }
  361. extension PeripheralManager {
  362. public override var debugDescription: String {
  363. var items = [
  364. "## PeripheralManager",
  365. "peripheral: \(peripheral)",
  366. ]
  367. queue.sync {
  368. items.append("needsConfiguration: \(needsConfiguration)")
  369. }
  370. return items.joined(separator: "\n")
  371. }
  372. }