iOS/Swift/CoreBluetooth Ble 通知不起作用



我有一个问题,我连接到外围设备并将通知值正确设置为 true,但我无法获取该值。我正在执行后续步骤。

1 - 连接到外围设备

2 - 我发现服务

3 - 发现服务的特征

4 - 激活特定特性的通知

override func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if characteristic.uuid == historicCharacteristicCBUUID && characteristic.properties.contains(.notify) {
print("(characteristic.uuid): properties contains .notify")
if hasWritenOnHistoric == false {
peripheral.setNotifyValue(true, for: characteristic)
}
} 
}

5 - 我等待委托,然后写下特征告诉外围设备开始发送数据

override func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
print(characteristic)
if error == nil {
print("TRUE")
if characteristic.uuid == historicCharacteristicCBUUID && characteristic.isNotifying == true {
writeOnHistory(peripheral: peripheral, characteristic: characteristic)
} else {
print("no ha cambiado su estado")
}
}
}

6 - 在外设上写入

func writeOnHistory(peripheral: CBPeripheral, characteristic: CBCharacteristic) {
if characteristic.uuid == historicCharacteristicCBUUID {
hasWritenOnHistoric = true
var bitesArray: [UInt8] = [0x01, 0x05]
for _ in 1...16 {
bitesArray.append(0x00)
}
print(bitesArray.count)
print(bitesArray)
let data = Data(bytes: bitesArray)
peripheral.writeValue(data, for: characteristic, type: .withResponse)
}
}

7 - 此委托仅调用一次,并且具有空数据 [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00](在Android中工作正常,从外围设备获取所有数据)

override func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let data = characteristic.value {
print(data)
}
}

我错过了什么吗?

提前感谢!

除非您调用didWriteValueFor,否则您将不会观察您的值是否更改。

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { 
if characteristic.uuid == myCharacteristic {
self.bluetoothManager.readValueForCharacteristic(characteristic: myCharacteristic)
}
}

最新更新