委托方法没有被调用? (CoreBluetooth)

时间:2016-06-23 22:10:47

标签: swift core-bluetooth

我在Swift 3中使用CoreBluetooth来模拟BTLE的串口。该服务对于中央设备是可见的,并且任何更新外围设备(快速)端都在更新中心侧而没有问题。

当我从中心侧发送读取或写入请求时,其中一个peripheralManager()委托方法应该处理该事件;然而,无论发生什么事都没有调用任何委托方法,中央设备最终会失去它的连接(由于超时,我相信)。

class BTConnectionHandler: NSObject, CBPeripheralManagerDelegate {

var cbManager: CBPeripheralManager!

var serialService: CBMutableService!
var tx: CBMutableCharacteristic!
var rx: CBMutableCharacteristic!

override init() {

    super.init()

    cbManager = CBPeripheralManager(delegate: self, queue: nil)
    cbManager.startAdvertising(ADVERTISEMENT_DATA)

    serialService = CBMutableService(type: SERIAL_UUID, primary: true)
    tx = CBMutableCharacteristic(type: TX_UUID, properties: TX_PROPERTIES, value: nil, permissions: TX_PERMISSIONS)
    rx = CBMutableCharacteristic(type: RX_UUID, properties: RX_PROPERTIES, value: nil, permissions: RX_PERMISSIONS)
    serialService.characteristics = [tx,rx]

    cbManager.add(serialService)

}

// PERIPHERAL (this) Write to TX
internal func write(string: String) -> Bool {
    let data = string.data(using: String.Encoding.utf8)!
    tx.value = data
    return cbManager.updateValue(data,for: tx,onSubscribedCentrals: nil)
}

// PERIPHERAL (this) Read from RX
internal func read() -> String? {
    if let outString = String(data: rx.value!, encoding: String.Encoding.utf8) {
        return outString
    } else {
        print("RX buffer is empty")
        return nil
    }
}

// CENTRAL read from TX
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
    print("Read request received from central device")
    request.value = tx.value
    cbManager.respond(to: request, withResult: .success)
}

// CENTRAL write to RX
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
    print("Write request(s) received from central device")
    for request in requests {
        rx.value = request.value
        cbManager.respond(to: request, withResult: .success)
    }
}

// Print state of peripheral manager as it changes
func peripheralManagerDidUpdateState(_ peripheral:CBPeripheralManager) {

   print(peripheral.state)

}


}

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题让我难倒了好几个小时。 我的问题是属性。一旦我添加.read属性,就会调用didReceiveRead回调:

myCharacteristic = CBMutableCharacteristic(
    type: myUUID,
    properties: [CBCharacteristicProperties.notify, CBCharacteristicProperties.read], //*** Need Read Permission to READ!!
    value: nil,
    permissions: CBAttributePermissions.readEncryptionRequired
)