原生微信小程序蓝牙开发(九)

接上一篇(原生微信小程序蓝牙开发(八)

我们现在说通过蓝牙设备发送指令的操作

第九步:发送信息给蓝牙(wx.writeBLECharacteristicValue)

向蓝牙低功耗设备特征值中写入二进制数据。

注意:必须设备的特征支持 write 才可以成功调用。

参数

Object object

属性类型默认值必填说明
deviceIdstring蓝牙设备 id
serviceIdstring蓝牙特征对应服务的 UUID
characteristicIdstring蓝牙特征的 UUID
valueArrayBuffer蓝牙设备特征对应的二进制值
writeTypestring蓝牙特征值的写模式设置,有两种模式,iOS 优先 write,安卓优先 writeNoResponse 。(基础库 2.22.0 开始支持)
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

官方文档:wx.writeBLECharacteristicValue(Object object)

下面是我的代码:

  // 将从后台服务获取的指令写入到蓝牙设备当中
  sendMy(argument) {
    // 生成时间戳
    const timestamp = new Date().getTime(); // 获取当前时间的时间戳(流水号
    const getsid = `getsid=${this.data.ip}_${this.data.sn}_${timestamp}\n`;
    const openid = `openid=${this.data.ip}_${this.data.sn}_${timestamp}\n`;
    const that = this;
    if (argument == "getsid") {
      wx.writeBLECharacteristicValue({
        deviceId: that.data.deviceId,
        serviceId: that.data.services,
        characteristicId: that.data.writeId, 
        value: that.stringToUint8Array(getsid), // 这里的value是ArrayBuffer类型
        success: (res) => {
          // 成功后进行的操作
          return;
        },
        fail: (res) => {
          // 失败的提示
        },
      });
    } else if (argument == "openid") {
     // 后面根据自己项目来
    }
  },

这里主要是展示怎么使用 api 的,具体操作根据自己项目来

我这里给蓝牙发送信息的时候封装了一个字符串转Uint8Array的方法一并呈现在下面:

 stringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
      arr.push(str.charCodeAt(i));
    }
    var tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array.buffer;
  },

蓝牙操作完最后进行——断开蓝牙 

欢迎大家补充,一起学习进步

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值