有没有办法在 JavaScript 中通过 BLE 发送大块数据?

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

我正在尝试将图像(15000 字节)发送到 BLE 外设。

搜索后我只找到了

p5.ble.js
在JavaScript中支持BLE的库。

function setup() {
    myBLE = new p5ble();

    // Create a 'Write' button
    const writeButton = createButton('Write');
    // writeButton.position(input.x + input.width + 15, 100);
    writeButton.mousePressed(writeToBle);

    for(let i = 0; i < 15000; i++)
    {
      img[i] = i;
      // console.log(img[i]);
    }
}


function writeToBle() {
  var str1 = new TextDecoder().decode(img.slice(0,127));

  // sending 2nd chunk
setTimeout(function(){
    var str2 = new TextDecoder().decode(img.slice(128,255)); // this just result in garbage
      myBLE.write(myCharacteristic, str2);
    }, 1000);

    // sending first chunk
    myBLE.write(myCharacteristic, str1);
    // myBLE.write(myCharacteristic, img.slice(0,127)); // this doesn't send
}

这是我的第一个 JavaScript 代码(它只是对 p5 ble 示例代码的修改)。

使用此代码我可以毫无问题地发送

str1
。我收到了正确的数据和正确的字节数。

但是由于某种原因,发送时

str2
我收到了大约 500 字节而不是 128 字节,并且数据只是这些数字的重复
239, 191, 189

我在这里做错了什么?

javascript bluetooth-lowenergy iot
1个回答
0
投票

BLE通信时,根据MTU值确定数据写入和读取操作。双方确定的MTU必须相同,这样通信才健康,不会有数据丢失。

我以前没有使用过该库,但是如果您查看文档,它将帮助您设置 MTU 值。

回答标题中的问题。尽管 BLE 的最大值因蓝牙版本而异;您可以使用最小 23 到最大 512 之间的值。

如果根据 MTU 大小将图像数据划分为数组,则可以使用 for 循环直接通过 BLE 发送该数组。

示例;

 function Update(dataURI) {
  RNFS.readFile(filePath, 'base64')
  .then(async contents => {
    const bufArray: any[] = [];

    let data = convertDataURIToBinary(contents);

    for (let i = 0; i < data.length; i += MTU) {
      const outerChunk = data.slice(i, i + MTU);
      bufArray.push(Object.values(outerChunk));
    }

    bufArray.push([194]); // Add last byte stop byte.

    wait(1000).then(() => {
      writePeripheral([193], false); // Start byte.
      wait(2000).then(() => {
        for (const bytes of bufArray) {
          writePeripheral(bytes, true);
        }
      });
    });
  })
  .catch(error => {
    console.error(error);
  });
 }

 function convertDataURIToBinary(dataURI) {
  var raw = atob(dataURI);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for (var i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
 }
© www.soinside.com 2019 - 2024. All rights reserved.