小程序_蓝牙广播模式

224 阅读3分钟
序:困惑,感觉什么都会一点,又什么都不会,讲出来又比较费解,工作却能写出东西来,但却觉得自己写的东西,大部分人都能胜任;开始客户问我小程序能不能做蓝牙广播,之前也没做过,我就说先看一下文档支不支持这个,然后就有了后面的事情,确实,实践成真知,不过要硬件的支持才能通讯;跑通应该是可以的,发的协议就看你和硬件那边协定了。(因为安卓和IOS的广播模式发送参数是不一样的,我这个是安卓和硬件成功通讯了的,IOS的等硬件确定)。

蓝牙低功耗(Bluetooth Low Energy, BLE)协议给设备定义了若干角色,称为工作模式。

当然,小程序的东西去看文档呀:蓝牙低功耗 (Bluetooth Low Energy, BLE) | 微信开放文档

1、中心设备/主机(Central):

中心设备可以扫描外围设备,并在发现有外围设备存在后与之建立连接,之后就可以使用外围设备提供的服务(Service)。

2、外围设备/从机(Peripheral):

外围设备一直处于广播状态,等待被中心设备搜索和连接,不能主动发起搜索。例如智能手环、传感器等设备。

注意

在小程序中,蓝牙设备可以同时处于主机和从机模式。在安卓设备上,只需要调用 wx.openBluetoothAdapter 初始化一次蓝牙适配器;而在 iOS 设备上,需要分别使用两种不同的 mode 参数分别初始化中心设备和外围设备的蓝牙适配器。建议统一对于主机和从机模式分别进行一次初始化。wx.closeBluetoothAdapter 会同时关闭两种模式的蓝牙适配器。

**所以,下面就是准备使用第2种方式:app.js **

function arrayToBuffer(arr) {
  let buffer = new ArrayBuffer(arr.length);
  let view = new DataView(buffer);
  for (let i = 0; i < arr.length; i++) {
    view.setUint8(i, arr[i]); 
  }
  return buffer;
}
let bleServer = null;
App({
  onLaunch() {
    let that = this;
    const infoRes = wx.getDeviceInfo();
    that.globalData.platform = infoRes.platform;
    setTimeout(() => {
       that.openBluetoothAdapter();
    }, 1000)
  },
  // 打开蓝牙适配器
  openBluetoothAdapter() {
    let that = this;
    let gbData = that.globalData;
    if(gbData.platform == "devtools")return
    that.getLocation();
    let mode = gbData.typeNum==1?"central":"peripheral";// 主机、从机模式
    wx.openBluetoothAdapter({
      mode: mode,
      refreshCache: false,
      success: (res) => {
        if(gbData.typeNum == 1){
          // 主机模式
        }else{
          // 创建外围设备的服务端
          wx.createBLEPeripheralServer({
            success: (oneRes) => {
              console.log("创建广播服务成功",oneRes); 
              bleServer = oneRes.server;
            },
            fail(err){
              console.error("创建广播服务失败",err);
            }
          })
        }
      },
      fail: (err) => {
        console.log("蓝牙适配器错误",err)
        wx.showModal({
          title: '提示',  
          content: '请打开您的系统蓝牙后重试',
          showCancel: false,
          success(){
            isFailOpen = false;
          }
        })
      }
    })
  },
  // 发送广播
  sendAdvertis(comArr){
    //const sUuid = this.ab2hex(comArr).toUpperCase();
    let advertiseRequest = {
      deviceName: "hai",
      //serviceUuids: [sUuid],
      serviceUuids:[
        '0000af8e-0000-1000-8000-00805f9b34fb',
        '0000ae8f-0000-1000-8000-00805f9b34fb'
      ],
      manufacturerData: [{
        manufacturerId: "0xFFFF",
        manufacturerSpecificData: arrayToBuffer(comArr),
      }],
    };
    if(this.globalData.platform == "android"){
      advertiseRequest = {
        deviceName: "hello",
        manufacturerData: [{
          manufacturerId: "0xFFFF",
          manufacturerSpecificData: arrayToBuffer(comArr),
        }]
      };
    }
    new Promise(function(resolve,reject){
      bleServer.startAdvertising({
        advertiseRequest,
        powerLevel: "high",
        // timeout: 60 * 1000  // 超时自动关闭
        success: (res) => {
          resolve(200);
          console.log('发送蓝牙广播成功',res);
        },
        fail: e => {
          reject(400);
          console.error("发送蓝牙广播失败",e);
        }
      })
    })
  },
  // 停止广播
  stopAdvertis(){
    setTimeout(() => {
      bleServer.stopAdvertising({
        complete(com){
          console.log('停止广播',com);
        }
      })
    }, 200)
  },
})

发送广播与停止广播根据自己的业务来调用