微信小程序蓝牙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)
        }
      })
    })
相关推荐
游戏开发爱好者810 小时前
iOS App 电池消耗管理与优化 提升用户体验的完整指南
android·ios·小程序·https·uni-app·iphone·webview
_pengliang11 小时前
小程序按住说话
开发语言·javascript·小程序
万岳科技程序员小金13 小时前
多端协同的招聘系统源码开发指南:小程序+APP一体化设计
小程序·软件开发·app开发·招聘小程序·同城招聘系统源码·招聘app开发·招聘软件开发
xkxnq13 小时前
微信小程序地理定位功能
微信小程序·小程序
難釋懷13 小时前
微信小程序全局数据共享
微信小程序·小程序
郭邯14 小时前
小程序自定义组件学习笔记
微信小程序
阿眠15 小时前
vue3实现web端和小程序端个人签名
前端·小程序·apache
2501_9159184118 小时前
iOS 性能监控工具全解析 选择合适的调试方案提升 App 性能
android·ios·小程序·https·uni-app·iphone·webview
xmdoor20 小时前
微信小程序:酒店预订管理系统
微信小程序·酒店预订·酒店系统·酒店管理
大锦终1 天前
【Linux】第一个小程序—进度条
linux·运维·服务器·小程序