微信小程序-蓝牙功能

这个比较简单

直接上代码

bash 复制代码
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);
          }
        })
      },
  },
});
相关推荐
YUJIAN。1 小时前
使用uniapp开发微信小程序-框架搭建
微信小程序·小程序·uni-app
关你西红柿子3 小时前
小程序app封装公用顶部筛选区uv-drop-down
前端·javascript·vue.js·小程序·uv
V+zmm101343 小时前
基于小程序宿舍报修系统的设计与实现ssm+论文源码调试讲解
java·小程序·毕业设计·mvc·ssm
V+zmm1013410 小时前
基于微信小程序的乡村政务服务系统springboot+论文源码调试讲解
java·微信小程序·小程序·毕业设计·ssm
还这么多错误?!10 小时前
uniapp微信小程序,使用fastadmin完成一个一键获取微信手机号的功能
微信小程序·小程序·uni-app
_院长大人_10 小时前
微信小程序用户信息解密 AES/CBC/NoPadding 解密失败问题
微信小程序·小程序
web1350858863510 小时前
uniapp小程序使用webview 嵌套 vue 项目
vue.js·小程序·uni-app
guanpinkeji11 小时前
废品回收小程序:助力企业转型发展
小程序·小程序开发·小程序制作·回收·废品回收小程序·废品回收
407指导员11 小时前
uniapp 微信小程序 页面部分截图实现
微信小程序·小程序·uni-app
三木吧14 小时前
开发微信小程序的过程与心得
人工智能·微信小程序·小程序