1.准备

低功耗蓝牙模块:(链接)蓝牙模块购买通道 相关参数数据(UUID表):

android 低功耗蓝牙 作为服务 低功耗蓝牙uuid_蓝牙模块

需要知道服务ID(serviceID)响应特征值 ID(notify characteristic UUID)写特征值ID(write characteristic UUID),AT指令可不用管。

2.自动链接时的推荐流程图

借鉴大神的,我认为逻辑很清晰,所以引用在此。

android 低功耗蓝牙 作为服务 低功耗蓝牙uuid_android 低功耗蓝牙 作为服务_02


本流程图是为了完成以后的特定模块的自动连接准备。现在只需要完成蓝牙(BLE)每一步的功能。

3.低功耗蓝牙步骤

  • 1、 开启蓝牙适配
    wx.openBluetoothAdapter(Object object)
  • 2、 获取蓝牙适配器状态,判断设备蓝牙是否可用。
    wx.getBluetoothAdapterState(Object object)
  • 3、 开启扫描蓝牙设备
    wx.startBluetoothDevicesDiscovery(Object object)
  • 4、 获取蓝牙设备列表
    wx.getBluetoothDevices(Object object)
  • 5、 连接某个已发现的设备
    wx.createBLEConnection(Object object)
  • 6、 停止搜索蓝牙设备
    wx.stopBluetoothDevicesDiscovery(Object object)
  • 7、 获取蓝牙设备服务
  • wx.getBLEDeviceServices(Object object)
  • 8、 获取服务下的所有特征值
    wx.getBLEDeviceCharacteristics(Object object)
  • 9、 启用响应特征值变化
    wx.notifyBLECharacteristicValueChange(Object object)
  • 10、接收蓝牙的返回信息
    wx.onBLECharacteristicValueChange(function callback)
  • 11、发送信息
    wx.writeBLECharacteristicValue(Object object))
  • 12、断开蓝牙设备的连接
    wx.closeBLEConnection(Object object)
    上诉述蓝牙相关API 函数详情见微信官方开发文档:官方低功耗蓝牙接口API函数说明

4.微信小程序源代码

1 .wxml文件

<view class="contentview">
 
  <view  class='myview'>
    <text>
      {{info}}
    </text>
  </view>
 
  <button type="primary" class="button" bindtap="BLEInit">初始化蓝牙</button>
  <button type="primary" class="button" bindtap="BLEState">获取蓝牙状态</button>
  <button type="primary" class="button" bindtap="BLESearch">搜索设备</button>
  <button type="primary" class="button" bindtap="BLEGetDevices">获取所有设备</button>
  <block wx:for="{{devices}}" wx:key="{{test}}">
    <button type="primary" class="button" id="{{item.deviceId}}" style='background-color:red' 
    bindtap="BLEConnect">{{item.name}}</button>
  </block>
  <button type="primary" class="button" bindtap="BLESearchStop">停止搜索</button>
  <button type="primary" class="button" bindtap="BLEGetservice">获取service</button>
  <button type="primary" class="button" bindtap="BLEGetCharacteristics">获取Character</button>
  <button type="primary" class="button" bindtap="BLECharacteristicValueChange">启用特征值变化</button>
  <button type="primary" class="button" bindtap="BLEDataRecieve">接收蓝牙返回消息</button>
  <view class="section">
  <input placeholder='请输入要发送的信息' bindinput='getmsg'/>
  </view>
  <button type="primary" class="button" bindtap="BLEDataSend">微信发送消息</button>
  <button type="primary" class="button" bindtap="BLEDisconnect">12断开蓝牙设备</button>
</view>

2 .wxss文件

.contentview {
margin: 0 10px;
}
 
.button {
margin: 5px;
}
 
.myview{
  height:200px;
  word-break:break-all;/* 自动换行 */
}

3 .js文件

