【问题标题】:Swift: BLE not update characteristicsSwift:BLE 不更新特性
【发布时间】:2019-03-30 04:19:34
【问题描述】:

我向 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)")
}

【问题讨论】:

    标签: swift bluetooth bluetooth-lowenergy


    【解决方案1】:

    您没有链接任何文档,但我从名称中假设这是一个串行协议;您在 Tx 特性上写入并在 Rx 上读取。我还假设文档说您应该在写入 0x11 后得到回复。你期望收到什么? (这是一条奇怪的 UART 消息。通常它们是 ASCII 格式,并且经常被 \n 终止。这方面的文档在哪里?)

    也就是说,问题很可能是您在开始观察 Rx 特性之前就在 Tx 特性上进行了编写。这意味着流程是这样的:

    • 发送 0x11 到 Tx。设备接受 0x11。
    • 订阅 Rx。设备接受这一点,并将通知您 Rx 的下一次更改。
    • 没有其他事情发生。

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

    【讨论】:

    • 我必须写入TX 0x11才能接收电池电量,订阅协议rx是什么意思以及如何操作?
    • 你正在这样做:peripheral.setNotifyValue(true, for: characteristic)。在致电write 之前,您需要确保已完成此操作。
    猜你喜欢
    • 1970-01-01
    • 2016-07-06
    • 2021-12-16
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2021-08-14
    相关资源
    最近更新 更多