文档管理中心
我的
API参考快应用API系统能力蓝牙

蓝牙

接口声明

在manifest.json文件的 features属性中增加如下配置。

收起
自动换行
深色代码主题
复制
  1. {"name": "system.bluetooth"}

导入模块

在调用接口页面的<script>部分增加如下配置。

收起
自动换行
深色代码主题
复制
  1. import bluetooth from '@system.bluetooth'

或

收起
自动换行
深色代码主题
复制
  1. var bluetooth = require("@system.bluetooth")

使用限制

展开

限制条件

说明

适用终端

手机、平板、车机

适用区域

全球

接口定义

展开

接口

描述

bluetooth.openAdapter(OBJECT)

初始化蓝牙模块。

bluetooth.closeAdapter(OBJECT)

关闭蓝牙模块。

bluetooth.getAdapterState(OBJECT)

获取本机蓝牙适配器状态。

bluetooth.onadapterstatechange(OBJECT)

监听蓝牙适配器状态变化事件。

bluetooth.startDevicesDiscovery(OBJECT)

开始搜寻附近的蓝牙外围设备。

bluetooth.stopDevicesDiscovery(OBJECT)

停止搜寻附近的蓝牙外围设备。

bluetooth.getDevices(OBJECT)

获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。

bluetooth.ondevicefound(OBJECT)

监听寻找到新设备的事件。

bluetooth.getConnectedDevices(OBJECT)

根据 uuid 获取处于已连接状态的设备。

bluetooth.createBLEConnection(OBJECT)

连接低功耗蓝牙设备。

bluetooth.closeBLEConnection(OBJECT)

断开与低功耗蓝牙设备的连接。

bluetooth.getBLEDeviceServices(OBJECT)

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

bluetooth.getBLEDeviceCharacteristics(OBJECT)

获取蓝牙设备某个服务中所有特征值(characteristic)。

bluetooth.readBLECharacteristicValue(OBJECT)

读取低功耗蓝牙设备的特征值的二进制数据值。

bluetooth.writeBLECharacteristicValue(OBJECT)

向低功耗蓝牙设备特征值中写入二进制数据。

bluetooth.notifyBLECharacteristicValueChange(OBJECT)

启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。

bluetooth.onblecharacteristicvaluechange(OBJECT)

监听低功耗蓝牙设备的特征值变化。

bluetooth.onbleconnectionstatechange(OBJECT)

监听低功耗蓝牙连接状态的改变事件。

bluetooth.getDevicesBattery(OBJECT)

查询华为蓝牙耳机的电量。

bluetooth.openAdapter(OBJECT)

描述

初始化蓝牙模块。

OBJECT参数

展开

参数

类型

是否必填

说明

operateAdapter

boolean

否

是否打开系统蓝牙开关。

设置为true,在系统蓝牙开关关闭的情况下会弹框提示是否打开。

默认值false。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.openAdapter({
  2. operateAdapter: true,
  3. success: function () {
  4. console.log("success");
  5. },
  6. fail: function () {
  7. console.log("fail");
  8. },
  9. complete: function () {
  10. console.log("complete");
  11. }
  12. })

bluetooth.closeAdapter(OBJECT)

描述

关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。建议在使用蓝牙流程后,与bluetooth.openAdapter成对调用。

OBJECT参数

展开

参数

类型

是否必填

说明

operateAdapter

boolean

否

是否关闭系统蓝牙开关。

设置为true,调用时会关闭系统蓝牙开关。

默认值false。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.closeAdapter({
  2. success:function(){
  3. console.log("success");
  4. },
  5. fail: function() {
  6. console.log("fail");
  7. },
  8. complete: function (){
  9. console.log("complete");
  10. }
  11. })

bluetooth.getAdapterState(OBJECT)

描述

获取本机蓝牙适配器状态。

OBJECT参数

展开

参数

类型

是否必填

说明

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

success返回值:

展开

参数名

类型

说明

available

boolean

蓝牙适配器是否可用。

discovering

boolean

是否正在搜索设备。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.getAdapterState({
  2. success:function(){
  3. console.log("success");
  4. },
  5. fail: function() {
  6. console.log("fail");
  7. },
  8. complete: function (){
  9. console.log("complete");
  10. }
  11. })

bluetooth.onadapterstatechange(OBJECT)

描述

监听蓝牙适配器状态变化事件。

返回值

展开

参数名

类型

说明

available

boolean

蓝牙适配器是否可用。

discovering

boolean

蓝牙适配器是否处于搜索状态。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.onadapterstatechange = function (event) {
  2. console.log('adapterState changed, now is', event.available)
  3. }

bluetooth.startDevicesDiscovery(OBJECT)

描述

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

OBJECT参数

展开

参数

类型

是否必填

说明

services

array.<string>

否

要搜索的主service的uuid列表。某些蓝牙设备会广播自己的主service的uuid。如果设置此参数,则只搜索广播包有对应uuid的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。

allowDuplicatesKey

boolean

否

默认值为false。是否允许重复上报同一设备。如果允许重复上报,则 bluetooth.ondevicefound 方法会多次上报同一设备,但是RSSI值会有不同。

interval

number

否

默认值为0。上报设备的间隔。0表示找到新设备立即上报,其他数值根据传入的间隔上报。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.startDevicesDiscovery({
  2. services: ['FEE7'],
  3. success: function () {
  4. console.log("success")
  5. }
  6. })

