如何通过ble传输大文件(~1MB)?

问题描述 投票:0回答:1

我正在构建一个应用程序,让用户可以更改Amazfit GTS / GTS 2 / Mi Band 4 / Mi Band 5(基本上是健身手表)的表盘。我正在使用插件 flutter_blue 将我的设备与手表连接。我需要将 .bin 文件(~1MB)传输到手表来更改表盘。 .bin 文件可以在here 找到。我能够将我的 Android 设备与手表连接。我还可以列出所有服务、特征和描述符。

我在网上读到大数据是通过 ble 分块发送的。

现在特征这么多,我不明白特征数据要写在哪一个,怎么写?我如何知道数据块已成功到达手表?

如果需要,我可以分享所有服务、特征截图。

任何帮助将不胜感激。

flutter dart bluetooth-lowenergy
1个回答
0
投票

这是我的解决方案。

首先,在成功连接后尝试在 BLE 设备中请求更高的 MTU。这将加快传输速度。它会自动选择可能的最高 MTU(蓝牙 5.x 为 512 字节)。

if (Platform.isAndroid) await device!.requestMtu(512);

然后将 utf8 编码迭代发送到块/块中。

void send(Uint8List fileContents) async {
  if (fileContents.isEmpty) return;

  int bytesAlreadySent = 0;
  int bytesRemaining = fileContents.length - bytesAlreadySent;
  
  // Try not making this value close as your MTU,
  // it will affect the reliability of the connection
  int maxBlockLength = 128;

  while (bytesRemaining > 0 && isFileTransferInProgress) {
    int blockLength = min(bytesRemaining, maxBlockLength);
    Uint8List blockView = Uint8List.view(fileContents.buffer, bytesAlreadySent, blockLength);

    await fileBlockCharacteristic?.write(blockView).then((_) {
      bytesRemaining -= blockLength;
      print("File block written - $bytesRemaining bytes remaining");
      bytesAlreadySent += blockLength;
    }).catchError((e) {
      print("File block write error with $bytesRemaining bytes remaining");
      isFileTransferInProgress = false;
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.