微信小程序蓝牙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)
        }
      })
    })
相关推荐
游戏开发爱好者85 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106327 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106327 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息8 小时前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”9 小时前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
换日线°1 天前
NFC标签打开微信小程序
前端·微信小程序
光影少年1 天前
AIGC + Taro / 小程序
小程序·aigc·taro
2501_915918411 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
天空属于哈夫克31 天前
Go 语言实战:构建一个企微外部群“技术贴收藏夹”小程序后端
小程序·golang·企业微信