bluetooth.stopDevicesDiscovery(OBJECT)

描述

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

OBJECT参数

展开

参数

类型

是否必填

说明

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.stopDevicesDiscovery({
  2. success:function(){
  3. console.log("success");
  4. },
  5. fail: function() {
  6. console.log("fail");
  7. },
  8. complete: function (){
  9. console.log("complete");
  10. }
  11. })

bluetooth.getDevices(OBJECT)

描述

获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。

OBJECT参数

展开

参数

类型

是否必填

说明

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

success返回值:

展开

参数名

类型

说明

devices

array.<string>

uuid对应的的已连接设备列表,devices结构请参见“devices说明”。

devices说明:

展开

参数名

类型

说明

name

string

蓝牙设备名称,某些设备可能没有。

deviceId

string

用于区分设备的id。

RSSI

number

当前蓝牙设备的信号强度。

advertisData

arraybuffer

当前蓝牙设备的广播数据段中的 ManufacturerData 数据段。

advertisServiceUUIDs

array.<string>

当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段。

localName

string

当前蓝牙设备的广播数据段中的 LocalName 数据段。

serviceData

string

当前蓝牙设备的广播数据段中的 ServiceData数据段,返回结构为{"service uuid string": ArrayBuffer}。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.getDevices({
  2. success:function(res){
  3. console.log(res)
  4. if (res.devices[0]) {
  5. console.log(res.devices[0].advertisData)
  6. }
  7. },
  8. fail: function() {
  9. console.log("fail");
  10. },
  11. complete: function (){
  12. console.log("complete");
  13. }
  14. })

bluetooth.ondevicefound(OBJECT)

描述

监听寻找到新设备的事件。

返回值

展开

参数名

类型

说明

devices

array.<object>

新搜索到的设备列表。devices结构请参见“devices说明”。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.ondevicefound = function (event) {
  2. console.log('new device list has founded')
  3. }

bluetooth.getConnectedDevices(OBJECT)

描述

根据 uuid 获取处于已连接状态的设备。

OBJECT参数

展开

参数

类型

是否必填

说明

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

services

array.<string>

是

蓝牙设备主 service 的 uuid 列表。

success返回值:

展开

参数名

类型

说明

devices

array.<string>

uuid对应的的已连接设备列表,devices结构请参见“连接devices说明”。

连接devices说明:

展开

参数名

类型

说明

name

string

蓝牙设备名称,某些设备可能没有。

deviceId

string

用于区分设备的id。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.getConnectedDevices({
  2. services:['uuid'],
  3. success:function(res){
  4. console.log(res)
  5. if (res.devices[0]) {
  6. console.log(res.devices[0].name)
  7. }
  8. },
  9. fail:function() {
  10. console.log("fail");
  11. },
  12. complete:function (){
  13. console.log("complete");
  14. }
  15. })

bluetooth.createBLEConnection(OBJECT)

描述

连接低功耗蓝牙设备。

若快应用有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

用于区分设备的 id。

timeout

number

否

超时时间,单位ms,不填表示不会超时。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.createBLEConnection({
  2. deviceId:deviceId,
  3. success:function(){
  4. console.log("success");
  5. },
  6. fail: function() {
  7. console.log("fail");
  8. },
  9. complete: function (){
  10. console.log("complete");
  11. }
  12. })

bluetooth.closeBLEConnection(OBJECT)

描述

断开与低功耗蓝牙设备的连接。

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

用于区分设备的 id。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.closeBLEConnection({
  2. deviceId:deviceId,
  3. success:function(){
  4. console.log("success");
  5. },
  6. fail: function() {
  7. console.log("fail");
  8. },
  9. complete: function (){
  10. console.log("complete");
  11. }
  12. })

bluetooth.getBLEDeviceServices(OBJECT)

描述

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

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

蓝牙设备 id。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

success返回值:

展开

参数名

类型

说明

services

array.<object>

设备服务列表,services结构请参见“services说明”。

services说明:

展开

参数名

类型

说明

uuid

string

蓝牙设备服务的 uuid。

isPrimary

boolean

该服务是否为主服务。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.getBLEDeviceServices({
  2. deviceId:deviceId,
  3. success:function(res){
  4. console.log('device services:', res.services)
  5. },
  6. fail: function() {
  7. console.log("fail");
  8. },
  9. complete: function (){
  10. console.log("complete");
  11. }
  12. })

bluetooth.getBLEDeviceCharacteristics(OBJECT)

描述

获取蓝牙设备某个服务中所有特征值(characteristic)。

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

蓝牙设备 id。

serviceId

string

是

蓝牙服务uuid,需要使用 getBLEDeviceServices 获取。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

success返回值:

展开

参数名

类型

说明

characteristics

array.<object>

设备服务列表,characteristics结构请参见“characteristics说明”。

characteristics说明:

展开

参数名

类型

说明

uuid

string

蓝牙设备特征值的 uuid。

properties

object

该特征值支持的操作类型,properties结构请参见“properties说明”。

properties说明:

展开

参数名

类型

说明

read

boolean

该特征值是否支持 read 操作

write

boolean

该特征值是否支持 write 操作

notify

boolean

该特征值是否支持 notify 操作

indicate

boolean

