PeripheralDelegate.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import CoreBluetooth
  2. final class PeripheralDelegate: NSObject, CBPeripheralDelegate {
  3. typealias ServicesDiscoveryHandler = (CBPeripheral, Error?) -> Void
  4. typealias CharacteristicsDiscoverHandler = (CBService, Error?) -> Void
  5. typealias CharacteristicNotificationStateUpdateHandler = (CBCharacteristic, Error?) -> Void
  6. typealias CharacteristicValueUpdateHandler = (CBCharacteristic, Error?) -> Void
  7. typealias CharacteristicValueWriteHandler = (CBCharacteristic, Error?) -> Void
  8. private let onServicesDiscovery: ServicesDiscoveryHandler
  9. private let onCharacteristicsDiscovery: CharacteristicsDiscoverHandler
  10. private let onCharacteristicNotificationStateUpdate: CharacteristicNotificationStateUpdateHandler
  11. private let onCharacteristicValueUpdate: CharacteristicValueUpdateHandler
  12. private let onCharacteristicValueWrite: CharacteristicValueWriteHandler
  13. init(
  14. onServicesDiscovery: @escaping ServicesDiscoveryHandler,
  15. onCharacteristicsDiscovery: @escaping CharacteristicsDiscoverHandler,
  16. onCharacteristicNotificationStateUpdate: @escaping CharacteristicNotificationStateUpdateHandler,
  17. onCharacteristicValueUpdate: @escaping CharacteristicValueUpdateHandler,
  18. onCharacteristicValueWrite: @escaping CharacteristicValueWriteHandler
  19. ) {
  20. self.onServicesDiscovery = onServicesDiscovery
  21. self.onCharacteristicsDiscovery = onCharacteristicsDiscovery
  22. self.onCharacteristicNotificationStateUpdate = onCharacteristicNotificationStateUpdate
  23. self.onCharacteristicValueUpdate = onCharacteristicValueUpdate
  24. self.onCharacteristicValueWrite = onCharacteristicValueWrite
  25. }
  26. func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
  27. onServicesDiscovery(peripheral, error)
  28. }
  29. func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
  30. onCharacteristicsDiscovery(service, error)
  31. }
  32. func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
  33. onCharacteristicNotificationStateUpdate(characteristic, error)
  34. }
  35. func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
  36. onCharacteristicValueUpdate(characteristic, error)
  37. }
  38. func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
  39. onCharacteristicValueWrite(characteristic, error)
  40. }
  41. }