微信小程序蓝牙连接设备

小程序连接设备蓝牙详细步骤(低功耗蓝牙)

参考官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-ble/wx.writeBLECharacteristicValue.html

上代码:

WXML

<view>
<view bindtap="initBlue">初始化蓝牙</view>
<view>
  匹配到的蓝牙{{consoleLog}}
</view>
<view>高压{{highpressure}}</view>
<view>低压{{lowpressure}}</view>
<view>脉搏{{pulse}}</view>
</view>

WXJS

Page({
data: {
     inputValue:'血压名称-设备编号',//血压
     deviceId:'',
     services:'',
     propertiesuuId:"",//监听值
     writeId:"",//写入值
     uuid:"",
     buffer:"",
     readvalue:"",
     highpressure:"",//高压
     lowpressure:"",//低压
     pulse:"",//脉搏
  },
})

1.0 wx.openBluetoothAdapter 初始化蓝牙模块

initBlue:function(){
    var that = this;
    wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
      success: function (res) {
        console.log(res)
        wx.showToast({
          title: '初始化成功',
          icon: 'success',
          duration: 800
        })
        that.findBlue();//2.0
      },
      fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户
        wx.showToast({
          title: '请开启蓝牙',
          icon: 'fails',
          duration: 1000
        })
      }
    })
  },

2.0 wx.startBluetoothDevicesDiscovery 开始搜寻附近的蓝牙外围设备

  findBlue(){
    var that = this
    //开始搜索蓝牙
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        wx.showLoading({
          title: '正在搜索设备',
        })
        that.getBlue()//3.0
      }
    })
  },

3.0 wx.getBluetoothDevices 获取在蓝牙模块生效期间所有已发现的蓝牙设备

 getBlue(){
    var that = this
    wx.getBluetoothDevices({
      success: function(res) {
        wx.hideLoading();
        for (var i = 0; i < res.devices.length; i++){
   //that.data.inputValue:表示的是需要连接的蓝牙设备ID,简单点来说就是我想要连接这个蓝牙设备,所以我去遍历我搜索到的蓝牙设备中是否有这个ID
          if (res.devices[i].name == that.data.inputValue || res.devices[i].localName == that.data.inputValue){
            that.setData({
              deviceId: res.devices[i].deviceId,
            })
            that.data.deviceId=res.devices[i].deviceId;
            that.connetBlue(res.devices[i].deviceId);//4.0
            return;
          }
        }
      },
      fail: function(){
        console.log("搜索蓝牙设备失败")
      }
    })
  },

4.0 wx.createBLEConnection 通过3.0步骤找到这个蓝牙之后,通过蓝牙设备的id进行蓝牙连接

  connetBlue(deviceId){                    
    var that = this;
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: deviceId,//设备id
      success: function (res) {
        wx.showToast({
          title: '连接成功',
          icon: 'fails',
          duration: 800
        })
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) {
            console.log('连接蓝牙成功之后关闭蓝牙搜索');
          }
        })
        that.getServiceId()//5.0
      }
    })
  },

5.0 wx.getBLEDeviceServices 获取蓝牙设备所有服务

  // 连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid
  getServiceId(){
    var that = this
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,
      success: function (res) {
        var item = res.services[2];
        that.setData({
          services: item.uuid
        })
        that.getCharacteId(that.data.deviceId,that.data.services)//6.0
      },
      fail(err){
        console.log(err);
      }
    })
  },

6.0 wx.getBLEDeviceCharacteristics 获取蓝牙设备某个服务中所有特征值

indicate和notify两者一个为true即可用

getCharacteId(){
    var that = this 
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId:that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId:that.data.services,
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; i++) {//2个值
          var item = res.characteristics[i];
          if(item.properties.indicate||item.properties.notify){
            that.setData({
              propertiesuuId: item.uuid,
            })
            that.startNotice(that.data.propertiesuuId)//7.0
          }
          if (item.properties.write == true){
            that.setData({
              writeId: item.uuid//用来写入的值
            })
          }
        }
      },
      fail(err){
        console.log("getBLEDeviceCharacteristics",err);
      }
    })
  },

7.0 wx.notifyBLECharacteristicValueChange 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。

注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用

 startNotice(uuid){
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: that.data.propertiesuuId,  //第一步 开启监听 notityid  第二步发送指令 write
      success (res){
        console.log(res,'启用低功能蓝牙监听成功');
        // 监听获取数据
        // ArrayBuffer转16进制字符串示例
        function ab2hex(buffer) {
          let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
          )
          return hexArr.join('');
        }
        
        // 16进制转中文字符串
        function hexCharCodeToStr(hexCharCodeStr) {
            var trimedStr = hexCharCodeStr.trim();
            var rawStr = 
            trimedStr.substr(0,2).toLowerCase() === "0x"
            ? 
            trimedStr.substr(2) 
            : 
            trimedStr;
            var len = rawStr.length;
            if(len % 2 !== 0) {
              alert("Illegal Format ASCII Code!");
              return "";
            }
            var curCharCode;
            var resultStr = [];
            for(var i = 0; i < len;i = i + 2) {
              curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
              resultStr.push(String.fromCharCode(curCharCode));
            }
            return resultStr.join("");
          }
        wx.onBLECharacteristicValueChange((res)=>{
  console.log("16进制转成中文字符串哦",(ab2hex(res.value)));
             var newvalue=ab2hex(res.value);
             console.log("aaaaaaa",newvalue);//38
             var bb=newvalue.slice(0,2);//le
             console.log(bb,"要我转成2进制呦",parseInt('bb',16).toString(2))
             var heightya= parseInt(newvalue.slice(2,6),16);//转成10进制
             var highpressure=parseInt(heightya/256);//除以256获取高压
             console.log("高压",heightya,newvalue.slice(2,6));
             console.log("高压最终值",highpressure);
             that.setData({
              highpressure:highpressure,
             })
             that.data.highpressure=highpressure;


             
             var lowya=parseInt(newvalue.slice(6,10),16);//转成10进制
             var lowpressure=parseInt(lowya/256);//除以256获取低压
             console.log("低压",lowya,newvalue.slice(6,10));
             console.log("低压最终值",lowpressure);
             that.setData({
              lowpressure:lowpressure,
             })
             that.data.lowpressure=lowpressure;


             var mb=newvalue.slice(28,32);//截取脉搏
             console.log("脉搏",mb);
             var num1=mb.slice(0,2);//截取脉搏前两位
             var num2=mb.slice(2,4);//截取脉搏后两位
             var allnum="";
             if(num1>num2){   //判断前两位与后两位,低位在前
             allnum=parseInt((num2+num1),16);//拼接好的脉搏转成10进制
             that.setData({
              pulse:allnum,
             })
             that.data.pulse=allnum;
             }else if(num1<num2){
               allnum=parseInt((num1+num2),16);
               that.setData({
                pulse:allnum,
               })
               that.data.pulse=allnum;
             }
        })
      },
      fail(err){
        console.log(err)
      }

})
  },

此篇仅供参考哦,如有问题尽管提。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值