使用 python 查找低功耗蓝牙

2023-12-20

是否可以修改此代码以包含蓝牙低功耗设备?https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py?r=1 https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py?r=1

我可以找到手机等设备和其他蓝牙 4.0 设备,但找不到任何 BLE。如果无法修改,是否可以运行 hcitool lescan 并从 python 内的 hci 转储中提取数据?我可以使用这些工具查看我正在寻找的设备,它会在 hcidump 中提供 RSSI,这就是我的最终目标。从 BLE 设备获取 MAC 地址和 RSSI。

Thanks!


正如我在评论中所说,该库不适用于 BLE。

以下是一些执行简单 BLE 扫描的示例代码:

import sys
import os
import struct
from ctypes import (CDLL, get_errno)
from ctypes.util import find_library
from socket import (
    socket,
    AF_BLUETOOTH,
    SOCK_RAW,
    BTPROTO_HCI,
    SOL_HCI,
    HCI_FILTER,
)

if not os.geteuid() == 0:
    sys.exit("script only works as root")

btlib = find_library("bluetooth")
if not btlib:
    raise Exception(
        "Can't find required bluetooth libraries"
        " (need to install bluez)"
    )
bluez = CDLL(btlib, use_errno=True)

dev_id = bluez.hci_get_route(None)

sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)
sock.bind((dev_id,))

err = bluez.hci_le_set_scan_parameters(sock.fileno(), 0, 0x10, 0x10, 0, 0, 1000);
if err < 0:
    raise Exception("Set scan parameters failed")
    # occurs when scanning is still enabled from previous call

# allows LE advertising events
hci_filter = struct.pack(
    "<IQH", 
    0x00000010, 
    0x4000000000000000, 
    0
)
sock.setsockopt(SOL_HCI, HCI_FILTER, hci_filter)

err = bluez.hci_le_set_scan_enable(
    sock.fileno(),
    1,  # 1 - turn on;  0 - turn off
    0, # 0-filtering disabled, 1-filter out duplicates
    1000  # timeout
)
if err < 0:
    errnum = get_errno()
    raise Exception("{} {}".format(
        errno.errorcode[errnum],
        os.strerror(errnum)
    ))

while True:
    data = sock.recv(1024)
    # print bluetooth address from LE Advert. packet
    print(':'.join("{0:02x}".format(x) for x in data[12:6:-1]))

我必须通过查看将所有这些拼凑在一起hcitool and gatttoolBluez 附带的源代码。该代码完全依赖于libbluetooth-dev所以你必须先确保你已经安装了它。

更好的方法是使用 dbus 进行调用bluetoothd,但我还没有机会研究这一点。此外,在建立 BLE 连接后,dbus 接口的功能也受到限制。

EDIT:

Martin Tramšak 指出,在 Python 2 中你需要将最后一行更改为print(':'.join("{0:02x}".format(ord(x)) for x in data[12:6:-1]))

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 python 查找低功耗蓝牙 的相关文章