微信小程序蓝牙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)
        }
      })
    })
相关推荐
qq_124987075321 小时前
基于微信小程序的电子元器件商城(源码+论文+部署+安装)
java·spring boot·spring·微信小程序·小程序·毕业设计
weixin_lynhgworld1 天前
科技赋能医疗,陪诊小程序开启就医新体验
科技·小程序
2501_916007471 天前
iOS 证书如何创建,从能生成到能长期使用
android·macos·ios·小程序·uni-app·cocoa·iphone
壹立科技1 天前
商超到家即时服务:软件基础功能打通“线上线下”关键链路
微信小程序·软件需求·外卖跑腿平台·外卖跑腿系统·商超配送
jqpwxt1 天前
启点创新游乐场多商户分账管理系统:驱动文旅商业生态革新的数字化引擎
大数据·人工智能·小程序
00后程序员张1 天前
AppStoreInfo.plist 在苹果上架流程中的生成方式和作用
android·小程序·https·uni-app·iphone·webview
计算机毕设指导61 天前
基于微信小程序+django连锁火锅智慧餐饮管理系统【源码文末联系】
java·后端·python·mysql·微信小程序·小程序·django
风月歌1 天前
php医院预约挂号系统小程序源代码(源码+文档+数据库)
数据库·微信小程序·小程序·毕业设计·php·源码
qq_12498707531 天前
基于微信小程序的校园资讯共享平台的设计与实现(源码+论文+部署+安装)
spring boot·后端·微信小程序·小程序·毕业设计
2501_915106321 天前
iOS App 测试方法,通过 Xcode、Instruments、Safari Inspector、克魔(KeyMob)等工具
android·ios·小程序·uni-app·iphone·xcode·safari