8、获取蓝牙设备所有service(getBLEDeviceServices)

wx.getBLEDeviceServices(Object object)

基础库 1.1.0 开始支持,低版本需做兼容处理

获取蓝牙设备所有服务(service)。

参数

Object object

属性类型默认值必填说明
deviceIdstring 蓝牙设备 id
successfunction 接口调用成功的回调函数
failfunction 接口调用失败的回调函数
completefunction 接口调用结束的回调函数(调用成功、失败都会执行)

object.success 回调函数

参数

Object res

属性类型说明
servicesArray.<Object>设备服务列表

res.services 的结构

属性类型说明
uuidstring蓝牙设备服务的 uuid
isPrimaryboolean该服务是否为主服务

 

lanyatest.wxml代码:

<!--pages/lanyatest/lanyatest.wxml-->
<view class="contentview">

  <view  class='myview' >
    
      {{info}}
    

  </view>

  <button type="primary" class="button" bindtap="lanyatest1">1初始化蓝牙</button>
  <button type="primary" class="button" bindtap="lanyatest2">2获取蓝牙状态</button>
  <button type="primary" class="button" bindtap="lanyatest3">3搜索周边设备</button>
  <button type="primary" class="button" bindtap="lanyatest4">4获取所有设备</button>
  <block wx:for="{{devices}}" wx:key="{{test}}">
    <button type="primary" class="button" id="{{item.deviceId}}" style='background-color:red' bindtap="lanyaconnect">5连接{{item.name}}         </button>
  </block>
  <button type="primary" class="button" bindtap="lanyatest6">6停止搜索周边蓝牙设备</button>
  <button type="primary" class="button" bindtap="lanyatest7">7获取所有service</button>
</view>

 

lanyatest.js代码:

// pages/lanyatest/lanyatest.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info:"未初始化蓝牙适配器",
    connectedDeviceId:"",
    deviceId:"",
    services:""
  },

  lanyatest1(event){
    var that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log('初始化蓝牙适配器成功')
        //页面日志显示
        that.setData({
          info: '初始化蓝牙适配器成功'
        })
      },
      fail: function (res) {
        console.log('请打开蓝牙和定位功能')
        that.setData({
          info: '请打开蓝牙和定位功能'
        })
      }
    })
  },



  lanyatest2(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
        })

      }
      
    })

  },



  lanyatest3(event){
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      services: ['FEE7'], //如果填写了此UUID,那么只会搜索出含有这个UUID的设备,建议一开始先不填写或者注释掉这一句
      success: function (res) {
        that.setData({
          info: "搜索设备" + JSON.stringify(res),
        })
        console.log('搜索设备返回' + JSON.stringify(res))

      }
    })

  },




  lanyatest4(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")
      }
    })

  },



  lanyaconnect(event){
    var that = this;
    wx.createBLEConnection({
      deviceId: event.currentTarget.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("连接失败");
      },

    })

  },


  lanyatest6(event){
    var that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("停止搜索" + JSON.stringify(res.errMsg));
        that.setData({
          info: "停止搜索"  + JSON.stringify(res.errMsg),
        })
      }
    })

  },



  lanyatest7(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),
        })
      }
    })

  },



//我删除了自动生成的生命周期函数

})

lanyatest.wxss代码:

/* pages/lanyatest/lanyatest.wxss */
.vertical{
  display: flex;
  flex-direction: column;
}

/**index.wxss**/
.horizontal{
  display: flex;
  flex-direction: row;
}

.btinfo{
  height:100px;
}

.contentview {
margin: 0 10px;
}
 
.button {
margin: 5px;
}

.myview{
  height:200px;
  word-break:break-all;/* 自动换行 */
}

真机调试结果:

 

 

 

 

 

微信小程序可以通过使用蓝牙 API 来读取蓝牙设备返回的数据。下面是一个简单的示例代码,演示如何读取蓝牙设备的数据: ```javascript // 开始搜索蓝牙设备 wx.startBluetoothDevicesDiscovery({ success: function (res) { // 监听蓝牙设备发现事件 wx.onBluetoothDeviceFound(function (devices) { // 遍历发现的蓝牙设备列表 devices.devices.forEach(function (device) { // 判断是否是目标设备 if (device.deviceId === 'YOUR_DEVICE_ID') { // 停止搜索蓝牙设备 wx.stopBluetoothDevicesDiscovery(); // 连接目标设备 wx.createBLEConnection({ deviceId: 'YOUR_DEVICE_ID', success: function (res) { // 监听蓝牙连接状态改变事件 wx.onBLEConnectionStateChange(function (res) { if (!res.connected) { console.log('蓝牙设备已断开连接'); } }); // 获取蓝牙设备的服务列表 wx.getBLEDeviceServices({ deviceId: 'YOUR_DEVICE_ID', success: function (res) { // 遍历服务列表 res.services.forEach(function (service) { // 判断是否是目标服务 if (service.uuid === 'YOUR_SERVICE_UUID') { // 获取服务的特征值列表 wx.getBLEDeviceCharacteristics({ deviceId: 'YOUR_DEVICE_ID', serviceId: service.uuid, success: function (res) { // 遍历特征值列表 res.characteristics.forEach(function (characteristic) { // 判断是否是目标特征值 if (characteristic.uuid === 'YOUR_CHARACTERISTIC_UUID') { // 开始监听蓝牙设备的特征值变化 wx.onBLECharacteristicValueChange(function (res) { // 处理接收到的数据 var data = ab2hex(res.value); console.log('收到数据:', data); }); // 启用低功耗蓝牙设备特征值变化通知 wx.notifyBLECharacteristicValueChange({ deviceId: 'YOUR_DEVICE_ID', serviceId: service.uuid, characteristicId: characteristic.uuid, state: true, success: function (res) { console.log('已开启数据接收'); } }); } }); } }); } }); } }); } }); } }); }); } }); // 将 ArrayBuffer 转为十六进制字符串 function ab2hex(buffer) { var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2); }); return hexArr.join(''); } ``` 在示例代码中,你需要将 `YOUR_DEVICE_ID` 替换为目标蓝牙设备的 ID,将 `YOUR_SERVICE_UUID` 替换为目标服务的 UUID,将 `YOUR_CHARACTERISTIC_UUID` 替换为目标特征值的 UUID。 请注意,读取蓝牙设备返回的数据需要在小程序的蓝牙权限设置中开启并获取用户授权。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值