跟着小白一起学鸿蒙[– 蓝牙应用(八)

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

​想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com​

蓝牙简介

蓝牙(Bluetooth)是一个短距离无线通信标准,用于在手机、计算机和其他电子设备之间通信。在 Linux 中权威的蓝牙协议栈实现是 BlueZ。其本身自带了很多有用的工具,如bluetoothctl,hcidump和monitor。本章我们主要介绍开源鸿蒙中的蓝牙应用和接口以及和Linux上工具软件bluetoothctl的对比。

经典蓝牙: 在2010年以前,我们谈论的蓝牙就是经典蓝牙(传统蓝牙)。蓝牙1.0/2.0/2.1/3.0都是经典蓝牙,经典蓝牙包括BR,EDR和HS (AMP) 三种模式。蓝牙数据是通过分组形势在空中传输的。

**低功耗蓝牙:**2010年,SIG联盟合并了Wibree联盟(注:Wibree联盟由 Nokia 和 Nordic 等创立,旨在为手机周边设备寻找一种更低功耗的无线通信技术,并把Wibree联盟提出的低功耗无线技术重新命名为低功耗蓝牙技术(BLE),从此 BLE 也成了一种蓝牙技术。其实经典蓝牙称谓不准确,在蓝牙4.0规格中,SIG定义了四种蓝牙controller技术:BR,EDR,AMP和LE。由于 LE 是 2010年才提出的,比较新,因此为了说起来方便,人们把之前的 BR/EDR/AMP 技术称为经典蓝牙技术。

**蓝牙5.0:**蓝牙5.0是继蓝牙4.2后最新的蓝牙技术标准,蓝牙5.0针对低功耗设备,有着更大的覆盖范围和更快的速度速率,有效距离最远可达300米,是上一代蓝牙4.2的四倍;最大传输速度为24Mbps,且新增了导航功能,对于低功耗的蓝牙设备间的配对优化明显。

开源鸿蒙的蓝牙介绍

在开源鸿蒙里开源鸿蒙有两个部分的相关实现:

**蓝牙仓库:**https://gitee.com/openharmony/communication_bluetooth。

目录结构:

.
├── frameworks //框架层
├── inner //native功能实现
└── js //js适配,NAPI实现
├── interfaces //接口层
├── inner_api //native api实现
└── kits //d.ts接口定义
├── services //蓝牙服务
├── bluetooth //标准系统蓝牙服务
└── bluetooth_lite //小型系统蓝牙服务
└── test
├── example //蓝牙测试应用
├── fuzztest
├── moduletest
└── unittest

功能介绍:

提供蓝牙BR、EDR和LE的主要功能支持。如: enableBluetooth,disableBluetooth, pairDevice, getLocalName, getPairedDevices, startBluetoothDiscovery, stopBluetoothDiscovery以及蓝牙事件监听,比如:bluetoothDeviceFind, boneStateChange, pinRequired, stateChange。

**设置仓库:**https://gitee.com/openharmony/applications_settings。

目录结构:

.
├── product
├── phone
└── src
└── main
├── ets
├── Application
├── controller
├── MainAbility
├── model
├── pages
├── res
└── resources
├── module.json5
└── resources
├── base
├── en_US
├── phone
├── rawfile
└── zh_CN
├── README.md
├── README_zh.md
└── signature
└── settings.p7b

功能介绍:

application_settings是一个hap应用,其中有一部分是蓝牙对应的配置,提供基本的功能如:蓝牙开关,蓝牙搜索,蓝牙配对(取消配对)等功能。

开源鸿蒙的蓝牙实验

**蓝牙测试应用地址:**https://gitee.com/openharmony/communication_bluetooth/tree/master/test/example/BluetoothTest。

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

蓝牙简单的验证流程:扫描。

graph LR
on[开启蓝牙] --> setBluetoothScanMode[设置蓝牙模式] --> onBluetoothDeviceFind[注册蓝牙发现回调] --> startBluetoothDiscovery[蓝牙发现]
//引入d.ts声明,同时在napi层调起bluetooth模块实例
import bluetooth from '@ohos.bluetooth';
……
//蓝牙使能
bluetooth.enableBluetooth();
//设置蓝牙模式:SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE,可连接,可被发现;0,一直,注意这个时间的单位是毫秒,如果需要设置一个功能启用时间务必注意,否则很短时间后设置的模式就会失效;
bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0);
//监听状态变化,如果状态变化则进行回调通知
bluetooth.on('stateChange', (data) => {
this.btStateMessage = 'STATE: ';
switch (data) {
case 0:
this.btStateMessage += 'STATE_OFF';
break;
case 1:
this.btStateMessage += 'STATE_TURNING_ON';
break;
case 2:
this.btStateMessage += 'STATE_ON';
break;
case 3:
this.btStateMessage += 'STATE_TURNING_OFF';
break;
case 4:
this.btStateMessage += 'STATE_BLE_TURNING_ON';
break;
case 5:
this.btStateMessage += 'STATE_BLE_ON';
break;
case 6:
this.btStateMessage += 'STATE_BLE_TURNING_OFF';
break;
default:
this.btStateMessage += '未知状态';
break;
}
})
//接收bluetooth发现设备的返回
bluetooth.on('bluetoothDeviceFind', (data: Array<string>) => {
LogUtil.info(`${this.TAG} subscribeBluetoothDeviceFind->deviceFind return:${JSON.stringify(data)}`);
})
//开始bluetooth发现
bluetooth.startBluetoothDiscovery();

蓝牙简单的验证流程:配对。

graph LR
on[开启蓝牙] --> setBluetoothScanMode[设置蓝牙模式] --> onPairedRequest[注册蓝牙配对回调] --> startBluetoothDiscovery[蓝牙配对]
import bluetooth from '@ohos.bluetooth';
……
//蓝牙使能
bluetooth.enableBluetooth();
//设置蓝牙模式:SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE,可连接,可被发现;0,一直;
bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0);
//接收bluetooth配对的返回
bluetooth.on('pinRequired', (data: {
deviceId: string;
pinCode: string;
}) => {
LogUtil.info(`${this.TAG} subscribePinRequired->pinRequired return:${JSON.stringify(data)}`);
//确认配对
bluetooth.setDevicePairingConfirmation(deviceId, pindCode)
})
//开始bluetooth配对
bluetooth.pairDevice(deviceMacAddress);
//获取bluetooth配对设备
let pairedDeviceList = bluetooth.getPairedDevices

