gpt4 book ai didi

c - Linux 上 C blueZ 中的蓝牙配对

转载 作者:IT王子 更新时间:2023-10-29 00:07:10 25 4
gpt4 key购买 nike

我找不到任何关于如何在使用 BlueZ 蓝牙库的 C 语言编写的程序中在 Linux 上配对蓝牙设备的引用资料。我已经设法进行 HCI 级别查询以获取设备及其 RSSI 级别(在设备发现期间),但目前我坚持这样做。我看到了将 DBUS api 用于 blueZ-simple-agent 的建议 - 但有什么方法可以避免这种情况,而只使用 BlueZ 的一些 C 级方法?

最佳答案

验证码来自hcitool(原始源码可见http://git.kernel.org/cgit/bluetooth/bluez.git/tree/tools/hcitool.c)

/* Request authentication */

static void cmd_auth(int dev_id, int argc, char **argv)
{
struct hci_conn_info_req *cr;
bdaddr_t bdaddr;
int opt, dd;

for_each_opt(opt, auth_options, NULL) {
switch (opt) {
default:
printf("%s", auth_help);
return;
}
}
helper_arg(1, 1, &argc, &argv, auth_help);

str2ba(argv[0], &bdaddr);

if (dev_id < 0) {
dev_id = hci_for_each_dev(HCI_UP, find_conn, (long) &bdaddr);
if (dev_id < 0) {
fprintf(stderr, "Not connected.\n");
exit(1);
}
}

dd = hci_open_dev(dev_id);
if (dd < 0) {
perror("HCI device open failed");
exit(1);
}

cr = malloc(sizeof(*cr) + sizeof(struct hci_conn_info));
if (!cr) {
perror("Can't allocate memory");
exit(1);
}

bacpy(&cr->bdaddr, &bdaddr);
cr->type = ACL_LINK;
if (ioctl(dd, HCIGETCONNINFO, (unsigned long) cr) < 0) {
perror("Get connection info failed");
exit(1);
}

if (hci_authenticate_link(dd, htobs(cr->conn_info->handle), 25000) < 0) {
perror("HCI authentication request failed");
exit(1);
}

free(cr);

hci_close_dev(dd);
}

并设置密码

/* Activate encryption */

static void cmd_enc(int dev_id, int argc, char **argv)
{
struct hci_conn_info_req *cr;
bdaddr_t bdaddr;
uint8_t encrypt;
int opt, dd;

for_each_opt(opt, enc_options, NULL) {
switch (opt) {
default:
printf("%s", enc_help);
return;
}
}
helper_arg(1, 2, &argc, &argv, enc_help);

str2ba(argv[0], &bdaddr);

if (dev_id < 0) {
dev_id = hci_for_each_dev(HCI_UP, find_conn, (long) &bdaddr);
if (dev_id < 0) {
fprintf(stderr, "Not connected.\n");
exit(1);
}
}

dd = hci_open_dev(dev_id);
if (dd < 0) {
perror("HCI device open failed");
exit(1);
}

cr = malloc(sizeof(*cr) + sizeof(struct hci_conn_info));
if (!cr) {
perror("Can't allocate memory");
exit(1);
}

bacpy(&cr->bdaddr, &bdaddr);
cr->type = ACL_LINK;
if (ioctl(dd, HCIGETCONNINFO, (unsigned long) cr) < 0) {
perror("Get connection info failed");
exit(1);
}

encrypt = (argc > 1) ? atoi(argv[1]) : 1;

if (hci_encrypt_link(dd, htobs(cr->conn_info->handle), encrypt, 25000) < 0) {
perror("HCI set encryption request failed");
exit(1);
}

free(cr);

hci_close_dev(dd);
}

关于c - Linux 上 C blueZ 中的蓝牙配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com