小程序ble整理

2019-02-19  本文已影响0人  Qianshui321

官方文档地址:
https://developers.weixin.qq.com/miniprogram/dev/api/wx.writeBLECharacteristicValue.html

代码直接上

app.js 中的部分参数
data:{
    DeviceCode:"", // 设备编码
    isconnect:false,//当前手机是否连接设备
    isopenble: false,// 当前手机蓝牙是否打开
    bleMac:[],//扫描到的设备   (为了方便处理ios)
    connectMac:"",//当前手机连接的设备.
   connectindex :"0"// ble连接次数
  }

以下是ble部分代码(utils.js中)
var isandroid = "android"; //默认当前手机是安卓
wx.getSystemInfo({
  success: function (res) {
    // 获取当前手机系统类型
    isandroid = res.platform;
    
  }
});

var ble = {  
  getsystem: isandroid, //当前手机类型
  data:function(){
    //这里保存 ble设备的读写uuid  这里为了考虑ios和安卓下 同一个设备的uuid不一样(区分大小写的)
    var data = {};
    var _this = this;
    if (_this.getsystem == "android"){
      data = {
        suuid: "0000FFF0-0000-1000-8000-00805F9B34FB",
        tuuid: "0000FFF2-0000-1000-8000-00805F9B34FB",
        zt_suuid: "0000FFF0-0000-1000-8000-00805F9B34FB",
        zt_tuuid: "0000FFF1-0000-1000-8000-00805F9B34FB"                
      }
    }else{
      data = {
        suuid: "0000FFF0-0000-1000-8000-00805F9B34FB",
        tuuid: "0000FFF2-0000-1000-8000-00805F9B34FB",
        zt_suuid: "0000FFF0-0000-1000-8000-00805F9B34FB",
        zt_tuuid: "0000FFF1-0000-1000-8000-00805F9B34FB"               
      }
    }
    return data;
  },
  /**
   *初始化蓝牙
   **/   
  init:function(){
    var _this = this;
    if (wx.openBluetoothAdapter) {
      // 打开蓝牙
      wx.openBluetoothAdapter({
        success:function(res){
          console.log("打开蓝牙",JSON.stringify(res));
          //如果蓝牙打开的话,开始搜索
          _this.search();
          getApp().data.isopenble = true;
        },
        fail:function(err){
          console.log("打开蓝牙失败",err);
          getApp().data.isopenble = false;
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      })
    }
  },
  search:function(){
    var _this = this;  
   // 搜索设备
    wx.startBluetoothDevicesDiscovery({
      // services: ['FEE7'], 
      success: function (res) {
        console.log("搜索蓝牙",res)
      
        setInterval(function(){
          //每5秒获取一次搜索到的ble设备
          _this.getble();
        },5000);
      },
      fail: function (err) {
        console.log("搜索蓝牙失败", err);
      }
    })
  },
  stopsearch:function(){
    // 停止搜索 
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log(res)
      }
    })
  },
  getble:function(){    
    var _this = this;    
    // 获取搜索到的ble设备
    wx.getBluetoothDevices({
      success: function (res) {
        console.log("搜索到的蓝牙", getApp().data.bleMac)
              
          if(res.devices[0]){

            // 存储搜索到的设备  
            for (var i = 0; i < res.devices.length;i++){
              var uuid = res.devices[i].deviceId;

              if (getApp().data.bleMac.indexOf(uuid) == -1) {
                getApp().data.bleMac.push(res.devices[i]);
              }
              
            }
          }
        
      },
      fail: function (err) {
        console.log("获取蓝牙失败", err);
      }
    })
  },
  connect:function(mac){
    var _this = this;
    // 开始连接设备 ,
    
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: mac,
      success: function (res) {
        console.log("连接设备",res)
        // 连接设备后停止搜索蓝牙
        
        if (res.errMsg == "createBLEConnection:ok"){
          if (isandroid != "ios"){
              // 连接成功后,停止搜索(安卓)。ps:忘记了为什么IOS不用停止搜索
            _this.stopsearch();//停止搜索蓝牙
          }
        //根据连接的ble设备获取service
          _this.getservice(mac);          
        }        
      },
      fail: function (err) {
        console.log("连接设备失败", err);
        getApp().data.connectindex ++;
       // 这里为了考虑连接的稳定性。 重连了3次 (有部分安卓手机连接容易断开,所以...)
        if (getApp().data.connectindex <=3){
          _this.connect(mac);          
        }else{
          wx.showToast({
            title: "连接设备失败",
            icon: 'success',
            duration: 2000
          })
        }
        getApp().data.isconnect = false;
      }
    })
  },
  disconnect:function(mac){
  // 根据传入的mac断开连接。 
    wx.closeBLEConnection({
      deviceId: mac,
      success: function(res) {
        console.log("断开蓝牙", res)
        getApp().data.isconnect = false;
        wx.showToast({
          title: "设备已断开",
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (err) {
        console.log("断开蓝牙", err);
        getApp().data.isconnect = false;
      }
    })
  },
  getservice:function(mac){
    var _this = this;
  // 获取ble设备的services
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: mac,
      success: function (res) {
        console.log('服务ID:', res.services);
        if (res.services[0]){
          // 获取成功后  在获取ble设备特征
          _this.getchart(mac);
        }
      },
      fail: function (err) {
        console.log("获取服务ID失败", err);
      }
    })
  },
  getchart:function(mac){
    var _this = this;
  // 获取ble设备的特征
  // 考虑 读写uuid不一样,这里分别处理
    if (_this.data().suuid != _this.data().zt_suuid){
      // 不一样的话, 需要获取两次,参数分别是suuid和zt_suuid ( 请看data中的值)
      wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: mac,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: _this.data().suuid,
        success: function (res) {
          console.log('特征ID:', res.characteristics)          
          // toast("连接成功")
          console.log(1111)
          
        },
        fail: function (err) {
          console.log("获取特征ID失败", err);

        }
      });
     
      setTimeout(function(){
        wx.getBLEDeviceCharacteristics({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId: mac,
          // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
          serviceId: _this.data().zt_suuid,
          success: function (res) {
            console.log('特征ID:', res.characteristics);
            if (res.characteristics[0]) {
            // 开始监听设备发出的数据
              _this.notify(mac);
            }
          }, fail: function (err) {
            console.log("特征ID失败", err);
          }
        });
      },1500);
    }else{
    // 一样的话 获取一次就行了。
      wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: mac,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: _this.data().suuid,
        success: function (res) {
          console.log('特征ID:', res.characteristics)
          if(res.characteristics[0]){
          // 开始监听设备发出的数据
            _this.notify(mac);
          }
        },
        fail: function (err) {
          console.log("特征ID失败", err);
        }
      })
    }
    
  },
  readchart:function(){
  //  根据指定的 serviceId和 characteristicId 获取设备发出的数据 (这个用的比较少)
    wx.readBLECharacteristicValue({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  [**new**]
      deviceId: deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: serviceId,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: characteristicId,
      success: function (res) {
        console.log('readBLECharacteristicValue:', res.errCode)
      }
    })
  },
  write:function(cmd){
    // 发送数据到设备
    var _this = this;      
        var mac = getApp().data.connectMac; // 连接的设备
        wx.writeBLECharacteristicValue({
          // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
          deviceId: mac,
          // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
          serviceId: _this.data().suuid,
          // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
          characteristicId: _this.data().tuuid,
          // 这里的value是ArrayBuffer类型
          value: _this.getbuffer(cmd),
          success: function (res) {
            console.log('发送指令', res.errMsg);

          },
          fail: function (err) {
            console.log("发送指令失败", err)
          }
        });       
  },
  notify:function(mac){
  //监听设备返回的数据
    var _this = this;
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
      deviceId: mac,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: _this.data().zt_suuid,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: _this.data().zt_tuuid,
      success: function (res) {
        console.log('监听消息', res.errMsg)
        getApp().data.isconnect = true;
        wx.showToast({
          title: "连接成功",
          icon: 'success',
          duration: 2000
        });
       
        //整个流程 到这才算连接成功。 这里可以做页面跳转
        
        if (res.errMsg == "notifyBLECharacteristicValueChange:ok"){
          _this.chartval(); //接收到的值( ble设备发出的数据)
          _this.error();   //  ble设备连接异常监听               
        }
      },
      fail: function (err) {
        console.log("监听失败", err);
      }
    })
  },
  error:function(){
    wx.onBLEConnectionStateChange(function (res) {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
      getApp().data.isconnect = res.connected;
      if (!res.connected){
        wx.showToast({
          title: "设备已断开",
          icon: 'success',
          duration: 2000
        });    
      }
    })
  },
  chartval:function(){  
    // ble 设备返回的值
    var _this = this; 
    wx.onBLECharacteristicValueChange(function (res) {

      console.log("接收的值", _this.gethex(res.value));
     
    })
  },
  getbuffer:function(hex){
    // 将发送的命令转成 Arraybuffer 类型
    var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))

    var buffer = typedArray.buffer;
    return buffer;
  },
  gethex:function(buffer){
  // 处理ble设备的广播数据()
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('')
  }
}

ps:
使用方法
1、ble.init(); //初始化
2、ble.connect("设备的MAC");//连接设备
3、ble.write("cmd"); // 发送数据

上一篇 下一篇

猜你喜欢

热点阅读