微信小程序-蓝牙功能

这个比较简单
直接上代码


module.exports = Behavior({
  // 全局 data
  data: {
    espdeviceId: '9F06627E-3BFF-0CB2-D41C-DBCA272DC633',
    serviceId:"",
    writecharacteristicId:"",
    _discoveryStarted:false,
    isfundble:false,//匹配到对应的设配
    canWrite:false,
  },
  methods: {
      closeBle(){
            //关闭
          wx.closeBluetoothAdapter();
      },
      openBluetoothAdapter() {
        //蓝牙初始化动作
        wx.openBluetoothAdapter({
          mode:"central",
          success: (res) => {
            console.log('openBluetoothAdapter success', res)
            //开启蓝牙扫描
            this.startBluetoothDevicesDiscovery()
          },
          fail: (res) => {
            if (res.errCode === 10001) {
              //手机蓝牙没开启,请开启
              wx.onBluetoothAdapterStateChange(function (res) {
                console.log('onBluetoothAdapterStateChange', res)
                if (res.available) {
                  this.startBluetoothDevicesDiscovery()
                }
              })
            }
          }
        })
      },
      startBluetoothDevicesDiscovery() {
        //开始蓝牙扫描
        var that = this;
        if (that.data._discoveryStarted) {
          return
        }
        console.log("startBluetoothDevicesDiscovery.......")
        that.setData({_discoveryStarted:true});
        wx.startBluetoothDevicesDiscovery({
         // services:[],//只扫描这个设备
          success: (res) => {
            console.log('startBluetoothDevicesDiscovery success', res)
            that.onBluetoothDeviceFound();
          },
        })
      },
      onBluetoothDeviceFound() {
        //开始蓝牙配对
        var that = this;
        wx.onBluetoothDeviceFound((res) => {
          res.devices.forEach(device => {
            if (device.deviceId == that.data.espdeviceId) {
              //确认是配对的蓝牙设备
              console.log("connect success,name:",device.name);
              //godo 
              that.setData({isfundble:true});
              that.createBLEConnection(device.deviceId);
              //停止蓝牙扫描
              wx.offBluetoothDeviceFound();
              //停止蓝牙扫描
              wx.stopBluetoothDevicesDiscovery();
            }
          })
        })
      },
      createBLEConnection(getDeviceId) {
        //链接蓝牙
        var that = this;
        wx.createBLEConnection({
          deviceId:getDeviceId,
          success: (res) => {
            //链接服务
            that.getBLEDeviceServices(getDeviceId)
          },
          fail:(err)=>{
            if(err.errCode = -1){
              //链接服务
            that.getBLEDeviceServices(getDeviceId)
            }
          }
        })
      },
      getBLEDeviceServices(getDeviceId) {
        //获取蓝牙服务
        var that = this;
        wx.getBLEDeviceServices({
          deviceId:getDeviceId,
          success: (res) => {
            for (let i = 0; i < res.services.length; i++) {
              if (res.services[i].isPrimary) {
                //是主服务,才进行对话
                that.setData({serviceId :res.services[i].uuid});
                that.getBLEDeviceCharacteristics(getDeviceId, that.data.serviceId);
                return
              }
            }
          }
        })
      },
      getBLEDeviceCharacteristics(deviceId, serviceId) {
        //获取特征值,开启监听数据,开启写数据准备
        var that = this;
        wx.getBLEDeviceCharacteristics({
          deviceId,
          serviceId,
          success: (res) => {
            console.log('getBLEDeviceCharacteristics success', res.characteristics)
            for (let i = 0; i < res.characteristics.length; i++) {
              let item = res.characteristics[i];
              if (item.properties.read) {
                //开启读数据准备
                wx.readBLECharacteristicValue({
                  deviceId,
                  serviceId,
                  characteristicId: item.uuid,
                })
              }
              if (item.properties.write) {
                this.setData({canWrite:true,writecharacteristicId:item.uuid});
              }
              if (item.properties.notify || item.properties.indicate) {
                //支持通知,开启通知
                wx.notifyBLECharacteristicValueChange({
                  deviceId,
                  serviceId,
                  characteristicId: item.uuid,
                  state: true,
                  success:(res)=>{
                    //开启通知成功,开启监听read
                    wx.onBLECharacteristicValueChange(that.listenReadValueChange);
                  }
                })
              }
            }
          },
          fail(res) {
            console.error('getBLEDeviceCharacteristics', res)
          }
        })
      },
      listenReadValueChange(characteristic){
         //监听read 的数据值
          console.log(characteristic.deviceId);
          console.log(ab2hex(characteristic.value));
         
      },
      // ArrayBuffer转16进制字符串示例
     ab2hex(buffer) {
        let hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function(bit) {
            return ('00' + bit.toString(16)).slice(-2)
          }
        )
        return hexArr.join('');
      },
      writeBLECharacteristicValue(leddata) {
        console.log("write msg");
        var that = this;
        // 向蓝牙设备发送一个0x00的16进制数据
        let buffer = new ArrayBuffer(1)
        let dataView = new DataView(buffer)
        dataView.setUint8(0, leddata);
        wx.writeBLECharacteristicValue({
          deviceId: that.data.espdeviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.writecharacteristicId,
          value: buffer,
          success:(res)=>{
            console.log("send msg:"+res)
          },
          fail:(err)=>{
            console.log(err);
          }
        })
      },
  },
});

你可能感兴趣的:(微信小程序,notepad++,小程序)