FE - 微信小程序 - 蓝牙 BLE 开发调研与使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LABLENET/article/details/78492824

背景

最近在研究 weex 的时候,感受到的不只是一点痛楚,从文档到示例代码,再到代码仓库,真是一塌糊涂。反看 微信小程序的文档 简直好到极点,公司现有产品本身是和硬件打交道的,所以在蓝牙开发上的就下了下功夫。年初,看到小程序的时候,其蓝牙还不支持 android ,少了很多特性。不知何时,微信就已经更新蓝牙(ble)开发的内容,今天有幸尝试这在微信小程序里,进行了试用和测试。

这里写图片描述

先说感受,优点:只需要根据 api 文档写 js 即可,可以在 微信的 androidios 端的小程序中使用,很强。缺点:属于微信小程序生态环境。

效果图

基本测试内容:连接我公司的ble 产品 , 并能正常传输数据,最后,还要测试在 androidios 的微信小程序中同时测试下,是否可以正常运行。

  • 扫描 ble 设备
  • 连接 ble 设备
  • 接收 ble 设备数据
  • androidios 是否均正常

(ios 效果图)
这里写图片描述

(图中’蓝牙未打开’字样是在蓝牙关闭和打开的时候变化的)

1、ble-初始化

初始化是会判断当前是否支持 ble 是否可以获得 bleAdapter;

 bleInit:function(){
    console.log('初始化蓝牙')
    let self = this
    wx.openBluetoothAdapter({
      success: function(res) {
        self.setData({
          bleAdapterStatus: "初始化成功"
        })
      },
      fail:function(msg){
        self.setData({
          bleAdapterStatus: "初始化失败"
        })
        wx.showModal({
          showCancel:false,
          title: '提示',
          content: '设备蓝牙未打开,请打开蓝牙功能',
          success:function(res){
            if (res.confirm) {
              //console.log('用户点击确定')
              // 退出小程序
            }
          }
        });
      }
    });
  }

2、ble-扫描蓝牙

基本步骤:ble 初始化 => 扫描设备 => 获取设备信息

 onScanClick:function(event){
    console.log('扫描开始')
    let self = this
    wx.openBluetoothAdapter({
      success: function(res) {
        // 扫描蓝牙
        self.bleDisCovery()
        self.setData({
          bleAdapterStatus:"初始化成功"
        })
      },
      fail:function(error){
        self.setData({
          bleAdapterStatus: "初始化失败"
        })
        wx.showModal({
          showCancel: false,
          title: '提示',
          content: '设备蓝牙未打开,请打开蓝牙功能',
          success: function (res) {
            if (res.confirm) {
              //console.log('用户点击确定')
            }
          }
        });
      },
      complete:function(){
        //console.log('complete')
      }
    });
  },,
  /**
   * 解析数据信息
   */
  bleFound:function(){
    console.log("发现设备信息")
    let self =this
    wx.onBluetoothDeviceFound(function (res) {
      let devices = res.devices
      console.log(devices)
      let length = self.data.bleChips.length
      let devicesLength = devices.length
      if (devicesLength > length){
        self.data.bleChips = devices
        self.setData({
          bleChips: devices
        });
      }
      console.log(self.data.bleChips)
    });

  },
  /**
   * 扫描设备
   */
  bleDisCovery:function(){
    console.log("扫描蓝牙")
    let self = this
     wx.startBluetoothDevicesDiscovery({
          interval:1000,
          success: function(res){
            self.bleFound();
          }
        });
  },

3、ble-连接设备

扫描到的数据列表显示,注意看连接 button , 点击事件传参数,通过 data-自定义参数名称;

比如我的 data-item :参数名称就为 item ;

  <view wx:if="{{!bleConnSuccess}}" class='scan_result' wx:for="{{bleChips}}">
     <text class="result_text">{{index}}-{{item.name}}-{{item.deviceId}}</text>
     <button bindtap='onConnBle' data-item='{{item}}'>连接</button>
  </view>

其次,接收数据:

onConnBle:function(e){
    // 停止扫描
    wx.stopBluetoothDevicesDiscovery({
      success: function(res) {
      },
    });
    // 接收点击事件的参数
    let device = e.currentTarget.dataset.item
    console.log(`conn ble >> ${device}`)
    this.setData({
      bleChipInfo: device
    })
    let deviceId = device.deviceId
    let self = this
    // 连接设备
    console.log("连接设备中...")
    wx.createBLEConnection({
      deviceId: deviceId,
      success: function(res) {
        wx.showToast({
          title: '连接成功',
        });
        // 连接成功,打开 notify
        setTimeout(function(){
          self.bleServices(deviceId)
        },1500)

      },
      fail:function(errMsg){
        wx.showToast({
          title: `连接失败:${errMsg}`,
        })
      }
    });
  }

4、ble- 获取 services

 bleServices: function (deviceId){
    let self = this
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res) {
        wx.showToast({
          title: 'service success',
        })
        // 设备中的 services
        let services = res.services
        for(let index in services){
          let service= services[index]
          console.log(service)
        }       
        console.log('device services:', res.services)
      }
    })
  },

5、ble-service 获取 characteristics

bleServiceChart: function (deviceId,serviceId){
    let self = this;
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: serviceId,
      success: function (res) {
        console.log('device getBLEDeviceCharacteristics:', res.characteristics)
        let characteristics = res.characteristics
        for (let index in characteristics){
          let characteristic = characteristics[index]
            //
          }
          console.log(characteristic)
        }
        self.openNotify(deviceId) 
      }
    })
  },

6、ble- notify data

开启 notify data ,要使用 onBLECharacteristicValueChange 进行数据接收;

 openNotify: function (deviceId) {
    this.setData({
      bleConnSuccess: true
    });
    let self = this
    wx.notifyBLECharacteristicValueChange({
      deviceId: deviceId,
      serviceId: '你的 service id',
      characteristicId: '你的  characteristic Id',
      state: true,
      success: function (res) {
        console.log('notify success')
        self.onNotifyChange()
        wx.showToast({
          title: 'notify success',
        });
      },
      fail: function (err) {
        console.log(err)
        wx.showToast({
          title: 'notify fail',
        });
      }
    });
  }

7、ble - 接收数据

  onNotifyChange:function(){
    // 接收数据
    let self = this
    wx.onBLECharacteristicValueChange(function (res) {
      console.log(res.characteristicId)
      let byteDatas = Array.from(new Int8Array(res.value))
      console.log(byteDatas)
      const data = byteDatas.join(',')
      self.setData({
        bleNotifyData:data
      });
      console.log(data)
    });
  },

最后

写入和读取操作,我这里就不做过多说明,官方文档说的已经很明确了;

注意事项

在 ios 和 android 测试时,android 平台不需要获取 service 和 characteristic,就可以进行开启 notify ;而在 ios 平台必须手动的去获取你要操作的 service 和 characteristic,不然会 notify 不成功;

Github :

wechat-ble-demo

猜你喜欢

转载自blog.csdn.net/LABLENET/article/details/78492824