Swift:BLE无法更新特征

时间:2018-10-25 14:00:23

标签: swift bluetooth bluetooth-lowenergy

我向TX发送了一个0x11字节,但没有任何反应,该功能

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)

从未打电话。这是我的代码..

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    peripheral.delegate = self
    //peripheral.discoverServices(nil)
    peripheral.discoverServices([CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")])
    print("Connected successfully to the device")

    //On stop le scan
    centralManager?.stopScan()
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    print("\n\n\n ✅ READING SERVICES OF PERIPHERAL ❤️ \(peripheral.name!) ❤️")

    for service in peripheral.services! {
        peripheral.discoverCharacteristics(nil, for: service)
        print(service)
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    print("\n\n  READING CHARARCTERISTICS OF  \(service.uuid) ")

    let NORDIC_UART_TX_CHARACTERISTIC = CBUUID(string: "6e400002-b5a3-f393-e0a9-e50e24dcca9e")
    let NORDIC_UART_RX_CHARACTERISTIC = CBUUID(string: "6e400003-b5a3-f393-e0a9-e50e24dcca9e")

    for characteristic in service.characteristics! {
            // Tx:
            if characteristic.uuid == NORDIC_UART_TX_CHARACTERISTIC {
                print("Tx char found: \(characteristic.uuid)")
                let command:[UInt8] = [0x11]
                let sendData: Data = Data(command)

                peripheral.writeValue(sendData, for: characteristic, type:.withResponse)
            }

            // Rx:
            if characteristic.uuid == NORDIC_UART_RX_CHARACTERISTIC {
                    print("Rx char found: \(characteristic.uuid)")
                peripheral.setNotifyValue(true, for: characteristic)
            }
    }
}

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?){
    print("characteristic changed: \(characteristic)")
}

1 个答案:

答案 0 :(得分:0)

您还没有链接任何文档,但是从名称来看,我假设这是一个串行协议。您可以在Tx特性上写,在Rx上读。我还假设文档中说您应该在编写0x11之后得到响应。您期望得到什么? (这是一条奇怪的UART消息。通常,它们使用ASCII格式,并且通常\ n终止。文档在哪里?)

也就是说,问题可能出在开始观察Rx特性之前,您正在写Tx特性。那意味着流程是这样的:

  • 将0x11发送到Tx。设备接受0x11。
  • 订阅Rx。设备接受该请求,并会在Rx上通知您下一次更改。
  • 什么都没发生。

在发送Tx之前,您需要确保发现所有特征并订阅Rx。