当前位置:   article > 正文

微信小程序-蓝牙功能

微信小程序-蓝牙功能

这个比较简单
直接上代码


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);
          }
        })
      },
  },
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/151137
推荐阅读
相关标签
  

闽ICP备14008679号