如何在Linux中使用Bluez实现蓝牙LE

lin*_*sek 13 bluetooth bluetooth-lowenergy bluez gatt

我正在为BLE演示设置两个Linux系统.显然,一个系统将是外围设备,一个系统将是中央设备.围绕这两种配置我有几个问题.

环境

外围设备设置

第一项业务是通过配置的GATT服务器获得外围系统设置和广告.此时,似乎无法从命令行配置GATT服务器.因此,虽然将USB加密狗带入并通告它是一项简单的任务,但这不允许创建自定义服务和特性.我能找到的GATT服务器的唯一例子是Bluez包中的gatt-example.c文件.所以我下载并构建了最新的bluez-5.23源代码.(http://www.linuxfromscratch.org/blfs/view/svn/general/bluez.html).另外使用--enable-maintainer-mode标志配置强制将gatt-example.c插件构建到bluetoothd中.我从~/bluez-5.23/plugins目录中验证了有bluetoothd-gat-example.o文件的后期构建.这告诉我gatt-example至少是成功构建的.

然后我修改了配置文件以启用LE和属性服务器.

$ sudo vi /etc/bluetooth/main.conf
EnableLE = true           // Enable Low Energy support. Default is false.
AttributeServer = true    // Enable the GATT attribute server. Default is false.
Run Code Online (Sandbox Code Playgroud)

然后只需重启或重启蓝牙守护进程......

中央设备设置

由于中央设备不需要像外围设备那样构建任何特殊插件,我只使用了bluez apt-get.这似乎已根据安装v4.101 bluetoothd -v.

会话设置

然后连接过程应该相当简单.我设置外围设备进行广告宣传,然后与中央设备连接:

外围:

$ sudo hciconfig hci0 up        // Make sure the interface is up
$ sudo hciconfig hci0 leadv     // Set the interface to advertise
Run Code Online (Sandbox Code Playgroud)

中央:

$ sudo hcitool -i hci0 lescan   // Scan for nearby devices advertising
LE Scan ...
00:02:72:C9:5E:0F (unknown)     // Not sure why two of the same MAC are found?
00:02:72:C9:5E:0F (unknown)     // but I know this is my device...

$ sudo gatttool -i hci0 -b 00:02:72:C9:5E:0F -m 48 --interactive     // Connect interactively
[   ][00:02:72:C9:5E:0F][LE]> connect
[CON][00:02:72:C9:5E:0F][LE]> primary
attr handle: 0x0001, end grp handle: 0x0008 uuid: 00001800-0000-1000-8000-00805f9b34fb
attr handle: 0x0010, end grp handle: 0x0010 uuid: 00001801-0000-1000-8000-00805f9b34fb
[CON][00:02:72:C9:5E:0F][LE]> characteristics 
handle: 0x0004, char properties: 0x02, char value handle: 0x0006, uuid: 00002a00-0000-1000-8000-00805f9b34fb
handle: 0x0007, char properties: 0x02, char value handle: 0x0008, uuid: 00002a01-0000-1000-8000-00805f9b34fb
Run Code Online (Sandbox Code Playgroud)

我们看不到gatt-example的服务或特性之一可用.

问题

- 外围设备

  1. 我如何创建自己的自定义GATT服务器?它可以是一个独立的C应用程序,还是需要像gatt一样的插件内置到bluetoothd?这个问题的答案(创建一个Gatt服务器?)意味着你要做到以下几点:"从初始化GATT库和其他模块开始",然后"注册你的GATT数据库".但是没有一个如何实现这些通用语句的例子,所提供的链接只是蓝牙网站的URL.
  2. GATT规范(https://developer.bluetooth.org/gatt/Pages/default.aspx)提供了许多可采用XML格式下载的"采用"服务和特性.但是没有关于如何使用它们的说明?!
  3. 如何验证我的GATT服务器是否正在运行?

- 中央设备

  1. 为什么我的中央设备没有看到外围设备上运行的GATT服务器的服务和特性?

我可以提供任何必要的额外信息.谢谢.

Oli*_*erM 3

要将 GATT 服务器创建到单独的进程中,您(至少)有两种情况:

  • Bluez v4.x:您的 GATT 服务必须是 Bluez 插件
  • Bluez v5.x:您的 GATT 服务应使用新的 GATT DBus API(但建议至少使用 Bluez v5.39(从 2016 年 4 月起)。否则,使用 Bluez GATT Server API 更安全) Bluez v4.x 插件方法。

如果您的中央设备看不到新导出的 GATT 服务,则可能是外设上的问题,而不是中央设备上的问题。当您需要在中央设备上实施 GATT 客户端时,您仍然有两种情况:

  • Bluez v4.x:Bluez 不公开 GATT API。您可以使用 shell 脚本启动命令,也可以使用gattlibgatttool等 GATT 库与 BLE 设备交互
  • Bluez v5.x:同样的事情,如果您无法迁移到 Bluez v5.39,那么最好使用 Bluez v4.x 方法。