微信小程序蓝牙调用公共方法Bluetooth.js

上一篇 微信小程序蓝牙相关API

const Bluetooth = Bluetooth || {}
/**
 * 蓝牙状态改变回调事件 
 */
Bluetooth.onBluetoothAdapterStateChangeCallback = null
/**
 * 搜索到新设备的事件的全部监听
 */
Bluetooth.onBluetoothDeviceFoundCallback = null
/**
 * 蓝牙低功耗连接状态改变事件的监听
 */
Bluetooth.onBLEConnectionStateChangeCallback = null
/**
 * 监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
 */
Bluetooth.onBLECharacteristicValueChangeCallback = null;
/**
 * 初始化蓝牙模块。iOS 上开启主机/从机(外围设备)模式时需分别调用一次,并指定对应的 mode。
 */
Bluetooth.openBluetoothAdapter = function(){
	return new Promise((resolve, reject) => {
    wx.openBluetoothAdapter({
      success (res) {
        console.log('初始化蓝牙模块成功', res);
        resolve(res);
      },
      fail (err)  {
        console.log('初始化蓝牙模块失败', err);
        reject(err);
      }
    })
  });
}
/**
 * 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。建议在使用蓝牙流程后,与 wx.openBluetoothAdapter 成对调用。
 */
Bluetooth.closeBluetoothAdapter = function () {
	return new Promise((resolve, reject) => {
    wx.closeBluetoothAdapter({
      success (res) {
        console.log('关闭蓝牙模块成功', res);
        resolve(res);
      },
      fail (err) {
        console.log('关闭蓝牙模块失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 监听蓝牙适配器状态变化事件
 */
Bluetooth.onBluetoothAdapterStateChange = function () {
  wx.onBluetoothAdapterStateChange(this.onBluetoothAdapterStateChangeCallback);
}
/**
 * 移除蓝牙适配器状态变化事件的全部监听函数
 */
Bluetooth.offBluetoothAdapterStateChange = function () {
  wx.offBluetoothAdapterStateChange();
}
/**
 * 获取本机蓝牙适配器状态。
 */
Bluetooth.getBluetoothAdapterState = function () {
	return new Promise((resolve, reject) => {
    wx.getBluetoothAdapterState({
      success (res) {
        console.log('获取本机蓝牙适配器状态成功', res);
        resolve(res);
      },
      fail (err) {
        console.log('获取本机蓝牙适配器状态失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 开始搜寻附近的蓝牙外围设备。
 * 此操作比较耗费系统资源,请在搜索到需要的设备后及时调用 wx.stopBluetoothDevicesDiscovery 停止搜索。
 */
Bluetooth.startBluetoothdeviceDiscovery = function () {
	return new Promise((resolve, reject) => {
    wx.startBluetoothDevicesDiscovery({
      //services: ['FEE7'],
      allowDuplicatesKey: true,
      success (res) {
        console.log('开始搜寻附近的蓝牙外围设备成功', res);
        resolve(res);
      },
      fail (err)  {
        console.log('开始搜寻附近的蓝牙外围设备失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
 */
Bluetooth.stopBluetoothDevicesDiscovery = function () {
	return new Promise((resolve, reject) => {
    wx.stopBluetoothDevicesDiscovery({
      success (res) {
        console.log('停止搜寻附近的蓝牙外围设备成功', res);
        resolve(res);
      },
      fail (err)  {
        console.log('停止搜寻附近的蓝牙外围设备失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 监听搜索到新设备的事件
 */
Bluetooth.onBluetoothDeviceFound = function () {
  wx.onBluetoothDeviceFound(this.onBluetoothDeviceFoundCallback);
}
/**
 * 移除搜索到新设备的事件的全部监听函数
 */
Bluetooth.offBluetoothDeviceFound = function () {
  wx.offBluetoothDeviceFound();
}
/**
 * 获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备。
 */
Bluetooth.getBluetoothDevices = function () {
	return new Promise((resolve, reject) => {
    wx.getBluetoothDevices({
      success (res) {
        console.log('获取在蓝牙模块生效期间所有搜索到的蓝牙设备成功', res);
        resolve(res);
      },
      fail (err)  {
        console.log('获取在蓝牙模块生效期间所有搜索到的蓝牙设备失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 连接蓝牙低功耗设备。
 * 若小程序在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需再次进行搜索操作。
 * @param {*} deviceId 
 */
Bluetooth.createBLEConnection = function (deviceId) {
	return new Promise((resolve, reject) => {
    wx.createBLEConnection({
      deviceId: deviceId,
      success (res) {
        console.log('连接蓝牙低功耗设备成功', res);
        resolve(res); 
      },
      fail (err) {
        console.log('连接蓝牙低功耗设备失败:', err)
        reject(err); 
      }
    });
  });
}
/**
 * 断开与蓝牙设备的连接。
 */
Bluetooth.closeBLEConnection = function (deviceId) {
	return new Promise((resolve, reject) => {
    wx.closeBLEConnection({
      deviceId: deviceId,
      success (res) {
        console.log('断开与蓝牙设备的连接成功', res);
        resolve(res);
      },
      fail (err) {
        console.log('断开与蓝牙设备的连接失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 蓝牙低功耗连接状态改变事件的监听函数
 */
Bluetooth.onBLEConnectionStateChange = function () { 
  wx.onBLEConnectionStateChange(this.onBLEConnectionStateChangeCallback);
}
/**
 * 移除蓝牙低功耗连接状态改变事件的监听函数
 */
Bluetooth.offBLEConnectionStateChange = function () { 
  wx.offBLEConnectionStateChange();
}
/**
 * 获取蓝牙设备所有服务 (service)。
 * @param {*} deviceId 
 */
Bluetooth.getBLEDeviceServices = function (deviceId) {
	return new Promise((resolve, reject) => {
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success (res) {
        console.log('获取蓝牙低功耗设备所有服务成功', res);
        resolve(res);
      },
      fail (err) {
        console.log('获取蓝牙低功耗设备所有服务失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 获取蓝牙设备某个服务中所有特征 (characteristic)。
 */
Bluetooth.getBLEDeviceCharacteristics = function (deviceId, serviceId) {
	return new Promise((resolve, reject) => {
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success (res) {
        console.log('获取蓝牙设备某个服务中所有特征成功', res);
        resolve(res);
      },
      fail (err) {
        console.log('获取蓝牙设备某个服务中所有特征失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 获取蓝牙低功耗设备的信号强度 (Received Signal Strength Indication, RSSI)。
 * @param {*} deviceId 蓝牙设备 id
 */
Bluetooth.getBLEDeviceRSSI = function (deviceId) { 
	return new Promise((resolve, reject) => {
    wx.getBLEDeviceRSSI({
      deviceId,
      success (res){
        console.log('获取蓝牙低功耗设备的信号强度成功', res);
        resolve(res);
      },
      fail (err) {
        console.log('获取蓝牙低功耗设备的信号强度失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。注意:必须设备的特征值支持notify或者indicate才可以成功调用
 * @param {*} deviceId 
 * @param {*} serviceId 
 * @param {*} notifyCharacteristicUUID 
 */
Bluetooth.notifyBLECharacteristicValueChange = function (deviceId, serviceId, notifyCharacteristicUUID) {
	return new Promise((resolve, reject) => {
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能 
      deviceId: deviceId, 
      serviceId: serviceId, 
      characteristicId: notifyCharacteristicUUID, 
      success (res) {
        console.log('启用蓝牙设备特征值变化时的 notify 功能 成功:', res);
        resolve(res);
      },
      fail (err) {
        console.log('启用蓝牙设备特征值变化时的 notify 功能 失败:', err);
        reject(err);
      }
    });
  });
}
/**
 * 监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
 */
Bluetooth.onBLECharacteristicValueChange = function () {
  wx.onBLECharacteristicValueChange(this.onBLECharacteristicValueChangeCallback);
}
/**
 * 移除蓝牙低功耗设备的特征值变化事件的全部监听函数
 */
Bluetooth.offBLECharacteristicValueChange = function () {
  wx.offBLECharacteristicValueChange();
}
/**
 * 读取蓝牙低功耗设备特征值的二进制数据。注意:必须设备的特征支持 read 才可以成功调用。
 * @param {*} deviceId 
 * @param {*} serviceId 
 * @param {*} readCharacteristicUUID 
 */
Bluetooth.readBLECharacteristicValue = function (deviceId, serviceId, readCharacteristicUUID) {
	return new Promise((resolve, reject) => {
		wx.readBLECharacteristicValue({
      deviceId: deviceId, 
      serviceId: serviceId,
      characteristicId: readCharacteristicUUID, 
			success: res => { 
        console.log('读取蓝牙低功耗设备特征值的二进制数据成功', res)
        resolve(res);
      },
			fail: err => { 
        console.log('读取蓝牙低功耗设备特征值的二进制数据失败', err)
        reject(err);
      }
		});
	});
}
/**
 * 向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持write才可以成功调用,具体参照 characteristic 的 properties 属性
 * @param {*} deviceId 
 * @param {*} serviceId 
 * @param {*} writeCharacteristicUUID 
 * @param {*} buffer  写入的数据 ArrayBuffer
 */
Bluetooth.writeBLECharacteristicValue = function (deviceId, serviceId, writeCharacteristicUUID, buffer) {
	return new Promise((resolve, reject) => {
    wx.writeBLECharacteristicValue({
      deviceId: deviceId, 
      serviceId: serviceId, 
      characteristicId: writeCharacteristicUUID, 
      value: buffer, // 这里的value是ArrayBuffer类型
      success (res) { 
        console.log('向低功耗蓝牙设备特征值中写入二进制数据成功', res);
        resolve(res);
      },
      fail (err) { 
        console.log('向低功耗蓝牙设备特征值中写入二进制数据失败', err);
        reject(err);
      }
    });
  });
}
/**
 * 检测手机蓝牙 、位置信息(安卓)
 * 检测微信蓝牙 、位置信息权限(安卓)
 * 检测小程序蓝牙权限 
 */
Bluetooth.CheckSystemInfo = function (){
  return new Promise((resolve, reject) => {
    //获取设备设置
    let systemSetting = wx.getSystemSetting();
    let bluetoothEnabled = systemSetting.bluetoothEnabled;
    let locationEnabled = systemSetting.locationEnabled;
    //获取设备基础信息
    let deviceInfo = wx.getDeviceInfo();
    let platform = deviceInfo.platform;  
    /*
      ios	iOS微信(包含 iPhone、iPad)
      android	Android微信
      windows	Windows微信
      mac	macOS微信
      devtools	微信开发者工具
    */
    //获取微信APP授权设置
    let appAuthorizeSetting = wx.getAppAuthorizeSetting();
    let bluetoothAuthorized = appAuthorizeSetting.bluetoothAuthorized; //允许微信使用蓝牙的开关(仅 iOS 有效)
    let locationAuthorized = appAuthorizeSetting.locationAuthorized;
    if(!bluetoothEnabled)
    {
      let showCancel = false;
      let confirmText = '确定';
      if (platform=='android') {
        showCancel = true;
        confirmText = '去开启';
      }
      wx.showModal({
        content: '请进入手机设置开启蓝牙',
        showCancel:showCancel,
        confirmText:confirmText,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            if (platform=='android') {
              wx.openSystemBluetoothSetting({
                success (res) {
                  console.log(res)
                }
              })
            }
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      });
      resolve(false);
    }
    else
    {
      //小程序的蓝牙权限
      wx.getSetting({
        success: (res) => {
          //console.log(res)
          if (!res.authSetting['scope.bluetooth']) {
            // 没有权限
            wx.showModal({
              title: '提示',
              content: '请开启小程序蓝牙权限',
              showCancel: false,
              success: modalSuccess => {
                wx.openSetting();
              }
            });
            resolve(false);
          }
          else
          {
            if (platform=='android') {
              if (!locationEnabled) {
                wx.showModal({
                  content: '请进入手机设置开启位置信息',
                  showCancel:false,
                  success: function (res) {
                    console.log(res);
                  }
                });
                resolve(false);
              }
              else
              {
                if (locationAuthorized!=='authorized') {
                  wx.showModal({
                    content: '请进入手机设置开启微信应用的位置信息权限',
                    showCancel:true,
                    confirmText:'去开启',
                    success: function (res) {
                      console.log(res);
                      if (res.confirm) {
                        console.log('用户点击确定')
                        wx.openAppAuthorizeSetting({
                          success (res) {
                            console.log('系统微信授权管理页', res)
                          }
                        })
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }
                  });
                  resolve(false);
                }
                else
                {
                  resolve(true);
                }
              }
            }
            else if (platform=='ios')
            {
              if (bluetoothAuthorized!=='authorized') {
                wx.showModal({
                  content: '请进入手机设置开启微信应用的蓝牙权限',
                  showCancel:true,
                  confirmText:'去开启',
                  success: function (res) {
                    console.log(res);
                    if (res.confirm) {
                      console.log('用户点击确定')
                      wx.openAppAuthorizeSetting({
                        success (res) {
                          console.log('系统微信授权管理页', res)
                        }
                      })
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                });
                resolve(false);
              }
              else
              {
                resolve(true);
              }
            }
            else
            {
              resolve(true);
            }
          }
        }, 
        fail: (err) => {
          reject(err)
        }
      })
    }
  });
}

export default Bluetooth

微信小程序蓝牙API的几个事件:

1.蓝牙状态改变回调事件 onBluetoothAdapterStateChangeCallback ,判断手机蓝牙是否开启

2.搜索到新设备的事件的全部监听 onBluetoothDeviceFoundCallback ,获取搜索的蓝牙列表

3.蓝牙低功耗连接状态改变事件的监听 onBLEConnectionStateChangeCallback  ,判断蓝牙设备连接状态

4.监听蓝牙低功耗设备的特征值变化事件 onBLECharacteristicValueChangeCallback ,获取写入数据后notify返回的数据

下一篇 将继续介绍 微信小程序初始化蓝牙模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsk198726

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值