G7PeripheralManager.swift 18 KB

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