我正在通过 BLE 将图像从 Android 应用程序发送到 iOS 应用程序。根据一些文章,通过 BLE 发送的最大大小为 1 KB,因此我将图像拆分为 1 KB 的块,并以 40 毫秒的延迟将其发送到 Swift 应用程序。
但是,块大小似乎太大了。调试后,我注意到我从 Swift 中读取的特征值最多只能是 187 字节。因此,当我将 Android 中的块大小减少到该数字或更小时,传输成功,否则由于数据被切断,传输不会成功。
有谁知道为什么它限制在这个大小,尽管它应该是 1 KB?或者,如果可配置,我如何增加大小?
这是我的安卓代码:
private void writeImageToCharacteristic() {
// determine number of chunks and checksum
final int chunkSize = 1000; // fails with 1000, succeeds with 180
int numberOfChunks = imageInByte.length / chunkSize;
numberOfChunks = imageInByte.length == numberOfChunks * chunkSize ? numberOfChunks : numberOfChunks + 1;
// get the characteristic
BluetoothGattCharacteristic imgCharacteristic = mBluetoothGattServer
.getService(SERVICE_UUID)
.getCharacteristic(IMAGE_CHARACTERISTIC_UUID);
Log.d(TAG, "Image size in byte: " + imageInByte.length);
Log.d(TAG, "Number of chunks: " + numberOfChunks);
Log.d(TAG, "Start sending...");
updateStateLabel("State: sending image data...");
// first message contains information about the image
final String msg = String.valueOf(numberOfChunks);
imgCharacteristic.setValue(msg.getBytes());
mBluetoothGattServer.notifyCharacteristicChanged(mConnectedDevice, imgCharacteristic, false);
// create the chunks (and checksums if configured)
List<byte[]> messages = new ArrayList<>();
for(int i = 0; i < numberOfChunks; ++i) {
final int start = i * chunkSize;
final int end = start + chunkSize > imageInByte.length ? imageInByte.length : start + chunkSize;
final byte[] chunk = Arrays.copyOfRange(imageInByte, start, end);
messages.add(chunk);
if(includeChecksums) {
final String chunkCheckSum = calculateCheckSum(chunk);
messages.add(chunkCheckSum.getBytes());
}
}
// send the data to the device by writing
// it to the characteristic with a delay of 40 ms
for(byte[] aMsg : messages) {
SystemClock.sleep(40);
imgCharacteristic.setValue(aMsg);
mBluetoothGattServer.notifyCharacteristicChanged(mConnectedDevice, imgCharacteristic, false);
}
Log.d(TAG, "Finished sending");
updateStateLabel("State: finished sending.");
}
这是读取它的 Swift 代码:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
switch characteristic.uuid {
case Constants.ImageCharacteristicUUID:
let imgData = characteristic.value!
// here, the characteristic.value seems to be limited to 187 bytes - why?
processImageData(data: imgData!)
default:
print("Unhandled Characteristic UUID: \(characteristic.uuid)")
}
}
感谢任何帮助。