Linux上的蓝牙对比实验

蓝牙的测试是需要有对应的测试对象的,简单的配对等功能我们可以用现在的智能手机进行,但是如果稍微复杂的功能我们可能就需要一种特殊的方法,后面我们就简单谈谈利用ubuntu上安装bluez工具进行测试的方法。

环境配置与安装

修改镜像资源配置为阿里源

sudo gedit /etc/apt/sources.list
//默认的链接为:https://developer.aliyun.com/mirror/ubuntu
//修改 etc/apt/sources.list 为
deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
# deb http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse

APT安装bluez

sudo apt install bluez

Linux终端安装和使用BlueZ(提供bluetoothctl实用程序),它为核心的蓝牙层和协议提供支持,它灵活、高效并且使用模块化实现。BlueZ具有的主要功能:完整的模块化实施、对称多处理安全、多线程数据处理、支持多个蓝牙设备、真正的硬件抽象、所有层的标准插座接口、设备和服务级别的安全支持。

了解bluez命令

控制台

检查蓝牙状态:

在添加蓝牙设备之前,计算机上的蓝牙服务必须已启动并正在运行。可以在systemctl命令的帮助下进行检查。

sudo systemctl status bluetooth

如果蓝牙服务状态未激活,则必须先启用它。然后启动服务,以便在启动计算机时自动启动。

sudo systemctl enable bluetooth
sudo systemctl start bluetooth

使用蓝牙设备之前先检查有没有被rfkill 禁用。

rfkill命令的功能是管理系统中的蓝牙和WIFI设备。rfkill命令是一个内核级别的管理工具,可以打开或关闭系统中的蓝牙和WIFI功能。

语法格式: rfkill [参数] 设备名

常用参数:

list

列出可用设备

block

关闭设备

unblock

打开设备

使用bluetoothctl连接到蓝牙设备。

bluetooth。

bluetoothctl — 在 shell 中配对设备是最简单可靠的方法之一。

