微信小程序蓝牙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)
        }
      })
    })
相关推荐
2501_915106321 天前
iPhone 文件管理,如何进行应用沙盒文件查看
android·ios·小程序·https·uni-app·iphone·webview
说私域1 天前
以非常6+1体系为支撑 融入AI智能名片商城小程序 提升组织建设效能
大数据·人工智能·小程序·流量运营·私域运营
是梦终空1 天前
计算机毕业设计267—基于Springboot+vue3+小程序的医院挂号系统(源代码+数据库)
spring boot·小程序·vue·毕业设计·课程设计·医院挂号系统·源代码
kyh10033811201 天前
微信小游戏《找茬找汉字闯关王》源码赠送
microsoft·微信·微信小程序·微信小游戏·找茬小游戏·微信找茬消除
码云数智-园园1 天前
小程序制作平台有哪些?2026微信小程序制作平台综合评测
微信小程序
低代码布道师1 天前
【教培管家】小程序实战(八)——我的课表
低代码·小程序·云开发
码云数智-大飞1 天前
小程序快速开发平台有哪些?微信小程序制作平台综合评测
微信小程序
一匹电信狗2 天前
【Linux我做主】从 fopen 到 open:Linux 文件 I/O 的本质与内核视角
linux·运维·服务器·c++·ubuntu·小程序·开源
2501_915921432 天前
Fastlane 结合 AppUploader 来实现 CI 集成自动化上架
android·运维·ci/cd·小程序·uni-app·自动化·iphone
云游云记2 天前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue