小程序蓝牙控制设备

小程序低功耗蓝牙控制设备

小程序控制蓝牙的过程&api
  1. 初始化蓝牙适配器wx.openBluetoothAdapter()
  2. 获取本机蓝牙链接状态wx.getBluetoothAdapterState()
  3. 开启搜索蓝牙wx.startBluetoothDevicesDiscovery()
  4. 获取所有蓝牙列表wx.getBluetoothDevices()
  5. 根据蓝牙列表匹配自己需要的广播蓝牙(厂商会给自己的设备规则),获取广播数据
  6. 把上一步匹配的到的蓝牙设备,进行连接wx.createBLEConnection()
  7. 连接成功,停止搜索wx.stopBluetoothDevicesDiscovery()
  8. 连接成功后,需要获取设备的uuid,设备特征值,发送指令需要用到wx.getBLEDeviceServices()
  9. 获取设备的characteristicId,发送指令需要用到wx.getBLEDeviceCharacteristics
  10. 发送密钥(密钥是从厂商获取到的)指令给门锁 wx.writeBLECharacteristicValue()
1. 初始化蓝牙适配器
initBluetoothAdapert function()(
	const that = this
	console.log("初始化蓝牙适配器");
	wx.openBluetoothAdapter({
	  success: function (res) {
		console.log("1.1获取自身蓝牙状态");
	    that.getBluetoothAdapterState();
	  },
	  fail: function (err) {
	    console.log(err);
	    wx.showToast({
	      title: '请检查您的蓝牙是否开启',
	      icon: 'success',
	      duration: 2000
	    })
	    setTimeout(function () {
	      wx.hideToast()
	    }, 2000)
	  }
	});
)

2.获取蓝牙适配器状态
getBluetoothAdapterState() {
    console.log('2.获取本机蓝牙连接状态')
    const that = this
    wx.getBluetoothAdapterState({
      success: function (res) {
        console.log("2.1获取本地蓝牙状态 available=true表示蓝牙已开启")
        console.log(res)
        if (res.available) {
          // 去搜索蓝牙
          that.startBluetoothDevicesDiscovery()
        } else {
          wx.showToast({
            title: '请打开您的蓝牙后重新尝试',
            icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function(res) {
        // 没有开启蓝牙 提示请打开蓝牙重新重试
      }
    })
  },

3. 搜索蓝牙设备
startBluetoothDevicesDiscovery: function () {
    console.log('2.1搜索蓝牙')
    var that = this;
    wx.showLoading({
      title: '正在搜索门锁信号'
    });
    wx.startBluetoothDevicesDiscovery({
      services: [],
      allowDuplicatesKey: false,
      success: function (res) {
        console.log('3.1 搜索到的蓝牙设备 然后获取列表')
        if (res.errCode == 0) {
          // 4.搜索到蓝牙
          that.getConnect(); // 获取蓝牙列表
        } else {
          // 没有搜索到蓝牙设备
 
        }
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },
4. 获取蓝牙设备列表

或者到设备的deviceId和mac, 去根据厂商的规则去匹配,然后只拿自己需要的这个设备蓝牙信息,把广播信息存一下,获取密钥的时候需要用得到

getConnectList: function() {
    var that = this;
    var timer = setInterval(function() {
        wx.getBluetoothDevices({ // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备
          success: function(res) {
   
            const mac = that.data.roomMac.toLowerCase()
            // 我这边的规则是mac地址大写匹配
      
            that.setData({
            	myAdData: '广播信息',
                deviceId: '设备Id'
                isFailed: true
            });
 
            if (that.data.myAdData) {
              clearInterval(timer);
              // 6. 匹配到自己的蓝牙设备 去链接 链接好了之后去获取秘钥发送请求
              that.createConnectBLE()
            } else {
              // 没有找到蓝牙设备
              wx.showModal({
                title: '提示',
                content: '没有连接到门锁,请近距离重新尝试',
                showCancel: false
              })
            }
          }
        });
      },
      3000);
    setTimeout(function() {
      if (!that.data.isFinded && !that.data.isConnected) {
        clearInterval(timer);
        that.setData({
          isFailed: false
        });
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '搜索蓝牙超时',
          showCancel: false
        })
      }
    }, 12000);
  },
5. 创建链接
  createConnectBLE: function() {
    console.log('创建蓝牙连接')
    const that = this
    wx.createBLEConnection({  // 连接蓝牙低功耗设备。
      deviceId: that.data.deviceId,
      timeout: 10000,
      success: function(res) {
        console.log(res);
        if (res.errCode == 0) {
          console.log('连接成功')
          that.setData({
            isConnected: true
          });
          console.log('停止蓝牙搜调用')
          wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
              console.log('停止蓝牙搜索成功')
              console.log(res)
            }
          })
          wx.stopBluetoothDevicesDiscovery(); // 如果已经找到, 停止搜寻附近的蓝牙外围设备。
          // 8. 链接成功后去获取设备信息(设备信息用来执行操作命令
          that.onGetuuid()
        } else {
          wx.showModal({
            title: '提示',
            content: '不能正常对蓝牙设备进行连接',
            showCancel: false
          })
        }
      },
      fail: (res) => {
        wx.hideLoading();
        if (res.errCode == 10012) {
          wx.showModal({
            title: '提示',
            content: '连接超时',
            showCancel: false
          })
        }
        console.warn("fail", res);
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },
6. 根据设备deviceId获取设备的uuid, 然后根据uuid获取characteristicId

两个api

onGetuuid :function(){
	wx.getBLEDeviceServices({
      deviceId,
      success(getServicesRes) {
        console.log("getServicesRes", getServicesRes);
        let service = getServicesRes.services[0]
        let uuid = service.uuid
        that.setData({
          uuid
        }) 
        wx.getBLEDeviceCharacteristics({
          deviceId,
          serviceId,
          success(getCharactersRes) {
            let characteristic = getCharactersRes.characteristics[0]
            let characteristicId = characteristic.uuid
            that.setData({
              characteristicId
            })
            // 去获取密钥指令 发送给设备
            that.getSecretKeyByBlue()
	      }
	    })
	  }
	)}
}
7.获取密钥指令发送给蓝牙
// 密钥自己去请求接口获取一下
// 这里直接去把获取的指令写入蓝牙
 writeBLECharacteristicValue(){
    var that = this
    var hex = that.data.secretKey  //要发送的信息
    console.log('要发送的信息是:'+hex)
    var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    var buffer1 = typedArray.buffer
    console.log('写入的buffer1')
    console.log(buffer1)
    console.log('写入的deviceId:' + that.data.deviceId)
    console.log('写入的serviceId:' + that.data.serviceId)
    console.log('写入的characteristicId:' + that.data.characteristicId)
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer1,
      success: function (res) {
        console.log('写入成功命令')
        console.log(res)
      },
      fail(res){
        console.log('写入成失败命令')
        console.log(res)
      }
    })
  }
})
  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值