无法将数据发送到特征 [英] Unable to send data to characteristic
问题描述
当远程设备更改特征值时,我可以在应用程序上收到通知,但是当应用程序更新该值时,远程设备将看不到它.
I am able to get notified on the app when a remote device change the characteristic value, but when the app update the value back, the remote device won't see it.
所以,我知道我的特征是有效的,我也知道其他应用能够写回该特征(实际设备会打印出该特征)
So ,I know my characteristic is valid, i also know that other apps are able to write back to that characteristic (The actual device prints it)
所以问题当然是应用程序中的 .
So problem is of course in the app.
更有趣的是,每个特征都有句柄,每个句柄都有自己的UUID.
Whats more interesting is that every characteristic has handles , which have each its own UUID.
iOS只会让我看到我的特征UUID,无法访问其句柄,尽管每个特征都有2个具有不同UUID的句柄
无论如何,这里我得到回调并尝试写回:
Anyway , here I get the callback and try to write back :
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的句柄)
and listing my characteristics ( which prints 1 UUID - thats true we have only 1, but it has 2 handles with different UUID)
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for charateristic in service.characteristics!
{
print("Found CHARACTERISTIC:",charateristic as CBCharacteristic)
}
推荐答案
您应该检查为您的特性设置了哪些属性.如果设置了CBCharacteristicPropertyWrite
,则可以执行带有响应的写操作.如果仅设置了CBCharacteristicPropertyWriteWithoutResponse
,则无法在设置了type: CBCharacteristicWriteType.withResponse
的情况下执行writeValue
.
You should check what properities are set for your characteristic. If CBCharacteristicPropertyWrite
is set then write with a response can be executed. If only CBCharacteristicPropertyWriteWithoutResponse
is set then you can not execute writeValue
with type: CBCharacteristicWriteType.withResponse
set.
这篇关于无法将数据发送到特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!