小程序蓝牙开发总结

1:安卓手机调用wx.getBluetoothDevices方法获取不到蓝牙设备时:

解决方法:Android蓝牙调试时,未打开微信的定位服务会导致搜索不到设备,请到手机的设置里面确认

2:wx.getBluetoothDevices(OBJECT)

存在调用该接口会返回之前的蓝牙使用流程中搜索到的蓝牙设备,可能设备已经不在用户身边,无法连接。

解决方法:每次调用前,需要调用wx.closeBluetoothAdapter(OBJECT),然后wx.openBluetoothAdapter(OBJECT)

然后wx.startBluetoothDevicesDiscovery,最后再调用wx.getBluetoothDevices,参考代码如下

//搜索获取已发现设备  
function searchBluetooth (that) {
  console.log('searchBluetooth')
  // 避免获取到之前的设备,每次获取设备前,先关闭蓝牙适配器,再开启适配器,设置延迟执行为了调用蓝牙接口正常
  closeBluetoothAdapter(function(res){
    if ('success' == res){
      initializeBluetooth(function (res) {
        if ('success' == res) {
          setTimeout(function(){
            wx.startBluetoothDevicesDiscovery({//开始搜寻附近的蓝牙外围设备
              services: ['00003900-842F-544F-5348-494241000001'], //只搜索主服务 UUID 为 FEE7 的设备
              success: function (res) {
                console.log('开始搜索周边蓝牙设备')
                console.log(res)
                setTimeout(function(){
                  wx.getBluetoothDevices({//sucess返回uuid 对应的的已连接设备列表,Array类型
                    success: function (res) {
                      // 获取到蓝牙设备成功之后停止搜索周边设备
                      wx.stopBluetoothDevicesDiscovery({ //先停止搜索周边设备
                        success: function (res) {
                          console.log('连接设备前,先停止搜索周边设备:')
                          console.log(res)
                        }
                      })
                      console.log('设备:' + JSON.stringify(res.devices));
                      var devices = res.devices;
                      var length = devices.length;
                      if (null != devices && length > 0){
                        for (var i = 0; i < length; i++){
                          var device = devices[i];
                          if (device.name == '未知设备' && device.localName){
                            device.name = device.localName;
                          }
                        }
                      }
                      that.setData({
                        devices: devices
                      })
                    }, fail: function (res) {
                      console.log("getBluetoothDevices fail:" + res);
                    }
                  })
                }, 500)
              }, fail: function (res) {
                console.log("searchBluetooth fail:" + res);
                wx.showToast({
                  title: '连接蓝牙失败',
                  icon: 'none',
                  image: '/images/my/[email protected]',
                  mask: true
                })
              }
            })
          }, 100)
        }
      })
   }
  });
}

3:iOS平台上,直接调用read、write、notify报如下错误

10004 no service 没有找到指定服务
10005 no characteristic 没有找到指定特征值

iOS平台上后续对特征值的read、write、notify,由于系统需要获取特征值实例,传入的 serviceId 与 characteristicId 必须由 getBLEDeviceServices 与 getBLEDeviceCharacteristics 中获取到后才能使用。建议双平台统一在建立链接后先执行 getBLEDeviceServices 与 getBLEDeviceCharacteristics 后再进行与蓝牙设备的数据交互

参考代码如下

// 密码配对
function pair(password, newPassword, callback){
  var deviceId = app.globalData.localId;
  wx.getBLEDeviceServices({
    deviceId: deviceId,
    success: function (res) {
      wx.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: order.uuid,
        success: function (res) {
          pair1(password, newPassword, callback);
        }, fail: function (res) {
          return callback('设备不支持密码配对特征值');
        }
      })
    }, fail: function (res) {
      return callback('设备不支持密码配对服务');
    }
  })
}
// 密码配对-写
function pair1(oldPassword, newPassword, callback){
  var deviceId = app.globalData.localId;
  var password = '123456';
  if (oldPassword){
    password = oldPassword;
  }
  var buf = stringToBytes(password)
  wx.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: order.uuid,
    characteristicId: order.pair,
    value: buf,
    success: function (res) {
      console.log('writeBLECharacteristicValue success', res)
      // 必须在这里的回调才能获取
      wx.onBLECharacteristicValueChange(function (characteristic) {
        console.log('characteristic value comed:', characteristic)
        var ret = byteToDecString(characteristic.value)
        console.log(ret);
        if (ret === "1") {
          // 配对成功之后,获取安全模式,以控制器的为准
          onConnected();
          if (newPassword && newPassword.length == 6){
            return changePassword(newPassword, callback);
          }else{
            return callback('配对成功');
          }
        } else {
          return callback('配对密码错误');
        }
      })
      wx.readBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: order.uuid,
        characteristicId: order.pair,
        success: function (res) {
          console.log('readBLECharacteristicValue:', res.errCode)
        },
        fail: function (res) {
          return callback('设备不支持密码配对读取');
        }
      })
    },
    fail: function (res) {
      return callback('设备不支持密码配对写入');
    }
  })
}

4:小程序蓝牙常用转换api

function byteToDecString(buffer) {
  return new Uint8Array(buffer)[0].toString(10)
}

function hexToBytes(hexs) {
  var array = new Uint8Array(hexs.length);
  for (var i = 0, l = hexs.length; i < l; i++) {
    array[i] = hexs[i]
  }
  return array.buffer;
}

function stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
}

function bytesToString(buffer) {
  return String.fromCharCode.apply(null, new Uint8Array(buffer))
}

function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}



你可能感兴趣的:(小程序)