CentralManagerDelegate.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import CoreBluetooth
  2. enum ConnectionChange {
  3. case connected
  4. case failedToConnect(Error?)
  5. case disconnected(Error?)
  6. }
  7. final class CentralManagerDelegate: NSObject, CBCentralManagerDelegate {
  8. typealias StateChangeHandler = (CBManagerState) -> Void
  9. typealias DiscoveryHandler = (CBPeripheral, AdvertisementData, RSSI) -> Void
  10. typealias ConnectionChangeHandler = (CBPeripheral, ConnectionChange) -> Void
  11. private let onStateChange: StateChangeHandler
  12. private let onDiscovery: DiscoveryHandler
  13. private let onConnectionChange: ConnectionChangeHandler
  14. init(
  15. onStateChange: @escaping StateChangeHandler,
  16. onDiscovery: @escaping DiscoveryHandler,
  17. onConnectionChange: @escaping ConnectionChangeHandler
  18. ) {
  19. self.onStateChange = onStateChange
  20. self.onDiscovery = onDiscovery
  21. self.onConnectionChange = onConnectionChange
  22. }
  23. func centralManagerDidUpdateState(_ central: CBCentralManager) {
  24. onStateChange(central.state)
  25. }
  26. func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi: NSNumber) {
  27. onDiscovery(peripheral, advertisementData, rssi.intValue)
  28. }
  29. func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
  30. onConnectionChange(peripheral, .connected)
  31. }
  32. func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
  33. onConnectionChange(peripheral, .failedToConnect(error))
  34. }
  35. func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
  36. onConnectionChange(peripheral, .disconnected(error))
  37. }
  38. }