微信小程序:蓝牙通讯,搜索、发送与接收

这篇博客详细介绍了如何使用微信小程序通过蓝牙与硬件设备进行交互,包括初始化蓝牙、查找和连接蓝牙设备、发送数据以及监听设备数据变化的过程。示例代码展示了从查找设备到连接设备,再到发送指令和接收应答的完整流程。
摘要由CSDN通过智能技术生成

需求背景

使用微信小程序,通过蓝牙与硬件设备产品进行交互

参考文档

微信小程序蓝牙通讯

开始

1.初始化蓝牙

initBlue: function () {
    var that = this
    wx.openBluetoothAdapter({
      success: function (res) {
        that.findBlue()
      },
      fail: function (res) {
        wx.showToast({
          title: '请打开手机蓝牙!',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }

2.查找蓝牙

findBlue() {
    var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        that.getBlue()
      }
    })
  },

  getBlue() {
    var that = this
    var searchResult = false
    var index = 0

    wx.showLoading({
      title: '搜索设备...',
    })

    //定时搜索
    var interval = setInterval(function () {
      wx.getBluetoothDevices({
        success: function (res) {
          index = index + 1
          if (!searchResult) {
            for (var i = 0; i < res.devices.length; i++) {
              //根据设备名称匹配   这里的meterId是需要匹配的设备名称
              if ((res.devices[i].name + "").substr(0, 16) == that.data.meterId ||
                (res.devices[i].localName + "").substr(0, 16) == that.data.meterId) {
                that.setData({
                  //获取蓝牙设备的deviceId
                  deviceId: res.devices[i].deviceId,
                })

                searchResult = true
                if (searchResult) {
                  clearInterval(interval)
                }
                //连接蓝牙
                that.connetBlue(res.devices[i].deviceId)
                return
              }
            }
          }

          if (index > 20) {
            clearInterval(interval)
            wx.hideLoading()
            wx.showToast({
              title: '未找到设备,请重试!',
              icon: 'none',
              duration: 2000
            })
            wx.stopBluetoothDevicesDiscovery() //关闭蓝牙搜索
          }
        }
      })
    }, 500)
  }

3.连接蓝牙设备

connetBlue(deviceId) {
    var that = this

    wx.hideLoading()
    wx.showLoading({
      title: '连接设备...',
    })

    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
        wx.stopBluetoothDevicesDiscovery() //关闭蓝牙搜索
        that.getServiceId() //获取服务ID
      },
      fail: function () {
        wx.hideLoading()
        wx.showToast({
          title: '连接设备失败!',
          icon: 'none',
          duration: 2000
        })
        wx.stopBluetoothDevicesDiscovery() //关闭蓝牙搜索
      }
    })
  },

  getServiceId() {
    var that = this
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success: function (res) {
        var model = res.services[0]
        that.setData({
          serviceId: model.uuid
        })
        that.getCharacteId()
      }
    })
  },

  getCharacteId() {
    var that = this

    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; i++) {
          var model = res.characteristics[i]
          if (model.properties.notify == true) {
            that.setData({
              notifyId: model.uuid
            })

            //重点:开启监听服务。监听设备数据变化
            that.startNotice(model.uuid)
          }
          if (model.properties.write == true) {
            that.setData({
              writeId: model.uuid
            })
          }
        }

        //有可写权限
        if (that.data.writeId != '') {
          wx.hideLoading()
          wx.showLoading({
            title: '通讯中...',
          })

          //这里可以完成需要下发到设备上的指令的生成
          that.sendCmd(value)
        } else {
          wx.showToast({
            title: '失败: 设备无写入权限!',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }

4.发送数据

 sendCmd(cmdValue) {
    var that = this

    if (cmdValue != '' && cmdValue != null && cmdValue != undefined) {
      that.writeCharacterToDevice(util.stringToArrayBuffer(cmdValue))
    } else {
      wx.showToast({
        title: '获取设备指令失败',
        icon: 'none',
        duration: 2000
      })
    }
  }

 writeCharacterToDevice(buffer) {
    var that = this

    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.writeId,
      value: buffer,
      fail: function () {
        wx.showToast({
          title: '写入设备数据失败!',
          icon: 'none',
          duration: 2000
        })

      },
      success: function () {
        wx.showLoading({
          title: '指令发送成功',
          duration: 2000
        })
      }
    })
  }

5.工具函数


  function stringToArrayBuffer(str) {
  var bytes = new Array();
  var len, c;
  len = str.length;
  for (var i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if (c >= 0x010000 && c <= 0x10FFFF) {
      bytes.push(((c >> 18) & 0x07) | 0xF0);
      bytes.push(((c >> 12) & 0x3F) | 0x80);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000800 && c <= 0x00FFFF) {
      bytes.push(((c >> 12) & 0x0F) | 0xE0);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000080 && c <= 0x0007FF) {
      bytes.push(((c >> 6) & 0x1F) | 0xC0);
      bytes.push((c & 0x3F) | 0x80);
    } else {
      bytes.push(c & 0xFF);
    }
  }
  var array = new Int8Array(bytes.length);
  for (var i in bytes) {
    array[i] = bytes[i];
  }
  return array.buffer;
}

