小程序蓝牙发送数据超过20个字节解决方案

问题:做小程序项目的时候碰到往蓝牙设备写数据超过20个字节,ios没有返回结果

解答:在社区和网上搜了一圈都说要分包发送但是没有完整的示例,以下代码是我亲测有效的

function writeTest(msg){
  let buffer = hexStringToArrayBuffer(msg);
  let pos = 0;
  let bytes = buffer.byteLength;
  console.log("bytes", bytes)
  while (bytes > 0) {
    let tmpBuffer;
    if (bytes > 20) {
      return delay(0.25).then(() => {
        tmpBuffer = buffer.slice(pos, pos + 20);
        pos += 20;
        bytes -= 20;
        console.log("tmpBuffer", tmpBuffer)
        wx.writeBLECharacteristicValue({
          deviceId: deviceId,
          serviceId: serviceId,
          characteristicId: writeId,
          value: tmpBuffer,
          success(res) {
            console.log('第一次发送', res)
          }
        })
      })
    } else {
     return  delay(0.25).then(() => {
        tmpBuffer = buffer.slice(pos, pos + bytes);
        pos += bytes;
        bytes -= bytes;
        wx.writeBLECharacteristicValue({
          deviceId: deviceId,
          serviceId: serviceId,
          characteristicId: writeId,
          value: tmpBuffer,
          success(res) {
            console.log('第二次发送', res)
          },
          fail: function (res) {
            console.log('发送失败', res)
          }
        })
      })
    }
  }
}
复制代码

这边有个关键点就是delay(0.25),一定要间隔相应的时间再发送,不然即使分包也接收不到正确的数据,回调数据可在onBLECharacteristicValueChange中查看。

function hexStringToArrayBuffer(str) {
  if (!str) {
    return new ArrayBuffer(0);
  }
  var buffer = new ArrayBuffer(str.length);
  let dataView = new DataView(buffer)
  let ind = 0;
  for (var i = 0, len = str.length; i < len; i += 2) {
    let code = parseInt(str.substr(i, 2), 16)
    dataView.setUint8(ind, code)
    ind++
  }
  return buffer;
}
复制代码
function delay(ms, res) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve(res);
        }, ms);
    });
}
复制代码

转载于:https://juejin.im/post/5c480d0c6fb9a049c30b954c

你可能感兴趣的:(小程序蓝牙发送数据超过20个字节解决方案)