【问题标题】:Raspberry Pi 3 BLE scanning树莓派 3 BLE 扫描
【发布时间】:2016-11-11 01:07:55
【问题描述】:

我正在尝试在 Raspberry Pi 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等于0,也就是没有找到任何设备。

但是,如果我在终端中使用命令$ sudo hcitool lescan,它会找到所有可用的设备。

谁能指出我解决此问题的正确方向?有没有其他方法可以将hcitool lescan 实现为 C++ 代码?

提前致谢。

【问题讨论】:

标签: c++ linux raspberry-pi bluetooth-lowenergy


【解决方案1】:

使用 BlueZ,您可以使用 hci_le_set_scan_parametershci_le_set_scan_enable 触发 BLE 扫描。

Here is an experiment written in 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++ 移植了这个例子 here

【讨论】:

  • 样本源的死链接!
  • 好的下载但是我的编译找不到标题。关于必要的先决条件或安装将东西放在哪里(如果不在系统库中并包含路径)的任何最新信息?我已经安装了 bluez 并且 python 工具可以工作了。
  • 好的 - 看来我必须为标题“sudo apt-get install libbluetooth-dev”安装 libbluetooth-dev
  • 我编译并链接了 C++ 示例,蓝牙服务正在运行。 hcitools 扫描仪显示许多 LE 设备。运行示例程序会显示“正在扫描...”并坐在那里等待。
  • 似乎 LE 扫描需要 root 权限,当我以 root 身份运行程序时,它工作正常。请注意,尽管在以非 root 身份运行时,检查返回值的调用都不会返回错误。
【解决方案2】:

NewAer SDK 支持 Pi 3 和 iOS 设备之间的 BLE 扫描和 P2P 通信。 SDK 也支持 Android,但由于操作系统处理 BLE 模式的方式,支持有限。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 2021-01-03
    • 2018-02-07
    • 2017-03-30
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多