小程序操作蓝牙进行读写

小程序操作蓝牙进行读写

本文讲述小程序使用蓝牙进行数据的读写。

这篇将是全代码,但关键地方都会有注释。

一、打开适配器

javascript 复制代码
initBLE:function(back) {
	wx.openBluetoothAdapter({ success(res){
	    // ===== 打开成功 =====
	    this.searchBLE();		// 开始搜索蓝牙外设
	    // 在蓝牙打开的情况下突然关闭
        wx.onBluetoothAdapterStateChange(function (res) {
          if (!res.available) { //蓝牙适配器是否可用
              this.setData({
                  tipsBox: "tipsBox",
                  tipsTitle: "温馨提示",
                  tipsContent: "蓝牙未打开,请重新打开蓝牙"
              })
          }
        })
	},fail(err) {
	    wx.showToast({
           title: '请检查手机蓝牙是否打开',
            icon: 'none',
        })
      }
	})
},

二、搜索蓝牙外设

javascript 复制代码
// 开始搜索
searchBLE() {
    let that =this;
    BLEMag.bluetoothMag.startMonitorBluetoothSearch({
        success(res) {
            that.monitorSearchDevice(); // 监听蓝牙搜索回调
            that.searchDevice(); // 开始蓝牙搜索
        }
    });
},

// 监听蓝牙搜索回调
monitorSearchDevice() {
  var that = this;
  wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      interval: 0,
      // ===== 搜索打开成功 =====
      success: function () {
          that.setData({
              showProgress: false
          })
      },
      // ===== 搜索打开失败 =====
      fail: function (res) {
          that.failCallback('蓝牙设备服务发现失败')
          that.printLog("蓝牙设备服务发现失败: " + res.errMsg);
      }
  })
},

// 搜索蓝牙
searchDevice:function(back) {
  var that = this;
  var deviceArr = [];
  wx.onBluetoothDeviceFound(function (res) {
    res.devices.forEach(device => {
    	// TODO 
    	// 做搜索到设备的处理
    	wx.stopBluetoothDevicesDiscovery(); // 停止搜索设备
    })
  })
},

三、连接蓝牙

javascript 复制代码
// 先关闭再连接蓝牙
createBLE: function (deviceID) {
    var that = this;
    
    // 先断开设备连接
    wx.closeBLEConnection({ deviceId: deviceID, success: function (res) {
        console.log('断开设备成功 = ', res)
		that.connectionBluetooth(deviceID);
    },fail: function (error) {
        if (error.errCode === 10006 && error.errMsg === "closeBLEConnection:fail:no connection"){
            console.log('断开设备失败1 = ', error)
        }else{
            console.log('断开设备失败2 = ', error)
        }
        console.log('断开设备失败 = ', error)	
    }})
},

// 连接蓝牙
connectionBluetooth:function(deviceID, deviceType, back) {
    var that = this;
    console.log(' 正在连接设备ID = ',deviceID);
    wx.createBLEConnection({ deviceId: deviceID, success: function (res) {
        console.log(' ============== 连接成功 ============== ',res);
        if (BLE_state === "关") { return }
        // 这里可以申请MTU
        wx.setBLEMTU({ deviceId: deviceID, mtu: 135, success: function (res){
            console.log(' ============== 申请MTU成功 ============== ',res);
            back.success("连接成功");
            that.getBLEServiceId(deviceID);	// 连接设备后获取蓝牙设备服务
        },fail: function (error){
            console.log(' ============== 申请MTU失败 ============== ',error);
            back.success("连接失败");
        }});
    },fail: function (error) {
        if (BLE_state === "关") { return }
        if (error.errMsg === "closeBLEConnection:fail:no connection") {
            console.log(' ============== 连接失败 ============== ', error);
        }
    }})
},

四、获取服务和特征