function arrayBufferToString(arr) {
  if (typeof arr === 'string') {
    return arr;
  }
  var dataview = new DataView(arr);
  var ints = new Uint8Array(arr.byteLength);
  for (var i = 0; i < ints.length; i++) {
    ints[i] = dataview.getUint8(i);
  }
  arr = ints;
  var str = '',
    _arr = arr;
  for (var i = 0; i < _arr.length; i++) {
    var one = _arr[i].toString(2),
      v = one.match(/^1+?(?=0)/);
    if (v && one.length == 8) {
      var bytesLength = v[0].length;
      var store = _arr[i].toString(2).slice(7 - bytesLength);
      for (var st = 1; st < bytesLength; st++) {
        store += _arr[st + i].toString(2).slice(2);
      }
      str += String.fromCharCode(parseInt(store, 2));
      i += bytesLength - 1;
    } else {
      str += String.fromCharCode(_arr[i]);
    }
  }
  return str;
}

6.开启事件监听

  /**
   * 监听水表数据变化
   * @param {水表ID} uuid 
   */
  startNotice(uuid) {
    var that = this

    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: uuid,
      success: function (res) {
        var deviceResult = ''
        //特征数据变化
        wx.onBLECharacteristicValueChange(function (res) {
          deviceResult = deviceResult + util.arrayBufferToString(res.value) //应答数据比较长,会触发多次
          //如果应答帧总长度大于数据包长度,并且包含“16”,则说明是完整的应答帧
          if (deviceResult.lastIndexOf('16') >= (deviceResult.length - 8) && deviceResult.indexOf('68') >= 0) {
            //解析应答帧  这里开始对设备应答数据进行处理了
            
            deviceResult = ''
          }
        })
      }
    })
  },

设备应答数据也可以发送到后台服务进行处理,根据具体业务而定

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 要让ESP32通过蓝牙发送数据到微信小程序,你可以使用ESP32内置的蓝牙模块,以及微信小程序提供的蓝牙API接口。 以下是一些基本步骤: 1. 使用Arduino IDE或其他编程工具,编写ESP32的蓝牙发送程序。例如,你可以使用Arduino蓝牙库,通过Serial通信接口将数据发送到ESP32内置的蓝牙模块。 2. 在微信小程序中,使用微信提供的蓝牙API接口,连接到ESP32的蓝牙模块,并接收来自ESP32的数据。例如,你可以使用wx.createBLEConnection()函数建立连接,使用wx.onBLECharacteristicValueChange()函数监听数据变化事件,以及使用wx.readBLECharacteristicValue()函数读取数据。 需要注意的是,蓝牙连接和数据传输的稳定性需要根据具体情况进行优化。同时,你需要确保ESP32和微信小程序之间的通信协议一致,例如数据格式、编码方式等。 ### 回答2: ESP32是一款功能强大的开发板,它支持蓝牙功能,并可以通过蓝牙将数据发送微信小程序进行接收。 在ESP32上,我们可以使用它内置的蓝牙模块来实现数据的发送。首先,我们需要在ESP32上启用蓝牙功能,并创建一个蓝牙服务,用于发送数据。可以使用ESP-IDF开发框架来实现这些功能。 接下来,在微信小程序中,我们需要使用wx.startBluetoothDevicesDiscovery函数来启用蓝牙设备的搜索功能。然后,使用wx.onBluetoothDeviceFound函数来监听蓝牙设备的发现事件,并获取到ESP32的蓝牙设备信息。 一旦微信小程序找到了ESP32的蓝牙设备,我们可以使用wx.createBLEConnection函数来建立与ESP32蓝牙设备的连接。 连接建立之后,可以使用wx.onBLEConnectionStateChange函数来监听蓝牙连接状态的变化,并在连接成功后发送数据请求到ESP32。 在ESP32上,当接收到来自微信小程序的数据请求时,可以通过蓝牙通信协议进行通信。ESP32可以将需要发送的数据打包成特定格式的数据包,并通过蓝牙发送微信小程序。 在微信小程序中,可以使用wx.onBLECharacteristicValueChange函数监听从ESP32接收到的数据,并进行处理。 总而言之,通过在ESP32上启用蓝牙功能,并在微信小程序中使用蓝牙接口进行连接和数据接收处理,我们可以实现ESP32向微信小程序发送数据的功能。这样,我们就可以利用ESP32和微信小程序相互通信,实现更多有趣的功能。 ### 回答3: ESP32是一种高集成度的蓝牙Wi-Fi芯片,可以用于无线传输数据。要在ESP32上发送数据到微信小程序蓝牙接收端,需要经过以下几个步骤: 1. 配置ESP32的蓝牙模块:首先,需要在ESP32上配置蓝牙模块,使其能够与其他设备进行通信。可以使用Arduino编程语言来编写代码,在代码中引入ESP32的蓝牙库,并设置蓝牙的名称和特性。 2. 连接微信小程序蓝牙接收端:在微信小程序中,需要使用wx.getBLEDevice函数获取到ESP32的蓝牙设备对象。然后通过wx.createBLEConnection函数进行连接。 3. 发送数据:一旦连接建立,就可以使用ESP32的蓝牙发送函数发送数据。可以使用ESP32的蓝牙库提供的函数来发送字符串、数字或二进制数据。 4. 接收数据:在微信小程序中,可以通过wx.onBLECharacteristicValueChange事件监听接收到的数据。当ESP32蓝牙发送数据时,该事件将被触发,从而可以获取到接收到的数据。 需要注意的是,ESP32和微信小程序蓝牙接收端的通信需要使用相同的数据格式和通信协议。通常情况下,可以使用文本字符串作为通信格式,例如发送JSON格式的数据。 总之,要实现ESP32蓝牙发送数据到微信小程序蓝牙接收端,需要先配置ESP32的蓝牙模块,然后在微信小程序中建立连接并监听接收到的数据。通过这种方式,可以实现两者之间的无线数据传输。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值