小程序蓝牙与设备传输数据-demo

本文详细介绍小程序与蓝牙设备通讯的步骤,包括蓝牙模块初始化、设备搜索、连接、读写及监听数据返回。涵盖分包写入、数据组包及错误处理等关键环节。

小程序与蓝牙设备通讯,总结一下分为下面几点

1.小程序初始化蓝牙模块
2.搜索设备
3.连接设备 获取蓝牙的所有服务以及服务对应的特征值,根据特征值进行读写和监听设备的数据返回
4. 写入数据
5. 读取蓝牙设备返回数据

下面我们看具体的实现步骤

初始化蓝牙模块

//初始化蓝牙
  openBluetoothAdapter() {
   
   
    var that = this;
    //初始化蓝牙模块
    wx.openBluetoothAdapter({
   
   
      success: (res) => {
   
   
        console.log('openBluetoothAdapter success', res)
        that.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
   
   
        console.log(res);
        if (res.errCode === 10001) {
   
   
          wx.onBluetoothAdapterStateChange(function (res) {
   
   
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
   
   
              that.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },

搜索蓝牙设备

//开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
   
   
    var that = this;
    if (that._discoveryStarted) {
   
   
      return
    }
    that._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
   
   
      allowDuplicatesKey: true,
      success: (res) => {
   
   
        console.log('startBluetoothDevicesDiscovery success', res)
        that.onBluetoothDeviceFound()
      },
    })
  },
  //停止搜寻附近的蓝牙外围设备
  stopBluetoothDevicesDiscovery() {
   
   
    wx.stopBluetoothDevicesDiscovery()
  },
  //监听寻找到新设备的事件
  onBluetoothDeviceFound() {
   
   
    var that = this;
    wx.onBluetoothDeviceFound((res) => {
   
   
      res.devices.forEach(device => {
   
   
        console.log(device);
        if (!device.name && !device.localName) {
   
   
          return
        }
        const foundDevices = that.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {
   
   }
        if (idx === -1) {
   
   
          data[`devices[${
     
     foundDevices.length
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值