javascript 复制代码
// 获取蓝牙服务
getBLEServiceId: function (deviceID) {
    var that = this;
    that.printLog("获取设备[" + deviceID + "]服务列表")
    wx.getBLEDeviceServices({
        deviceId: deviceID,
        // ===== 获取服务成功 =====
        success: function (res) {
            var services = res.services;
            that.printLog('找到设备服务列表个数: ' + services.length);
            if (services.length <= 0) {
                that.printLog("未找到主服务列表")
                return;
            }
            if (services.length == 1) {
                var service = services[0];
                that.printLog("服务UUID:[" + service.uuid + "]");
                that.printLog("Primary:" + service.isPrimary);
                that.setData({currServiceID: service.uuid})
                that.getBLECharactedId(deviceID, service.uuid); // 获取服务特征值
            } else { // 多个主服务
                // TODO 如果有多个主服务,可以硬编码比对 ServiceUUID
                var service = null;
                for (var i = 0; i < services.length; i++) {
                    if (services[i].uuid == '服务uuid') {
                        service = services[i];
                        break;
                    }
                }
                if (service == null) {
                    service = services[0];
                }
                that.printLog("服务UUID:[" + service.uuid + "]");
                that.printLog("Primary:" + service.isPrimary);
                that.getBLECharactedId(deviceID, service.uuid); // 获取服务特征值
            }
        },
        // ===== 获取服务失败 =====
        fail: function (res) {
            that.failCallback('获取设备蓝牙服务列表失败,请重试')
            that.printLog("获取设备服务列表失败" + res.errMsg);
        }
    })
},

// 获取服务特征
getBLECharactedId: function (deviceID, serviceId) {
    var that = this;
    that.printLog("获取设备特征值")
    wx.getBLEDeviceCharacteristics({
        deviceId: deviceID,
        serviceId: serviceId,
        // ===== 获取特征值成功 =====
        success: function (res) {
            console.log(res);
            var chars = res.characteristics;
            if (chars.length <= 0) {
                that.printLog("未找到设备特征值")
                return;
            }
            that.printLog("找到设备特征值个数:" + chars.length);

            var char = chars[0];
            that.printLog("特征值[" + char.uuid + "]")
            var prop = char.properties;

            // 这里会获取到两个特征值,一个用来写,一个用来读
            for (var i = 0; i < chars.length; i++) {
              var char = chars[i];
              // 这里可以对特征值的uuid进行判断,具体看实际情况
              if(char.uuid=='特征的uuid值'){
              	  var prop = char.properties;
	              if (prop.notify == true) {          // 读
	                that.printLog("该特征值属性: Notify");
	                that.recvBLECharacterNotice(deviceID, serviceId, char.uuid);
	              } else if (prop.write == true) {    // 写
	                that.printLog("该特征值属性: Write");
	                that.setData({currCharId: char.uuid})
	                that.sendBLEData(deviceID, serviceId, char.uuid);
	              } else {
	                that.printLog("该特征值属性: 其他");
	              }
	            }
              }
        },
        // ===== 获取特征值失败 =====
        fail: function (res) {
            console.log('获取设备特征值失败,', res);
        }
    })
},

五、数据读写

javascript 复制代码
// 蓝牙特征值变化通知
recvBLECharacterNotice: function (deviceId, serviceId, charId) {
    var that = this;
    that.printLog("注册Notice 回调函数");
    // state:true 启用Notify功能
    wx.notifyBLECharacteristicValueChange({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: charId,
        state: true,
        // ===== 蓝牙特征值监听成功 =====
        success: function (res) {
            that.printLog("启用低功耗蓝牙设备特征值变化时的 notify 功能 success");
            // 监听低功耗蓝牙设备的特征值变化 characteristic
            wx.onBLECharacteristicValueChange(function (res) { // 监听回调
                console.log(res);
                that.printLog("收到Notify数据: " + plugin.ab2hex(res.value));
            });
        },
        // ===== 蓝牙特征值监听失败 =====
        fail: function (res) {
            // console.log(res);
            // that.printLog("特征值Notice 接收数据失败: " + res.errMsg);
            // that.failCallback('设备蓝牙特征值接收数据失败,请重试')
            // 这里需要注意,这样写是因为会报一个错但是还是能监听到数据
            wx.onBLECharacteristicValueChange(function (res) { // 监听回调
              console.log(res);
              that.printLog("收到Notify数据: " + plugin.ab2hex(res.value));
            });
        }
    })
},

// 发送数据
sendBLEData(deviceId, serviceId, charId){
  // 这里我举例发个数据(注意最后发送的是个十进制数组)
  let array = [];
  for (var i = 0; i < data.length; i++) {
  	array.push(data.charAt(i).charCodeAt())
  }
  var buffer = new Uint8Array(array).buffer;
  var that = this;
  wx.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: charId,
    value: buffer,
    success: function (res) {
        that.printLog("向蓝牙发送数据");
    },
    fail: function (res) {
        console.log(res);
    },
    complete: function () {
    }
  })
},
相关推荐
林恒smileZAZ8 个月前
uni-app攻略:如何对接驰腾打印机
uni-app·打印机·小程序蓝牙·打印处理