如何通过CoreBluetooth特性发送[UInt8]字节数组?长数组发送失败
CoreBluetooth发送[UInt8]字节数组失败排查
我已实现通过CoreBluetooth特性发送字符串,代码如下:
let data: String = "1" let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue) connectedPeripheral.writeValue(valueString!, for: fileBlockCharacteristic, type: CBCharacteristicWriteType.withResponse)
但发送[UInt8]字节数组时遇到问题,接收端回调完全无响应。我尝试过多种将[UInt8]转为Data的方式:
- 直接用
Data(array)转换:
let array: [UInt8] = Array(fileData!.dropFirst(startIndex).prefix(byteCount)) connectedPeripheral.writeValue(Data(array), for: fileBlockCharacteristic, type: CBCharacteristicWriteType.withResponse)
- 通过
NSData中转:
let array: [UInt8] = Array(fileData!.dropFirst(startIndex).prefix(byteCount)) let data = NSData(bytes: array, length: array.count) connectedPeripheral.writeValue(Data(data), for: fileBlockCharacteristic, type: CBCharacteristicWriteType.withResponse)
- 使用
bytesNoCopy初始化Data:
let array: [UInt8] = Array(fileData!.dropFirst(startIndex).prefix(byteCount)) let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: array), count: array.count, deallocator: .none) print("data: \(data)")
其他UInt8转Data的方案也试过,问题依旧。使用withResponse调用时无报错,使用withoutResponse会提示does not specify the "Write Without Response" property - ignoring response-less write,说明调用逻辑本身正确,但仅字符串发送成功,数组发送失败。
接收端回调代码(仅字符串发送时触发):
void onFileBlockWritten(BLECentral& central, BLECharacteristic& characteristic) { Serial.println("writing file block..."); }
更新:发送固定长度为20的[UInt8]数组可成功,但长度为21及以上则失败,即使将接收端的接收上限调整至150也无法解决。成功的代码如下:
let array: [UInt8] = Array(fileData!.dropFirst(startIndex).prefix(20)) let data = NSData(bytes: array, length: array.count) connectedPeripheral.writeValue(Data(data), for: fileBlockCharacteristic, type: CBCharacteristicWriteType.withResponse)
内容的提问来源于stack exchange,提问作者lcj
相关产品推荐
相关产品推荐