Bluetoothctl是用于控制蓝牙设备的交互式且易于使用的工具。它是在基于Linux的操作系统上管理蓝牙的主要实用程序。实质上是由bluez源码下的client目录的相关文件编译生成的可执行程序(命令)。bluetoothctl 主要是bluez官方提供的一个命令行交互的一个客户端,用于和bluetoothd的通信进行BLE广播包的设置、BLE相关配置、创建服务、特征等. 具体的功能请打开终端,运行bluetoothctl 进行查看。

启动bluetoothctl交互式命令:

bluetoothctl是一个交互式实用程序。通常应该使用交互式模式,操作起来更快,更容易。要进入交互方式,只需运行不带参数的bluetoothctl命令,要退出蓝牙交互模式,只需在提示中键入exit 。

$ bluetoothctl

查看controller。

$ [bluetoothctl]#  list

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

查看controller的属性。

$ [bluetoothctl]# show

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

打开蓝牙:

适配器:[bluetooth]# default-agent //设置默认代理Default agent request successful[bluetooth]# power on //打开Changing power on succeeded。

help:

输入help命令以获取可用命令的列表。

[bluetooth]# help
Menu main:
Available commands:
//命令 //命令功能的解释
-------------------
advertise Advertise Options Submenu
scan Scan Options Submenu
gatt Generic Attribute Submenu
list List available controllers
show [ctrl] Controller information
select <ctrl> Select default controller
devices List available devices
paired-devices List paired devices
system-alias <name> Set controller alias
reset-alias Reset controller alias
power <on/off> Set controller power
pairable <on/off> Set controller pairable mode
discoverable <on/off> Set controller discoverable mode
discoverable-timeout [value] Set discoverable timeout
agent <on/off/capability> Enable/disable agent with given capability
default-agent Set agent as the default one
advertise <on/off/type> Enable/disable advertising with given type
set-alias <alias> Set device alias
scan <on/off> Scan for devices
info [dev] Device information
pair [dev] Pair with device
trust [dev] Trust device
untrust [dev] Untrust device
block [dev] Block device
unblock [dev] Unblock device
remove <dev> Remove device
connect <dev> Connect device
disconnect [dev] Disconnect device
menu <name> Select submenu
version Display version
quit Quit program
exit Quit program
help Display help about this program
export Print environment variables

主菜单下的功能

子菜单:

menu + “子菜单名”:进入子菜单,目前有advertise、scan、gatt三个子菜单,分别用于设置BLE广播信息、扫描过滤、GATT设置。如 menu advertise/scan/gatt,功能在下面的子菜单功能测试中。

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

进入每个子菜单后,使用back返回主菜单,才可以重新进入新的子菜单。

进行扫描以检测你的蓝牙设备:要主动搜索可以连接的蓝牙设备。

# scan on

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

当运行上面的命令时,PC将查找并列出系统可以访问的所有蓝牙设备。

所有蓝牙设备都标记为设备,后跟它们各自的媒体访问控制(MAC)地址,这是网络上设备的唯一标识符。 MAC地址的格式为XX:XX:XX:XX:XX:XX 。 Bluetoothctl还在上面的输出中显示设备的名称。

要使蓝牙适配器可被其他设备发现,请使用以下命令:

[bluetoothctl]# discoverable on

4、与发现的蓝牙设备配对:

[bluetoothctl]# pair DC:A6:32:74:A5:AF

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

除了与蓝牙设备配对外,还可以选择信任设备,以便之后的配对可以自动完成无需验证。

[bluetoothctl]# trust DC:A6:32:74:A5:AF

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

可以通过发出以下命令来取消对设备的信任:

[bluetoothctl]# untrust DC:A6:32:74:A5:AF

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

可以使用以下命令列出计算机蓝牙范围内的设备:

[bluetoothctl]# devices

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

可以通过运行以下命令查看当前与系统配对的设备:

[bluetoothctl]# paired-devices

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

可以通过运行以下命令查看当前版本:

[bluetooth]# version
Version 5.53

可以通过运行以下命令更改别名:

[bluetooth]# system-alias 别名

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

可以通过运行以下命令重置别名。

[bluetooth]# reset-alias

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