Page
({
  data: 
  {
    info:"",                //显示框
    devices:"",             //所有搜索到的蓝牙设备
    connectedDeviceId:"",   //连接上的设备的ID
    services: "" ,          //连接上设备的所有服务
    notifyCharacteristicsId: "0000FEE1-0000-1000-8000-00805F9B34FB", //响应UUID,根据蓝牙模块获得
    writeCharacteristicsId:  "0000FEE2-0000-1000-8000-00805F9B34FB", //写UUID, 根据蓝牙模块获得
  },
 
  
  /****************1.蓝牙初始化***************/
  BLEInit(event)
  {
      var that = this;
      wx.openBluetoothAdapter
      ({
          success: function (res) 
          {
            console.log('初始化蓝牙适配器成功')
            that.setData
            ({
              info: '初始化蓝牙适配器成功'
            })
          },
          fail: function (res) 
          {
            console.log('请打开蓝牙和定位功能')
            that.setData
            ({
              info: '请打开蓝牙和定位功能'
            })
          }
      })
  },


  /****************2.获取蓝牙状态***************/
  BLEState(event)
  {
    var that = this;
    wx.getBluetoothAdapterState
    ({
        success: function (res) 
        {
          //打印相关信息
          console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available);

          that.setData
          ({
              info: JSON.stringify(res.errMsg) +"\n蓝牙是否可用:" + res.available
          })
        },

        fail: function (res) 
        {
          //打印相关信息
          console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available);

          that.setData
          ({
              info: JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available
          })
        }
    })
 
  },


  /****************3.搜索设备**************/
  BLESearch(event)
  {
    var that = this;
    wx.startBluetoothDevicesDiscovery
    ({
        services: ['0000FEE0-0000-1000-8000-00805F9B34FB'], //如果填写了此UUID,那么只会搜索出含有这个UUID的设备,建议一开始先不填写
        success: function (res) 
        {
          that.setData
          ({
              info: "搜索设备" + JSON.stringify(res),
          })

          console.log('搜索设备返回' + JSON.stringify(res))
        }
    })
  },


  /****************4.获取蓝牙设备***************/
  BLEGetDevices(event)
  {
    var that = this;
    wx.getBluetoothDevices
    ({
        success: function (res) 
        {
          that.setData
          ({
            info: "设备列表\n" + JSON.stringify(res.devices),
            devices: res.devices
          })

          console.log('搜设备数目:' + res.devices.length)
          console.log('设备信息:\n' + JSON.stringify(res.devices)+"\n")
        }
    })
  },


   /****************5.连接蓝牙设备***************/
  BLEConnect(event)
  {
    var that = this;
    wx.createBLEConnection
    ({
      deviceId: event.target.id,
      success: function (res) 
      {
        console.log('调试信息:' + res.errMsg);
        that.setData
        ({
          connectedDeviceId: event.currentTarget.id,
          info: "MAC地址:" + event.currentTarget.id  + '  调试信息:' + res.errMsg,
        })
      },
      fail: function () 
      {
        console.log("连接失败");
      },
    })
  },


  /****************6.停止搜索蓝牙设备***************/
  BLESearchStop(event)
  {
    var that = this;
    wx.stopBluetoothDevicesDiscovery
    ({
      success: function (res) 
      {
        console.log("停止搜索" + JSON.stringify(res.errMsg));
        that.setData
        ({
          info: "停止搜索"  + JSON.stringify(res.errMsg),
        })
      }
    })
  },


  /****************7.获取服务service***************/
  BLEGetservice(event)
  {
    var that = this;
    wx.getBLEDeviceServices
    ({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: that.data.connectedDeviceId,

      success: function (res) 
      {
        console.log('services UUID:\n', JSON.stringify(res.services));
        for (var i = 0; i < res.services.length; i++) 
        {
          console.log("第"+(i+1) + "个UUID:" + res.services[i].uuid+"\n")
        }
        that.setData
        ({
          services: res.services,
          info: JSON.stringify(res.services),
        })
      }
    })
  },
 

  /****************8.获取所有的特征值***************/
  BLEGetCharacteristics(event)
  {
    var that = this;

    wx.getBLEDeviceCharacteristics
    ({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 中获取
      deviceId: that.data.connectedDeviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services[0].uuid,

      success: function (res) 
      {
        console.log("%c getBLEDeviceCharacteristics", "color:red;");

        for (var i = 0; i < res.characteristics.length; i++) 
        {
          console.log('特征值:' + res.characteristics[i].uuid)
 
          if (res.characteristics[i].properties.notify) 
          {
              console.log("打印notifyCharacteristicsId")
              console.log(that.data.notifyCharacteristicsId)
          }

          if (res.characteristics[i].properties.write)
          {
              console.log("打印writeCharacteristicsId")
              console.log(that.data.writeCharacteristicsId)
          }
        }
        console.log('device getBLEDeviceCharacteristics:', JSON.stringify(res.characteristics));
      },

      fail: function () 
      {
        console.log("获取所有特征值失败");
      },
    })
  },


  /****************9.启用特征值变化***************/
  BLECharacteristicValueChange(event)
  {
    var that = this;

    console.log("启用的notifyCharacteristicsId", that.data.notifyCharacteristicsId);
 
    wx.notifyBLECharacteristicValueChange
    ({
      state: true,
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.services[0].uuid,
      characteristicId: that.data.notifyCharacteristicsId,

      success: function (res) 
      {
        console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        var msg = '启动notify:' + res.errMsg
        that.setData({
          info: msg
        })
      },
      fail: function () 
      {
        console.log('启动notify:' + res.errMsg);
      },
      
    })
  },


  /****************10.接收蓝牙的返回数据***************/
  BLEDataRecieve(event)
  {
    var that = this;
    console.log("开始接收数据");

    wx.onBLECharacteristicValueChange
    (
      function (res) 
      {
        console.log("characteristicId:" + res.characteristicId)
        console.log("serviceId:" + res.serviceId)
        console.log("deviceId" + res.deviceId)
        console.log("Length:" + res.value.byteLength)
        console.log("hexvalue:" + ab2hex(res.value))
        that.setData
        ({
          info: that.data.info + ab2hex(res.value)
        })
      }
    )
  },

/****************11.蓝牙发送数据***************/
  BLEDataSend(event)
  {
    var that = this
    var hex = that.data.sendmsg  //要发送的信息

    console.log('要发送的信息是:'+hex)

    var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))

    console.log(typedArray)

    var buffer1 = typedArray.buffer

    wx.writeBLECharacteristicValue
    ({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.services[0].uuid,
      characteristicId: that.data.writeCharacteristicsId,

      // 这里的value是ArrayBuffer类型
      value: buffer1,

      success: function (res) 
      {
        console.log('写入成功', res.errMsg)
      },
      fail(res)
      {
        console.log('写入失败', res.errMsg)
      }
    })
  },
 
  /****************12.断开蓝牙的连接***************/
  BLEDisconnect(event)
  {
    var that = this;
    wx.closeBLEConnection
    ({
        deviceId: that.data.connectedDeviceId,
        success: function (res) 
        {
          that.setData
          ({
            connectedDeviceId: "",
          })
          console.log('断开蓝牙设备成功:' + res.errMsg)
        },
        fail:function(res)
        {
          console.log('断开蓝牙设备失败:' + res.errMsg)
        }
    })
  },


  //获取输入框的数据
  getmsg(event){
    this.setData({
      sendmsg:event.detail.value
    })
    
  },
 
})


// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(',');
}

5.总结

1.搜寻操作比较耗费系统资源,请在搜索并连接到设备后调用 wx.stopBluetoothDevicesDiscovery 方法停止搜索。