微信小程序-蓝牙功能

这个比较简单

直接上代码

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);
          }
        })
      },
  },
});
相关推荐
難釋懷7 小时前
微信小程序全局配置
微信小程序·小程序
Enti7c7 小时前
微信小程序核心知识点速览
微信小程序·小程序
2501_9159184119 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
说私域21 小时前
从品牌附庸到自我表达:定制开发开源AI智能名片S2B2C商城小程序赋能下的营销变革
人工智能·小程序
難釋懷21 小时前
第一个小程序
小程序
春哥的研究所21 小时前
可视化DIY小程序工具!开源拖拽式源码系统,自由搭建,完整的源代码包分享
小程序·开源·开源拖拽式源码系统·开源拖拽式源码·开源拖拽式系统
weixin_lynhgworld21 小时前
盲盒一番赏小程序技术实现方案:高并发与防作弊的平衡之道
小程序
今日热点1 天前
小程序主体变更全攻略:流程、资料与异常处理方案
经验分享·微信·小程序·企业微信·微信公众平台·微信开放平台
鸭鸭梨吖1 天前
微信小程序---下拉框
微信小程序·小程序
CRMEB定制开发1 天前
CRMEB Pro版前端环境配置指南
前端·微信小程序·uni-app·商城源码·微信商城·crmeb