微信小程序-蓝牙功能

这个比较简单

直接上代码

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);
          }
        })
      },
  },
});
相关推荐
ace_TiAmo43 分钟前
React8+taro开发微信小程序,实现lottie动画
微信小程序·小程序·react·taro
老李不敲代码2 小时前
榕壹云在线商城系统:基于THinkPHP+ Mysql+UniApp全端适配、高效部署的电商解决方案
mysql·微信小程序·小程序·uni-app·软件需求
专业系统开发老赵4 小时前
小程序租赁系统源码功能分享
小程序
小咕聊编程6 小时前
【含文档+PPT+源码】基于微信小程序的卫生院预约挂号管理系统的设计与实现
微信小程序·小程序
夜猫的兔子8 小时前
微信小程序中使用ECharts 并且动态设置数据
微信小程序·小程序·echarts
爱分享的淘金达人11 小时前
25年河南事业单位报名详细流程图解
java·python·小程序·tomcat·流程图
2305_7978820912 小时前
美食推荐小程序
大数据·微信小程序·小程序
forestsea21 小时前
Python进阶编程总结
开发语言·python·notepad++
peachSoda71 天前
uniapp小程序生成海报/图片并保存分享
小程序·uni-app
说私域1 天前
社交电商引流策略中的让利行为及其影响——基于开源AI智能名片、链动2+1模式与S2B2C商城小程序的分析
人工智能·小程序·开源·产品运营·零售