编程语言
首页 > 编程语言> > 微信小程序蓝牙连接设备

微信小程序蓝牙连接设备

作者:互联网

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

参考官方文档: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) {
        console.log(res)
        wx.showLoading({
          title: '正在搜索设备',
        })
        that.getBlue()//3.0
      }
    })
  },

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

 getBlue(){
    var that = this

    wx.getBluetoothDevices({
      success: function(res) {
        console.log(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;
            console.log(that.data.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
        })
        console.log("连接蓝牙成功!")
        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];
        console.log("123456",item.uuid);
        that.setData({
          services: item.uuid
        })
        console.log(that.data.deviceId,that.data.services)
        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) {
        console.log("我是serviceId",res.characteristics)
        for (var i = 0; i < res.characteristics.length; i++) {//2个值
          var item = res.characteristics[i];
          if(item.properties.indicate||item.properties.notify){
            console.log("我是两个符合之后的结果",item.uuid)
            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){
      console.log("我是uuid",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) {
          // console.log(Array)
          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(res);
          console.log("@@@@@@@@@@@",res.value);
          console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`);
          console.log("是我是我",res.value);
          
          // console.log("123456789456789");
  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);//截取脉搏后两位
             console.log(num1);
             console.log(num2);
             var allnum="";
             if(num1>num2){   //判断前两位与后两位,低位在前
             allnum=parseInt((num2+num1),16);//拼接好的脉搏转成10进制
             console.log(allnum);
             that.setData({
              pulse:allnum,
             })
             that.data.pulse=allnum;
             }else if(num1<num2){
               allnum=parseInt((num1+num2),16);
               console.log(allnum);
               that.setData({
                pulse:allnum,
               })
               that.data.pulse=allnum;
             }
        })
      },
      fail(err){
        console.log(err)
      }

})
  },

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

标签:console,log,微信,蓝牙,deviceId,res,var,连接
来源: https://blog.csdn.net/weixin_46031235/article/details/113845288