小程序操作蓝牙进行读写

小程序操作蓝牙进行读写

本文讲述小程序使用蓝牙进行数据的读写。
这篇将是全代码,但关键地方都会有注释。

一、打开适配器

initBLE:function(back) {
   
   
	wx.openBluetoothAdapter({
   
    success(res){
   
   
	    // ===== 打开成功 =====
	    this.searchBLE();		// 开始搜索蓝牙外设
	    // 在蓝牙打开的情况下突然关闭
        wx.onBluetoothAdapterStateChange(function (res) {
   
   
          if (!res.available) {
   
    //蓝牙适配器是否可用
              this.setData({
   
   
                  tipsBox: "tipsBox",
                  tipsTitle: "温馨提示",
                  tipsContent: "蓝牙未打开,请重新打开蓝牙"
              })
          }
        })
	},fail(err) {
   
   
	    wx.showToast({
   
   
           title: '请检查手机蓝牙是否打开',
            icon: 'none',
        })
      }
	})
},

二、搜索蓝牙外设

// 开始搜索
searchBLE() {
   
   
    let that =this;
    BLEMag.bluetoothMag.startMonitorBluetoothSearch({
   
   
        success(res) {
   
   
            that.monitorSearchDevice(); // 监听蓝牙搜索回调
            that.searchDevice(); // 开始蓝牙搜索
        }
    });
},

// 监听蓝牙搜索回调
monitorSearchDevice() {
   
   
  var that = this;
  wx.startBluetoothDevicesDiscovery({
   
   
      allowDuplicatesKey: true,
      interval: 0,
      // ===== 搜索打开成功 =====
      success: function () {
   
   
          that.setData({
   
   
              showProgress: false
          })
      },
      // ===== 搜索打开失败 =====
      fail: function (res) {
   
   
          that.failCallback('蓝牙设备服务发现失败')
          that.printLog("蓝牙设备服务发现失败: " + res.errMsg);
      }
  })
},

// 搜索蓝牙
searchDevice:function(back) {
   
   
  var that = this;
  var deviceArr = [];
  wx.onBluetoothDeviceFound(function (res) {
   
   
    res.devices.forEach(device => {
   
   
    	// TODO 
    	// 做搜索到设备的处理
    	wx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值