该特征值是否支持 indicate 操作

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.getBLEDeviceCharacteristics({
  2. deviceId:deviceId,
  3. serviceId:serviceId,
  4. success:function(res){
  5. console.log('device getBLEDeviceCharacteristics:',
  6. res.characteristics)},
  7. fail: function() {
  8. console.log("fail");
  9. },
  10. complete: function (){
  11. console.log("complete");
  12. }
  13. })

bluetooth.readBLECharacteristicValue(OBJECT)

描述

读取低功耗蓝牙设备的特征值的二进制数据值。

注意

必须设备的特征值支持 read 才可以成功调用。

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

蓝牙设备 id。

serviceId

string

是

蓝牙特征值对应服务的 uuid。

characteristicId

string

是

蓝牙特征值的 uuid。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.readBLECharacteristicValue(
  2. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  3. deviceId:deviceId,
  4. // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  5. serviceId:serviceId,
  6. // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  7. characteristicId,
  8. success:function() {
  9. console.log("success")
  10. })

bluetooth.writeBLECharacteristicValue(OBJECT)

描述

向低功耗蓝牙设备特征值中写入二进制数据。

注意

必须设备的特征值支持 write 才可以成功调用。

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

蓝牙设备 id。

serviceId

string

是

蓝牙特征值对应服务的 uuid。

characteristicId

string

是

蓝牙特征值的 uuid。

说明

uuid中的字母需要是小写,不能是大写,否则会提示10008错误。

value

arraybuffer

是

蓝牙设备特征值对应的二进制值。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.writeBLECharacteristicValue({
  2. // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound
  3. //接口中获取
  4. deviceId:deviceId,
  5. // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  6. serviceId:serviceId,
  7. // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  8. characteristicId:characteristicId,
  9. // 这里的value是ArrayBuffer类型
  10. value: buffer,
  11. success:function(){
  12. console.log("success");
  13. },
  14. fail: function() {
  15. console.log("fail");
  16. },
  17. complete: function (){
  18. console.log("complete");
  19. }
  20. })

bluetooth.notifyBLECharacteristicValueChange(OBJECT)

描述

启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。

注意

必须设备的特征值支持 notify 或者 indicate 才可以成功调用。

必须先启用notifyBLECharacteristicValueChange才能监听到设备 characteristicValueChange 事件。

OBJECT参数

展开

参数

类型

是否必填

说明

deviceId

string

是

蓝牙设备 id。

serviceId

string

是

蓝牙特征值对应服务的 uuid。

characteristicId

string

是

蓝牙特征值的 uuid。

state

boolean

是

是否启用 notify。

success

function

否

成功回调。

fail

function

否

失败回调。

complete

function

否

执行结束后的回调。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.notifyBLECharacteristicValueChange({
  2. state: true, // 启用 notify 功能
  3. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  4. deviceId:deviceid,
  5. // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  6. serviceId:serviceId,
  7. // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  8. characteristicId:characteristicId,
  9. success:function(){
  10. console.log("success")
  11. },
  12. fail: function() {
  13. console.log("fail");
  14. },
  15. complete: function (){
  16. console.log("complete");
  17. }
  18. })

bluetooth.onblecharacteristicvaluechange(OBJECT)

描述

监听低功耗蓝牙设备的特征值变化。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。

返回值

展开

参数名

类型

说明

deviceId

string

蓝牙设备 id。

serviceId

string

蓝牙特征值对应服务的 uuid。

characteristicId

string

蓝牙特征值的 uuid。

value

arraybuffer

特征值最新的值。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.onblecharacteristicvaluechange = function (event) {
  2. console.log(event.value)
  3. }

bluetooth.onbleconnectionstatechange(OBJECT)

描述

监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等。

callback返回值

展开

参数名

类型

说明

deviceId

string

蓝牙设备id。

connected

boolean

是否处于已连接状态。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.onbleconnectionstatechange = function(res){
  2. console.log(‘device’+ res.deviceId+‘state has changed,connected:’+res.connected)
  3. }

bluetooth.getDevicesBattery(OBJECT)(1078+,非厂商联盟规范)

描述

查询华为蓝牙耳机的电量。

OBJECT参数

展开

参数

类型

是否必填

说明

mac

String

是

蓝牙耳机的mac地址。

success

Function

否

成功回调。

fail

Function

否

失败回调。

complete

Function

否

执行结束后的回调。

success返回值:

展开

参数

类型

说明

batteryValue

Object

电量。

-1表示未知状态,0~100表示剩余电量的百分比。

chargeState

Object

充电状态。

  • -1:未知状态
  • 0:未充电
  • 1:充电中

infoStr

String

整体电量情况。

返回数据示例如下:

{"chargeState":{"1":-1,"2":0,"3":1,"4":0},"batteryValue":{"1":-1,"2":55,"3":100,"4":65},"infoStr":"6,2,55,3,0,4,100,5,1,6,65,7,0"}

chargeState和batteryValue信息的参数值含义如下:

  • 代表normal(当前无实际意义)
  • 代表left(左耳机)
  • 代表right(右耳机)
  • 代表charger(盒子)

fail返回值:

展开

参数

说明

errCode

错误码。

errMsg

错误信息。

错误码说明:

展开

错误码

说明

200

其他通用错误。

示例代码

收起
自动换行
深色代码主题
复制
  1. bluetooth.getDevicesBattery({
  2. mac: "XX:XX:XX:XX:XX:XX",
  3. success: function (data) {
  4. console.log('getDevicesBattery success data = ' + JSON.stringify(data));
  5. },
  6. fail: function (errMsg, errCode) {
  7. console.log('getDevicesBattery fail errMsg = ' + errMsg + '; errCode = ' + errCode);
  8. },
  9. complete: function () {
  10. console.log('getDevicesBattery complete .');
  11. }
  12. })

