微信小程序蓝牙writeBLECharacteristicValue写入数据返回成功后,实际硬件内信息查询未存储?

问题:连接蓝牙后,调用小程序writeBLECharacteristicValue,返回传输数据成功,查询硬件响应发现没有存储进去?

解决:一直以为是这个write方法的问题,找了很多相关贴,后续进行硬件日志查询,发现传输的数据确实传成功了,但是只传输了二分之一。

原因:微信小程序对于传输Value有默认字节限制,默认是20,传输内容超过了20,所以只传过去了前20个字节。超过字节限制,不会报错,也会报传输成功。

行动:查询小程序字节限制(wx.getBLEMTU),对传输内容做分包处理再传输
注意:在使用微信小程序getBLEMTU获取mtu时,一定要减3!!!!!!

javascript 复制代码
function stringToAsciiCodesAndSplit(str: string, mtuSize = 20): Uint8Array[] {
  // 将字符串转换为 ASCII 码的 ArrayBuffer
  const asciiCodes: number[] = []
  for (let i = 0; i < str.length; i++) {
    asciiCodes.push(str.charCodeAt(i))
  }
  
  const uint8Array = new Uint8Array(asciiCodes)
  console.log('uint8Array.buffer', uint8Array.buffer)

  // 定义一个 packets 数组,它将存储多个 Uint8Array 类型的元素
  const packets: Uint8Array[] = []
  
  // 根据 MTU字节 大小拆分数据
  for (let i = 0; i < uint8Array.length; i += mtuSize) {
    packets.push(uint8Array.slice(i, i + mtuSize))
  }

  return packets
}
javascript 复制代码
const command = `atxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyy`
//mtu为字节限制
    const buffer = stringToAsciiCodesAndSplit(command, mtu)
    buffer.forEach((packet, index) => {
      // 将每个包转换为 ArrayBuffer
      const addBuffer = packet.buffer
      Taro.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: addBuffer,
        success: function (res) {
          console.log(`第 ${index + 1} 个WIFI添加包发送成功:`, res)
        },
        fail: function (err) {
          console.log(`第 ${index + 1} 个WIFI添加包发送失败:`, err)
        }
      })
    })
相关推荐
peachSoda71 天前
小程序图片加载优化方案
前端·微信小程序·小程序
2501_915921431 天前
在 Linux 上通过命令行上架 iOS APP,Fastlane + AppUploader(开心上架)
android·linux·运维·ios·小程序·uni-app·iphone
云云只是个程序马喽1 天前
推客系统源码部署小程序配置机构号教程
小程序
吴声子夜歌1 天前
小程序——开放接口(登录和用户信息)详解
小程序·apache
2501_915921431 天前
从构建到 IPA 保护,Flutter iOS 包如何做混淆与安全处理
android·安全·flutter·ios·小程序·uni-app·iphone
努力成为包租婆1 天前
【微信小程序-内嵌H5,微信开发工具上-页面没有更新】
微信小程序·小程序
计算机徐师兄1 天前
Java基于SSM的校园顺路代送微信小程序【附源码、文档说明】
java·微信小程序·ssm·校园顺路代送微信小程序·校园顺路代送·顺路代送微信小程序·java校园顺路代送微信小程序
2501_916008891 天前
iPhone 手机硬件组件使用耗能历史记录查看,能耗查看
android·ios·智能手机·小程序·uni-app·iphone·webview
百万蹄蹄向前冲1 天前
支付宝 VS 微信 小程序差异
前端·后端·微信小程序
人生导师yxc1 天前
微信小程序接入支付宝沙箱支付(http请求)
微信小程序·小程序