我正在开发一个iOS应用程序,需要将20多个字节的数据发送到Bluetooth LE中心。我已经设置了一个外围设备管理器,并依次发送每个20字节的“数据包”。我只会在peripheralManager.updatevalue
返回true后发送下一个数据包(如果peripheralManagerIsReadyToUpdateSubscribers
返回false,则在调用updateValue
之后重试)。在大多数情况下,这种方法都是可行的,但是在大约20%的时间内,发送的数据不正确。
我有三个小包。在大多数情况下,中心会先接收A,然后再接收B,然后再接收C,但是有时中心会接收到B,然后再接收B,然后再接收C,或者先接收到C,然后再接收C,然后再接收C。
它总是发送三个通知,但是值不正确。
在重要的情况下:
特征值存储在BLECharacteristic
个对象的实例中
@objc public class BLECharacteristic: CBMutableCharacteristic{
public var dynamicValue: Data?
public override init(type UUID: CBUUID, properties: CBCharacteristicProperties, value: Data?, permissions: CBAttributePermissions){
super.init(type: UUID, properties: properties, value: nil, permissions: permissions)
self.dynamicValue = value
}
public convenience init(characteristic: CBCharacteristic){
self.init(type: characteristic.uuid, properties: characteristic.properties, value: characteristic.value, permissions: CBAttributePermissions.readable)
}
}
在调用peripheralManagerIsReadyToUpdateSubscribers
之后将通知“缓冲”发送时,信息存储在DelayedNotification
对象中。
@objc public class DelayedNotification: NSObject{
private(set) var valueToNotify: Data
private(set) var characteristic: BLECharacteristic
private(set) var devicesToNotify: [CBCentral]?
@objc public init(_ data: Data, _ char: BLECharacteristic, _ devsNotify: [CBCentral]?){
valueToNotify = data
characteristic = char
devicesToNotify = devsNotify
}
}
创建对象时:
var valueToSend: Data
if(characteristic.dynamicValue == nil){
valueToSend = Data()
}else{
valueToSend = characteristic.dynamicValue!
}
buffer.append(DelayedNotification(valueToSend, characteristic, devicesToNotify))
编辑:更多代码
private func notifyDevices(_ characteristic: BLECharacteristic){
DispatchQueue.main.async {
var valueToSend: Data
if(characteristic.dynamicValue == nil){
valueToSend = Data()
}else{
valueToSend = Data(characteristic.dynamicValue!)
}
self.notificationLock.wait()
self.notBuffer.append(DelayedNotification(valueToSend, characteristic, nil))
self.notificationLock.signal()
self.processNotificationBuffer()
}
}
private func processNotificationBuffer(){
DispatchQueue.main.async{
self.notificationLock.wait()
for notification in self.notBuffer{
let res = self.peripheralManager.updateValue(Data(notification.valueToNotify), for: notification.characteristic, onSubscribedCentrals: notification.devicesToNotify)
if(res){
NSLog("Sent: " + String(data: notification.valueToNotify, encoding: .utf8)!) // This is always printed in the right order
notificationSent()
self.notBuffer.remove(at: self.notBuffer.index(of: notification)!)
}
}
self.notificationLock.signal()
}
}
@objc public func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) {
processNotificationBuffer()
}
答案 0 :(得分:0)
问题出在客户身上。我的自定义android客户端可以正常工作。