查看环境变量。

[bluetooth]# export

跟着小白一起学鸿蒙[-- 蓝牙应用(八)跟着小白一起学鸿蒙[-- 蓝牙应用(八)

交互实例:

实际的步骤取决于设备和它的输入功能。以下是使用 配对设备的一般步骤。bluetoothctl。

运行 交互命令。输入 来获取帮助。bluetoothctl“help。

  1. (可选操作)使用选择一个默认的蓝牙接收器。select *MAC_address*。
  2. 使用命令打开蓝牙。蓝牙默认是关闭的,并且重启之后默认也会关闭,参照[#开机后自动启动#]power on。
  3. 使用命令获得要配对的设备的MAC地址。devices。
  4. 如果设备没有出现在上一步的列表中,使用命令去搜索发现所有可配对的设备。scan on。
  5. 使用命令去结束搜索。scan off。
  6. 使用命令 打开代理或者选择一个特定的代理:如果在 命令后按下两次 tab 键,应该就能看到可用代理的列表。蓝牙代理用于管理蓝牙”配对码”。它可以回复外部发来的”配对码”,也可以主动发送。。agent onagentdefault-agent`。
  7. 使用命令配对设备(可用 tab 键补全 MAC 地址)。pair *MAC_address*。
  8. 手动将设备添加到信任列表,如果配对设备不需要 PIN。使用命令 。trust *MAC_address*。
  9. 使用命令建立连接。connect *MAC_address*。
$ bluetoothctl
[NEW] Controller AC:1E:9E:0B:2E:63 hostname [default]
[bluetooth]# agent KeyboardOnly
Agent registered
[bluetooth]# default-agent
Default agent request successful
[bluetooth]# power on
Changing power on succeeded
[CHG] Controller AC:1E:9E:0B:2E:63 Powered: yes
[bluetooth]# scan on
Discovery started
[CHG] Controller AC:1E:9E:0B:2E:63 Discovering: yes
[NEW] Device AC:1E:9E:0B:2E:63 device name
[CHG] Device AC:1E:9E:0B:2E:63 LegacyPairing: yes
[bluetooth]# pair AC:1E:9E:0B:2E:63
Attempting to pair with AC:1E:9E:0B:2E:63
[CHG] Device AC:1E:9E:0B:2E:63 Connected: yes
[CHG] Device AC:1E:9E:0B:2E:63 Connected: no
[CHG] Device AC:1E:9E:0B:2E:63 Connected: yes
Request PIN code
[agent] Enter PIN code: 1234
[CHG] Device AC:1E:9E:0B:2E:63 Paired: yes
Pairing successful
[CHG] Device AC:1E:9E:0B:2E:63 Connected: no
[bluetooth]# connect AC:1E:9E:0B:2E:63
Attempting to connect to AC:1E:9E:0B:2E:63
[CHG] Device AC:1E:9E:0B:2E:63 Connected: yes
Connection successful

advertise菜单下的功能

[bluetooth]# menu advertise
Menu advertise:
Available commands:
//命令 //命令功能的解释
-------------------
uuids [uuid1 uuid2 ...] Set/Get advertise uuids
service [uuid] [data=xx xx ...] Set/Get advertise service data
manufacturer [id] [data=xx xx ...] Set/Get advertise manufacturer data
data [type] [data=xx xx ...] Set/Get advertise data
discoverable [on/off] Set/Get advertise discoverable
discoverable-timeout [seconds] Set/Get advertise discoverable timeout
tx-power [on/off] Show/Enable/Disable TX power to be advertised
name [on/off/name] Configure local name to be advertised
appearance [on/off/value] Configure custom appearance to be advertised
duration [seconds] Set/Get advertise duration
timeout [seconds] Set/Get advertise timeout
secondary [1M/2M/Coded] Set/Get advertise secondary channel
clear [uuids/service/manufacturer/config-name...] Clear advertise config
back Return to main menu
version Display version
quit Quit program
exit Quit program
help Display help about this program
export Print environment variables

scan菜单下的功能

[bluetooth]# menu scan
Menu scan:
Available commands:
//命令 //命令功能的解释
-------------------
uuids [all/uuid1 uuid2 ...] Set/Get UUIDs filter
rssi [rssi] Set/Get RSSI filter, and clears pathloss
pathloss [pathloss] Set/Get Pathloss filter, and clears RSSI
transport [transport] Set/Get transport filter
duplicate-data [on/off] Set/Get duplicate data filter
discoverable [on/off] Set/Get discoverable filter
clear [uuids/rssi/pathloss/transport/duplicate-data/discoverable] Clears discovery filter.
back Return to main menu
version Display version
quit Quit program
exit Quit program
help Display help about this program
export Print environment variables

gatt菜单下的功能

[bluetooth]# menu gatt
Menu gatt:
Available commands:
//命令 //命令功能的解释
-------------------
list-attributes [dev/local] List attributes
select-attribute <attribute/UUID> Select attribute
attribute-info [attribute/UUID] Select attribute
read [offset] Read attribute value
write <data=xx xx ...> [offset] [type] Write attribute value
acquire-write Acquire Write file descriptor
release-write Release Write file descriptor
acquire-notify Acquire Notify file descriptor
release-notify Release Notify file descriptor
notify <on/off> Notify attribute value
clone [dev/attribute/UUID] Clone a device or attribute
register-application [UUID ...] Register profile to connect
unregister-application Unregister profile
register-service <UUID> [handle] Register application service.
unregister-service <UUID/object> Unregister application service
register-includes <UUID> [handle] Register as Included service in.
unregister-includes <Service-UUID><Inc-UUID> Unregister Included service.
register-characteristic <UUID> <Flags=read,write,notify...> [handle] Register application characteristic
unregister-characteristic <UUID/object> Unregister application characteristic
register-descriptor <UUID> <Flags=read,write...> [handle] Register application descriptor
unregister-descriptor <UUID/object> Unregister application descriptor
back Return to main menu
version Display version
quit Quit program
exit Quit program
help Display help about this program
export Print environment variables

要取消蓝牙设备的配对,使用remove命令,如下所示:

bluetoothctl remove FC:69:47:7C:9D:A3

可以使用bluetoothctl将设备与系统断开连接:

bluetoothctl disconnect FC:69:47:7C:9D:A3

如果希望阻止特定设备连接到系统,则可以使用block命令,后跟该设备的MAC地址。

bluetoothctl block FC:69:47:7C:9D:A3

要取消阻止设备,只需将上述命令中的单词block替换为unblock即可。

bluez功能对应着鸿蒙程序中的功能

功能说明

bluez功能

开源鸿蒙接口

蓝牙开关

power on/off

enableBluetooth/disableBluetooth

配对

pair [dev]

pairDevice

设置可被发现的

pairable/discoverable <on/off>

setBluetoothScanMode

设置蓝牙名称

system-alias <name>

setLocalName

注意:bluez开机后自动启动

将如下代码添加至main.conf,蓝牙可以自动启动:

/etc/bluetooth/main.conf
[Policy]
AutoEnable=true
注意:bluez启动后自动可被发现

如果设备总是可见或者可以直接连接:

/etc/bluetooth/main.conf
[General]
DiscoverableTimeout = 0

跟着小白一起学鸿蒙[-- 蓝牙应用(八)

总结

  1. HAP应用调用系统模块就是import bluetooth from ‘@ohos.bluetooth’,其他内容可以从interface/sdk-js/api/@ohos.xxx.d.ts里查找;在DevEco工具里openharmony的sdk默认路径AppDataLocalOpenHarmonySdkets3.1.7.7api文件夹下也可以找.d.ts。
  2. 开源鸿蒙的蓝牙功能和linux上的bluez大多数功能相同,可以进行对比验证比较两边的差距。

​想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com​​。

文章版权声明

 1 原创文章作者:路人甲,如若转载,请注明出处: https://www.52hwl.com/108142.html

 2 温馨提示:软件侵权请联系469472785#qq.com(三天内删除相关链接)资源失效请留言反馈

 3 下载提示:如遇蓝奏云无法访问,请修改lanzous(把s修改成x)

 免责声明:本站为个人博客,所有软件信息均来自网络 修改版软件,加群广告提示为修改者自留,非本站信息,注意鉴别

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2024年1月17日 下午9:45
下一篇 2024年1月17日 下午9:45