在 Linux 下使用 BlueZ(官方蓝牙协议栈)进行蓝牙广播并等待连接传输数据,通常涉及以下步骤:
- 打开 HCI 设备(
hci_open_dev
)
- 设置蓝牙适配器为可被发现和可连接模式
- 开启 LE 广播(Advertising)
- 等待连接请求并处理数据传输
完整示例代码
1. 依赖安装
确保系统已安装 bluez
开发库:
sudo apt-get install libbluetooth-dev
2. C 语言实现
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
int main(int argc, char **argv) {
// (1) 获取本地蓝牙适配器ID(默认0)
int dev_id = hci_get_route(NULL);
if (dev_id < 0) {
perror("No Bluetooth adapter found");
exit(1);
}
// (2) 打开HCI设备
int sock = hci_open_dev(dev_id);
if (sock < 0) {
perror("Failed to open HCI device");
exit(1);
}
printf("Bluetooth device opened, sock=%d\n", sock);
// (3) 设置蓝牙为可发现、可连接模式
if (hci_write_scan_enable(sock, SCAN_INQUIRY | SCAN_PAGE, 10000) < 0) {
perror("Failed to set scan mode");
close(sock);
exit(1);
}
printf("Bluetooth is discoverable and connectable\n");
// (4) LE Advertising Parameters
le_set_advertising_parameters_cp adv_params;
memset(&adv_params, 0, sizeof(adv_params));
adv_params.min_interval = htobs(0x080); // Minimum advertising interval
adv_params.max_interval = htobs(0x080); // Maximum advertising interval
adv_params.type = LE_ADV_IND; // Connectable undirected advertising
adv_params.filter_policy = LE_FILTER_ALLOW_ALL;
// (5) Enable Advertising
if (hci_le_set_advertise_enable(sock, true, NULL)) {
perror("Failed to enable advertising");
close(sock);
return -1;
}
printf("Advertising started... Waiting for connections.\n");
while (1) {
sleep(1); // Keep running until Ctrl+C or connection established.
}
hci_close_dev(sock);
return 0;
}
关键函数说明
API | Description |
---|---|
hci_get_route() |
获取默认蓝牙适配器 ID |
hci_open_dev() |
打开 HCI Socket |
hci_write_scan_enable() |
使设备可被发现和连接 |
le_set_advertising_parameters_cp |
LE广播参数配置 |
hci_le_set_advertise_enable() |
启动/停止LE广播 |
运行方式
编译并运行:
gcc -o bt_advertise bt_advertise.c -lbluetooth && sudo ./bt_advertise
- ⚠️需要 root/sudo权限(因涉及底层HCI操作)。
- 📌可用手机或其他设备扫描并尝试连接。
进阶改进
✅ 增加 GATT Server:使用 gattlib
/ D-Bus API,让设备支持数据传输。
✅ BLE Beacon模式:修改广告类型为不可连接的广播(如 iBeacon)。
✅ 多线程处理:单独线程监听 ACL/UART/L2CAP socket接收数据。
如需更完整的 BLE GATT Server + Data Transfer Demo,请告知!
内容由零声教学AI助手提供,问题来源于学员提问