【问题标题】:Unable to send data to characteristic无法向特征发送数据
【发布时间】:2016-09-20 20:20:22
【问题描述】:

当远程设备更改特征值时,我能够在应用程序上收到通知,但是当应用程序更新回值时,远程设备将看不到它。

所以,我知道我的特征是有效的,我也知道其他应用程序能够写回该特征(实际设备打印它)

所以问题当然出在应用中

更有趣的是每个特征都有handles,每个都有自己的UUID。

iOS 只会让我看到我的特征 UUID,无法访问它的句柄,尽管每个特征有 2 个具有不同 UUID 的句柄

无论如何,我在这里收到回调并尝试回信:

 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    print("UPDATE FROM:" , characteristic) //good!
    sendData(data: "check")  //not good
       if characteristic.uuid.uuidString == characteristicUUID {
         if let str = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)
         {
            print("BLE:GOT:",str )
            NotificationCenter.default.post(name: Notification.Name(rawValue: "Bluetooth"), object: str)
         }
      }
}

和写作:

  func sendData(data:String)
    {
        if(peripheral != nil)
        {
             //happens for sure
            var bytesData = [UInt8](data.utf8)
            let writeData = NSData (bytes: &bytesData, length: bytesData.count)
             peripheral.writeValue(writeData as Data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
        }
    }

并列出我的特征(打印 1 个 UUID - 没错,我们只有 1 个,但它有 2 个具有不同 UUID 的句柄)

  func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        for charateristic in service.characteristics!
        {
               print("Found CHARACTERISTIC:",charateristic as CBCharacteristic)
        }

【问题讨论】:

    标签: ios swift bluetooth-lowenergy


    【解决方案1】:

    您应该检查为您的特征设置了哪些属性。如果设置了CBCharacteristicPropertyWrite,则可以执行带有响应的写入。如果只设置了CBCharacteristicPropertyWriteWithoutResponse,则不能在设置type: CBCharacteristicWriteType.withResponse 的情况下执行writeValue

    【讨论】:

    • 谢谢,我不确定我明白你的意思。你如何检查/设置这个?我不确定您是否完整阅读了我的问题,但我确实说过其他应用程序能够写入同一设备
    • 如果您无法访问 BLE 设备端的固件或文档,只需尝试将 CBCharacteristicWriteType.withResponse 更改为 CBCharacteristicWriteType.withoutResponse。如果有效,就是这样。要进行更改,您需要访问固件。
    • 当然 ;-) 看看这些之间的区别以及通知和指示之间的区别。如果使用通知或无响应写入,则 BLE 协议设计无法保证数据将被传输。不幸的是,如果您无法访问设备端,则无法更改它,因此您必须按原样使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多