状态码

展开

错误码

错误信息

说明

0

ok

正常

10000

not init

未启动连接。

10001

not available

当前蓝牙适配器不可用。

10002

no device

没有找到指定设备。

10003

connection fail

连接失败。

10004

no service

没有找到指定服务。

10005

no characteristic

没有找到指定特征值。

10006

no connection

当前连接已断开。

10007

property not support

当前特征值不支持此操作。

10008

system error

其余所有系统上报的异常。

10009

system not support

系统版本低于 5.0 不支持 BLE。

Demo

收起
自动换行
深色代码主题
复制
  1. <template>
  2. <div class="container">
  3. <div class="item-content">
  4. <text class="txt">openBluetooth:{{openBluetoothSuccess}}</text>
  5. </div>
  6. <input type="button" class="btn" onclick="openAdapter" value="open Bluetooth" />
  7. <div class="item-content">
  8. <text class="txt">closeBluetooth:{{closeBluetoothSuccess}}</text>
  9. </div>
  10. <input type="button" class="btn" onclick="closeAdapter" value="close Bluetooth" />
  11. <div class="item-content">
  12. <text class="txt"> getAdapterState:{{bluetoothstate}}</text>
  13. </div>
  14. <input type="button" class="btn" onclick="getAdapterState" value="get Adapter State" />
  15. <input type="button" class="btn" onclick="onAdapterState" value="on Adapter State" />
  16. <div class="input-item">
  17. <text class="input-hint">bluetooth.inputUuid</text>
  18. <input class="input-text" placeholder="please input bluetooth.uuid" onchange="oninput"></input>
  19. </div>
  20. <div class="item-content">
  21. <text
  22. class="txt">bluetoothDiscoveryDevices:{{bluetoothdevices}}</text>
  23. </div>
  24. <input type="button" class="btn" onclick="startBluetoothDevicesDiscovery" value="bluetooth discoveryDevices" />
  25. <div class="item-content">
  26. <text class="txt">stopDiscovery:{{stopDiscoverSuccess}}</text>
  27. </div>
  28. <input type="button" class="btn" onclick="stopBluetoothDevicesDiscovery" value="bluetooth stopDiscoveryDevices" />
  29. <div class="item-content">
  30. <text class="txt">getBluetoothDevices:{{bluetoothdevices}}</text>
  31. </div>
  32. <input type="button" class="btn" onclick="getBluetoothDevices" value="bluetooth getBluetoothDevices" />
  33. <div class="input-item">
  34. <text class="input-hint">bluetooth.inputDeviceId</text>
  35. <input class="input-text" placeholder="deviceId" onchange="oninputdeviceId"></input>
  36. </div>
  37. <div class="item-content">
  38. <text class="txt">connectBluetoothDevice:{{connectionstate}}</text>
  39. </div>
  40. <input type="button" class="btn" onclick="createBLEConnection" value="Connects to a BLE device" />
  41. <div class="item-content">
  42. <text class="txt"> disconnectBluetooth :{{closeconnectionstate}}</text>
  43. </div>
  44. <input type="button" class="btn" onclick="closeBLEConnection" value="Disconnects from a BLE device" />
  45. <div class="item-content">
  46. <text
  47. class="txt">getBluetoothDevicesService:{{deviceservices}}</text>
  48. </div>
  49. <input type="button" class="btn" onclick="getBLEDeviceServices" value="getBluetoothAllDevicesService" />
  50. <div class="item-content">
  51. <text class="txt">getConnectedDevices:{{connecteddevices}}</text>
  52. </div>
  53. <input type="button" class="btn" onclick="getConnectedDevices" value="get ConnectedDevices" />
  54. <div class="input-item">
  55. <text class="input-hint">bluetooth.inputServiceId</text>
  56. <input class="input-text" placeholder="serviceId" onchange="oninputserviceId"></input>
  57. </div>
  58. <div class="item-content">
  59. <text
  60. class="txt">getBLEDeviceCharacteristics:{{servicecharacters}}</text>
  61. </div>
  62. <input type="button" class="btn" onclick="getBLEDeviceCharacteristics" value="get BLEDeviceCharacteristics" />
  63. <div class="input-item">
  64. <text class="input-hint">inputCharacteristicId</text>
  65. <input class="input-text" placeholder="characteristicId" onchange="oninputcharacteristicId"></input>
  66. </div>
  67. <div class="input-item">
  68. <text class="input-hint">bluetooth.toggleNotify</text>
  69. <input class="input-text" type="checkbox" onchange="oninputnotifystate"></input>
  70. </div>
  71. <div class="item-content">
  72. <text class="txt">notifyBLECharacteristicValueChange:{{notifyBLECharacteristicValue}}</text>
  73. </div>
  74. <input type="button" class="btn" onclick="notifyBLECharacteristicValueChange" value="notify BLECharacteristicValueChange" />
  75. <input type="button" class="btn" onclick="onblecharacteristicvaluechange" value="on blecharacteristicvaluechange" />
  76. <div class="item-content">
  77. <text
  78. class="txt">SpecifyBluetoothServiceFeatureValue:{{characteristicsvalue}}</text>
  79. </div>
  80. <input type="button" class="btn" onclick="readBLECharacteristicValue" value="read BLECharacteristicValue" />
  81. <div class="input-item">
  82. <text class="input-hint">inputByteStringValue</text>
  83. <input class="input-text" placeholder="byteStringValue" onchange="oninputbyteStringValue"></input>
  84. </div>
  85. <div class="item-content">
  86. <text
  87. class="txt">writeCharacteristicValue:{{writecharacteristicsvalue}}</text>
  88. </div>
  89. <input type="button" class="btn" onclick="writeBLECharacteristicValue" value="write CharacteristicValue" />
  90. <div class="item-content">
  91. <text
  92. class="txt">lowpowerBleconnectionstate:{{bleconnectionstate}}</text>
  93. </div>
  94. <input type="button" class="btn" onclick="onbleconnectionstatechange" value="on bleconnectionstatechange" />
  95. <div class="input-item">
  96. <text class="input-hint">inputmac</text>
  97. <input class="input-text" placeholder="mac" onchange="oninputmac"></input>
  98. </div>
  99. <div class="item-content">
  100. <text class="txt">batteryLevel:{{bluetoothElectricity}}</text>
  101. </div>
  102. <input type="button" class="btn" onclick="getBatteryLevel" value="get Devices Battery" />
  103. </div>
  104. </template>
  105. <style>
  106. .container{
  107. flex: 1;
  108. flex-direction: column;
  109. }
  110. .item-container {
  111. margin-bottom: 50px;
  112. margin-right: 60px;
  113. margin-left: 60px;
  114. flex-direction: column;
  115. }
  116. .item-content {
  117. flex-direction: column;
  118. background-color: #ffffff;
  119. padding-left: 30px;
  120. padding-right: 30px;
  121. padding-top: 20px;
  122. padding-bottom: 20px;
  123. margin-bottom: 30px;
  124. align-items: flex-start;
  125. }
  126. .txt {
  127. padding-top: 15px;
  128. padding-bottom: 15px;
  129. }
  130. .input-item {
  131. margin-bottom: 80px;
  132. flex-direction: column;
  133. }
  134. .input-hint {
  135. margin-left: 30px;
  136. margin-bottom: 30px;
  137. margin-right: 30px;
  138. }
  139. .input-text {
  140. height: 80px;
  141. line-height: 80px;
  142. padding-left: 30px;
  143. padding-right: 30px;
  144. margin-left: 30px;
  145. margin-right: 30px;
  146. border-top-width: 1px;
  147. border-bottom-width: 1px;
  148. border-color: #999999;
  149. font-size: 30px;
  150. background-color: #ffffff;
  151. }
  152. .btn {
  153. height: 80px;
  154. text-align: center;
  155. border-radius: 5px;
  156. margin-right: 60px;
  157. margin-left: 60px;
  158. margin-bottom: 50px;
  159. color: #ffffff;
  160. font-size: 30px;
  161. background-color: #0faeff;
  162. }
  163. </style>
  164. <script>
  165. import bluetooth from '@system.bluetooth'
  166. export default {
  167. data: {
  168. componentName: 'bluetooth',
  169. componentData: {},
  170. openBluetoothSuccess: '',
  171. closeBluetoothSuccess: '',
  172. bluetoothstate: '',
  173. bluetoothdevices: '',
  174. connectStatus: '',
  175. bluetoothElectricity: '',
  176. stopDiscoverSuccess: '',
  177. connectionstate: '',
  178. closeconnectionstate: '',
  179. connecteddevices: '',
  180. notifyBLECharacteristicValue: '',
  181. scanedresult: '',
  182. deviceservices: '',
  183. servicecharacters: '',
  184. characteristicsvalue: '',
  185. writecharacteristicsvalue: '',
  186. bleconnectionstate: '',
  187. deviceIdInput: '',
  188. serviceId: '',
  189. serviceMac: '',
  190. service_psd: '',
  191. service_uuid: '',
  192. service_uuidarray: [],
  193. characteristics_uuid: '',
  194. byteStringValue: '',
  195. byteValue: '',
  196. deviceId: '',
  197. notifystate: false,
  198. ble_isonnectting: false,
  199. characteristics: []
  200. },
  201. onInit: function () {
  202. this.$page.setTitleBar({ text: 'bluetooth' })
  203. this.componentData = this.$t('message.interface.system.bluetooth')
  204. },
  205. openAdapter() {
  206. var that = this
  207. that.openBluetoothSuccess = ''
  208. bluetooth.openAdapter({
  209. operateAdapter: true,
  210. success: function (res) {
  211. console.log('openBluetoothAdapter success')
  212. that.openBluetoothSuccess = 'success'
  213. },
  214. fail: function (erromsg, errocode) {
  215. console.log('openBluetoothAdapter fail')
  216. that.openBluetoothSuccess = 'code ' + errocode + ' errormsg ' + erromsg
  217. },
  218. complete: function () {
  219. console.log('openBluetoothAdapter complete')
  220. }
  221. })
  222. },
  223. closeAdapter() {
  224. var that = this
  225. bluetooth.closeAdapter({
  226. operateAdapter: true,
  227. success: function () {
  228. console.log('closeAdapter success')
  229. that.closeBluetoothSuccess = 'success'
  230. },
  231. fail: function (erromsg, errocode) {
  232. console.log('closeAdapter fail')
  233. that.closeBluetoothSuccess = 'code ' + errocode + ' errormsg ' + erromsg
  234. },
  235. complete: function () {
  236. console.log('closeAdapter complete')
  237. }
  238. })
  239. },
  240. getAdapterState() {
  241. var that = this
  242. bluetooth.getAdapterState({
  243. success: function (res) {
  244. console.log('getBluetoothAdapterState success', res)
  245. var available = res.available
  246. var discovering = res.discovering
  247. that.bluetoothstate = 'available ' + available + ' discovering ' + discovering
  248. },
  249. fail: function (erromsg, errocode) {
  250. console.log('getAdapterState fail')
  251. that.bluetoothstate = 'code ' + errocode + ' errormsg ' + erromsg
  252. },
  253. complete: function () {
  254. console.log('getAdapterState complete')
  255. }
  256. })
  257. },
  258. onAdapterState() {
  259. var that = this
  260. console.log("on blooth state");
  261. bluetooth.onadapterstatechange = function (res) {
  262. console.log('adapterState changed, now is', res)
  263. var available = res.available
  264. var discovering = res.discovering
  265. that.bluetoothstate = 'available ' + available + ' discovering ' + discovering
  266. }
  267. },
  268. startBluetoothDevicesDiscovery: function () {
  269. var that = this
  270. console.log('startBluetoothDevicesDiscovery begin ' + that.service_uuidarray)
  271. bluetooth.startDevicesDiscovery({
  272. services: that.service_uuidarray,
  273. allowDuplicatesKey: false,
  274. success: function (res) {
  275. console.log('startBluetoothDevicesDiscovery success', res)
  276. that.onBluetoothDeviceFound()
  277. },
  278. fail: function (erromsg, errocode) {
  279. console.log('startBluetoothDevicesDiscovery fail ', erromsg)
  280. that.bluetoothdevices = 'code ' + errocode + ' errormsg ' + erromsg
  281. }
  282. })
  283. },
  284. stopBluetoothDevicesDiscovery: function () {
  285. var that = this
  286. console.log('stopBluetoothDevicesDiscovery begin')
  287. bluetooth.stopDevicesDiscovery({
  288. success: function (res) {
  289. console.log('stopBluetoothDevicesDiscovery success ', res)
  290. that.stopDiscoverSuccess = 'success'
  291. },
  292. fail: function (erromsg, errocode) {
  293. console.log('stopBluetoothDevicesDiscovery fail ', erromsg)
  294. that.stopDiscoverSuccess = 'code ' + errocode + ' errormsg ' + erromsg
  295. }
  296. })
  297. },
  298. onBluetoothDeviceFound: function () {
  299. var that = this
  300. var devicefound = false
  301. console.log('onBluetoothDeviceFound begin')
  302. // Monitor scan
  303. bluetooth.ondevicefound = function (res) {
  304. console.log(that.componentData.monitorSearchNewDevices, res)
  305. that.bluetoothdevices = JSON.stringify(res)
  306. if (Array.isArray(res.devices)) {
  307. for (var i = 0; i < res.devices.length; i++) {
  308. console.log(res.devices[i].name)
  309. if (res.devices[i].name === 'HUAWEI Mate 20') {
  310. that.deviceId = res.devices[i].deviceId
  311. devicefound = true
  312. break
  313. }
  314. }
  315. }
  316. if (devicefound) {
  317. that.stopBluetoothDevicesDiscovery()
  318. }
  319. }
  320. },
  321. getBluetoothDevices() {
  322. var that = this
  323. console.log('getBluetoothDevices begin')
  324. bluetooth.getDevices({
  325. success: function (res) {
  326. console.log('getBluetoothDevices success', res)
  327. that.bluetoothdevices = JSON.stringify(res)
  328. if (res.devices[0]) {
  329. console.log(res.devices[0].deviceId)
  330. console.log(res.devices[0].name)
  331. }
  332. },
  333. fail: function (erromsg, errocode) {
  334. console.log('getBluetoothDevices fail ', erromsg)
  335. that.bluetoothdevices = 'code ' + errocode + ' errormsg ' + erromsg
  336. },
  337. complete: function () {
  338. console.log('getBluetoothDevices complete')
  339. }
  340. })
  341. },
  342. createBLEConnection() {
  343. var that = this
  344. console.log('createBLEConnection begin deviceId ' + that.deviceId)
  345. bluetooth.createBLEConnection({
  346. deviceId: that.deviceId,
  347. success: function (res) {
  348. console.log('createBLEConnection success', res)
  349. that.connectionstate = 'success'
  350. },
  351. fail: function (erromsg, errocode) {
  352. console.log('createBLEConnection fail ', erromsg)
  353. that.connectionstate = 'code ' + errocode + ' errormsg ' + erromsg
  354. },
  355. complete: function () {
  356. console.log('createBLEConnection complete')
  357. }
  358. })
  359. },
  360. getBatteryLevel() {
  361. var that = this
  362. console.log('getBatteryLevel begin deviceId ' + that.mac)
  363. bluetooth.getDevicesBattery({
  364. mac: that.mac,
  365. success: function (res) {
  366. // console.log('getBatteryLevel success', res)
  367. console.log('getDevicesBattery success data = ' + JSON.stringify(res));
  368. that.bluetoothElectricity = res.batteryValue
  369. },
  370. fail: function (erromsg, errocode) {
  371. console.log('getBatteryLevel fail ', erromsg,errocode)
  372. that.bluetoothElectricity = 'code ' + errocode + ' errormsg ' + erromsg
  373. },
  374. complete: function () {
  375. console.log('getBatteryLevel complete')
  376. }
  377. })
  378. },
  379. closeBLEConnection() {
  380. var that = this
  381. console.log('closeBLEConnection begin deviceId ' + that.deviceId)
  382. bluetooth.closeBLEConnection({
  383. deviceId: that.deviceId,
  384. success: function (res) {
  385. console.log('closeBLEConnection success', res)
  386. that.closeconnectionstate = 'success'
  387. },
  388. fail: function (erromsg, errocode) {
  389. console.log('closeBLEConnection fail ', erromsg)
  390. that.closeconnectionstate = 'code ' + errocode + ' errormsg ' + erromsg
  391. },
  392. complete: function () {
  393. console.log('closeBLEConnection complete')
  394. }
  395. })
  396. },
  397. getBLEDeviceServices() {
  398. var that = this
  399. console.log('getBLEDeviceServices begin deviceId ' + that.deviceId)
  400. bluetooth.getBLEDeviceServices({
  401. deviceId: that.deviceId,
  402. success: function (res) {
  403. console.log('getBLEDeviceServices success', res)
  404. that.deviceservices = JSON.stringify(res)
  405. if (Array.isArray(res.services)) {
  406. for (var i = 0; i < res.services.length; i++) {
  407. console.log(res.services[i].uuid)
  408. if (res.services[i].isPrimary) {
  409. that.service_uuid = res.services[i].uuid
  410. console.log('getBLEDeviceServices service_uuid ', that.service_uuid)
  411. break
  412. }
  413. }
  414. }
  415. },
  416. fail: function (erromsg, errocode) {
  417. console.log('getBLEDeviceServices fail ', erromsg)
  418. that.deviceservices = 'code ' + errocode + ' errormsg ' + erromsg
  419. },
  420. complete: function () {
  421. console.log('getBLEDeviceServices complete')
  422. }
  423. })
  424. },
  425. getConnectedDevices() {
  426. var that = this
  427. // Here you need to get the device first, then connect, then get the services of the device, and then pass in the main uuid of the service.
  428. console.log('getConnectedDevices begin')
  429. bluetooth.getConnectedDevices({
  430. services: that.service_uuidarray,
  431. success: function (res) {
  432. console.log('getConnectedDevices success', res)
  433. that.connecteddevices = JSON.stringify(res)
  434. if (res.devices[0]) {
  435. console.log(res.devices[0].deviceId)
  436. console.log(res.devices[0].name)
  437. }
  438. },
  439. fail: function (erromsg, errocode) {
  440. console.log('getConnectedDevices fail ', erromsg)
  441. that.connecteddevices = 'code ' + errocode + ' errormsg ' + erromsg
  442. },
  443. complete: function () {
  444. console.log('getBluetoothDevices complete')
  445. }
  446. })
  447. },
  448. getBLEDeviceCharacteristics() {
  449. var that = this
  450. console.log('getBLEDeviceCharacteristics begin deviceId ' + that.deviceId)
  451. bluetooth.getBLEDeviceCharacteristics({
  452. deviceId: that.deviceId,
  453. serviceId: that.service_uuid,
  454. success: function (res) {
  455. console.log('getBLEDeviceCharacteristics success', res)
  456. that.servicecharacters = JSON.stringify(res)
  457. if (Array.isArray(res.characteristics)) {
  458. for (var i = 0; i < res.characteristics.length; i++) {
  459. console.log(res.characteristics[i].uuid)
  460. if (res.characteristics[i].properties.write) {
  461. that.characteristics_uuid = res.characteristics[i].uuid
  462. console.log('getBLEDeviceCharacteristics characteristics_uuid ', that.characteristics_uuid)
  463. break
  464. }
  465. }
  466. }
  467. },
  468. fail: function (erromsg, errocode) {
  469. console.log('getBLEDeviceCharacteristics fail ', erromsg)
  470. that.servicecharacters = 'code ' + errocode + ' errormsg ' + erromsg
  471. },
  472. complete: function () {
  473. console.log('getBLEDeviceCharacteristics complete')
  474. }
  475. })
  476. },
  477. readBLECharacteristicValue() {
  478. var that = this
  479. console.log('readBLECharacteristicValue begin deviceId ' + that.deviceId)
  480. console.log('readBLECharacteristicValue begin serviceId ' + that.service_uuid)
  481. console.log('readBLECharacteristicValue begin characteristicId ' + that.characteristics_uuid)
  482. bluetooth.readBLECharacteristicValue({
  483. deviceId: that.deviceId,
  484. serviceId: that.service_uuid,
  485. characteristicId: that.characteristics_uuid,
  486. success: function (res) {
  487. console.log('readBLECharacteristicValue success', res)
  488. },
  489. fail: function (erromsg, errocode) {
  490. console.log('readBLECharacteristicValue fail ', 'code ' + errocode + ' errormsg ' + erromsg)
  491. that.characteristicsvalue = 'code ' + errocode + ' errormsg ' + erromsg
  492. },
  493. complete: function () {
  494. console.log('readBLECharacteristicValue complete')
  495. }
  496. })
  497. },
  498. writeBLECharacteristicValue() {
  499. var that = this
  500. console.log('writeBLECharacteristicValue begin deviceId ' + that.deviceId)
  501. console.log('writeBLECharacteristicValue begin serviceId ' + that.service_uuid)
  502. console.log('writeBLECharacteristicValue begin characteristicId ' + that.characteristics_uuid)
  503. // Send a 0x00 hexadecimal data to the Bluetooth device
  504. let buffer = new ArrayBuffer(1)
  505. let dataView = new DataView(buffer)
  506. dataView.setUint8(0, 0)
  507. that.byteValue = that.stringToByte(that.byteStringValue)
  508. bluetooth.writeBLECharacteristicValue({
  509. deviceId: that.deviceId,
  510. serviceId: that.service_uuid,
  511. characteristicId: that.characteristics_uuid,
  512. value: that.byteStringValue,
  513. success: function (res) {
  514. console.log('writeBLECharacteristicValue success', res)
  515. that.writecharacteristicsvalue = 'success'
  516. },
  517. fail: function (erromsg, errocode) {
  518. console.log('writeBLECharacteristicValue fail ', erromsg)
  519. that.writecharacteristicsvalue = 'code ' + errocode + ' errormsg ' + erromsg
  520. },
  521. complete: function () {
  522. console.log('writeBLECharacteristicValue complete')
  523. }
  524. })
  525. },
  526. notifyBLECharacteristicValueChange() {
  527. var that = this
  528. console.log('notifyBLECharacteristicValueChange begin deviceId ' + that.deviceId)
  529. console.log('notifyBLECharacteristicValueChange begin serviceId ' + that.service_uuid)
  530. console.log('notifyBLECharacteristicValueChange begin characteristicId ' + that.characteristics_uuid)
  531. bluetooth.notifyBLECharacteristicValueChange({
  532. state: that.notifystate,
  533. deviceId: that.deviceId,
  534. serviceId: that.service_uuid,
  535. characteristicId: that.characteristics_uuid,
  536. success: function (res) {
  537. console.log('notifyBLECharacteristicValueChange success', res)
  538. that.notifyBLECharacteristicValue = 'success'
  539. },
  540. fail: function (erromsg, errocode) {
  541. console.log('notifyBLECharacteristicValueChange fail ', erromsg)
  542. that.notifyBLECharacteristicValue = 'code ' + errocode + ' errormsg ' + erromsg
  543. },
  544. complete: function () {
  545. console.log('notifyBLECharacteristicValueChange complete')
  546. }
  547. })
  548. },
  549. onblecharacteristicvaluechange: function () {
  550. var that = this
  551. console.log('onblecharacteristicvaluechange begin')
  552. bluetooth.onblecharacteristicvaluechange = function (res) {
  553. console.log(that.componentData.monitorCharacteristicChange, res)
  554. that.characteristicsvalue = JSON.stringify(res)
  555. }
  556. },
  557. onbleconnectionstatechange: function () {
  558. var that = this
  559. console.log('onbleconnectionstatechange begin')
  560. bluetooth.onbleconnectionstatechange = function (res) {
  561. console.log(that.componentData.monitorConnectChange, res)
  562. that.bleconnectionstate = JSON.stringify(res)
  563. }
  564. },
  565. stringToByte(str) {
  566. var bytes = []
  567. var len, c
  568. len = str.length
  569. for (var i = 0; i < len; i++) {
  570. c = str.charCodeAt(i)
  571. if (c >= 0x010000 && c <= 0x10FFFF) {
  572. bytes.push(((c >> 18) & 0x07) | 0xF0)
  573. bytes.push(((c >> 12) & 0x3F) | 0x80)
  574. bytes.push(((c >> 6) & 0x3F) | 0x80)
  575. bytes.push((c & 0x3F) | 0x80)
  576. } else if (c >= 0x000800 && c <= 0x00FFFF) {
  577. bytes.push(((c >> 12) & 0x0F) | 0xE0)
  578. bytes.push(((c >> 6) & 0x3F) | 0x80)
  579. bytes.push((c & 0x3F) | 0x80)
  580. } else if (c >= 0x000080 && c <= 0x0007FF) {
  581. bytes.push(((c >> 6) & 0x1F) | 0xC0)
  582. bytes.push((c & 0x3F) | 0x80)
  583. } else {
  584. bytes.push(c & 0xFF)
  585. }
  586. }
  587. return bytes
  588. },
  589. oninput: function (event) {
  590. var self = this
  591. var arra = []
  592. arra.push(event.value)
  593. self.service_uuidarray = arra
  594. },
  595. oninputdeviceId: function (event) {
  596. var self = this
  597. self.deviceId = event.value
  598. },
  599. oninputmac: function (event) {
  600. var self = this
  601. self.mac = event.value
  602. },
  603. oninputserviceId: function (event) {
  604. var self = this
  605. self.service_uuid = event.value
  606. },
  607. oninputcharacteristicId: function (event) {
  608. var self = this
  609. self.characteristics_uuid = event.value
  610. },
  611. oninputbyteStringValue: function (event) {
  612. var self = this
  613. self.byteStringValue = event.value
  614. },
  615. oninputnotifystate: function (event) {
  616. var self = this
  617. self.notifystate = event.checked
  618. console.log('notifystate ' + self.notifystate)
  619. },
  620. }
  621. </script>

效果图如下:

版本更新说明

展开

版本

发布日期

描述

1040

2019-06-24

第一次正式发布。

相关链接