树莓派3 BLE扫描

3

我正在尝试在树莓派3上实现以下代码以扫描BLE设备:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

int main(int argc, char **argv)
{
    inquiry_info *ii = NULL;
    int max_rsp, num_rsp;
    int dev_id, sock, len, flags;
    int i;
    char addr[19] = { 0 };
    char name[248] = { 0 };

    dev_id = hci_get_route(NULL);
    sock = hci_open_dev( dev_id );
    if (dev_id < 0 || sock < 0) {
        perror("opening socket");
        exit(1);
    }

    len  = 8;
    max_rsp = 255;
    flags = IREQ_CACHE_FLUSH;
    ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));

    num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
    if( num_rsp < 0 ) perror("hci_inquiry");

    for (i = 0; i < num_rsp; i++) {
        ba2str(&(ii+i)->bdaddr, addr);
        memset(name, 0, sizeof(name));
        if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name), 
            name, 0) < 0)
        strcpy(name, "[unknown]");
        printf("%s  %s\n", addr, name);
    }

    free( ii );
    close( sock );
    return 0;
}

问题在于num_rsp等于零,也就是说,它没有找到任何设备。
然而,如果我在终端中使用命令$ sudo hcitool lescan,它会找到所有可用的设备。
有人能指点我排除故障的正确方向吗?还有其他实现hcitool lescan的C++代码的方法吗?
提前感谢。

请查看此答案 - bluepinto
2个回答

3
使用BlueZ,您可以使用hci_le_set_scan_parametershci_le_set_scan_enable触发BLE扫描。
这里有一个用C语言编写的实验:链接
if (hci_le_set_scan_parameters(current_hci_state.device_handle, 0x01, htobs(0x0010), htobs(0x0010), 0x00, 0x00, 1000) < 0)
{
    current_hci_state.has_error = 1;
    snprintf(current_hci_state.error_message, sizeof(current_hci_state.error_message), "Failed to set scan parameters: %s", strerror(errno));
    return;
}

if (hci_le_set_scan_enable(current_hci_state.device_handle, 0x01, 1, 1000) < 0)
{
    current_hci_state.has_error = 1;
    snprintf(current_hci_state.error_message, sizeof(current_hci_state.error_message), "Failed to enable scan: %s", strerror(errno));
    return;
}

我已经将这个示例移植到了C++,在这里可以找到。


示例源代码链接已失效! - peterk
好的,已经下载了,但我的编译器找不到头文件。 最近有关于必要先决条件的信息吗?如果安装不在系统库和包含路径中,它会把东西放在哪里?我已经安装了bluez,Python工具可以使用。 - peterk
1
好的 - 看来我需要安装libbluetooth-dev以获取头文件 "sudo apt-get install libbluetooth-dev" - peterk
我编译并链接了C++示例,蓝牙服务正在运行。hcitools扫描器显示了多个LE设备。运行示例程序会显示“扫描中...”,然后静止等待。 - peterk
2
看起来LE扫描需要root权限,当我以root身份运行程序时,它可以正常工作。但请注意,当以非root身份运行时,没有任何调用返回值被检查的调用会返回错误。 - peterk

0
NewAer SDK支持在Pi 3和iOS设备之间进行BLE扫描和P2P通信。该SDK也支持Android,但由于操作系统处理BLE模式的方式不同,因此其支持有限。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接