蓝牙

更新时间:

接口声明

{ "name": "blueos.bluetooth.bluetoothManager" }
复制代码

导入模块

 import bluetooth from '@blueos.bluetooth.bluetoothManager'var bluetooth = require("@blueos.bluetooth.bluetoothManager")
复制代码

开发者需要在 manifest.json 里面配置权限:

{
  "permissions": [{ "name": "watch.permission.BLUETOOTH" }]
}
复制代码

接口定义

bluetooth.startDevicesDiscovery(OBJECT)

开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源,请在搜索并连接到设备后调用 bluetooth.stopDevicesDiscovery 方法停止搜索。

参数:

参数名 类型 必填 说明
services String[] 要搜索的主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应 uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。
allowDuplicatesKey Boolean 默认值为 false。是否允许重复上报同一设备。如果允许重复上报,则 bluetooth.ondevicefound 方法会多次上报同一设备,但是 RSSI 值会有不同。
interval Number 单位毫秒,默认值为 0。上报设备的间隔。0 表示找到新设备立即上报,其他数值根据传入的间隔上报。
success Function 成功回调。
fail Function 失败回调。
complete Function 执行结束后的回调。

示例

bluetooth.startDevicesDiscovery({
  services: ['FEE7'],
  success: function () {
    console.log('success')
  },
})
复制代码

bluetooth.stopDevicesDiscovery(OBJECT)

停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。

OBJECT 参数:

参数名 类型 必填 说明
success Function 成功回调
fail Function 失败回调
complete Function 执行结束后的回调

示例

bluetooth.stopDevicesDiscovery({
  success: function () {
    console.log('success')
  },
  fail: function (data, code) {
    console.log(`handling fail, code = ${code}`)
  },
  complete: function () {
    console.log('complete')
  },
})
复制代码

bluetooth.onDeviceFound = function(data)

监听寻找到新设备的事件

data 返回值:

参数名 类型 描述
devices Object[] 新搜索到的设备列表

devices 返回值:

参数名 类型 描述
name String 蓝牙设备名称,某些设备可能没有
deviceId String 用于区分设备的 id
RSSI Number 当前蓝牙设备的信号强度
advertisData ArrayBuffer 当前蓝牙设备的广播数据段中的 ManufacturerData 数据段
advertisServiceUUIDs String[] 当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段
localName String 当前蓝牙设备的广播数据段中的 LocalName 数据段
serviceData Object 当前蓝牙设备的广播数据段中的 ServiceData 数据段,key 为 uuid 的 String 值,value 为对应的 ServiceData 的 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('')
}
bluetooth.onDeviceFound = function (data) {
  console.log('new device list has founded')
  data.devices.forEach((device) => {
    console.log(`handling find new devive:${JSON.stringify(device)}`)
    console.log(`handling advertisData = ${ab2hex(device.advertisData)}`)

    for (let key in device.serviceData) {
      console.log(
        `handling serviceData: uuid = ${key}, serviceData = ${ab2hex(device.serviceData[key])}`
      )
    }
  })
}
复制代码
上一篇
概述
下一篇
上传下载
以上内容对您是否有帮助?
  • 毫无帮助
  • 帮助不大
  • 一般
  • 很好
  • 非常好
意见反馈