首页 > 解决方案 > Bluetoothctl 或 gatttool 用于来自多个设备的 BLE 通知

问题描述

我已经阅读了有关该主题的许多问题,但没有找到有关如何最好(或者甚至可能)使用任何库或 API(最好是命令行或 Python 库)一次接收来自多个设备的通知的信息。

在连接到不同的设备后,例如心率监测器和电话,或两个 HR 监测器,有没有办法同时从每个设备接收来自 1 个服务的数据?

编辑:

只要我不请求相同的服务,我就可以连接具有相同特性的不同设备,并能够使用 Bluetoothctl(Bluez 的一部分)从它们那里获取通知,这部分回答了我的问题;仍然,有谁知道更好的方法来做到这一点?

标签: bluetoothbluetooth-lowenergybluetooth-gatt

解决方案


1)首先有一个 github python 项目,它在 Raspberry Pi 上的 Linux 中执行此操作:https ://github.com/IanHarvey/bluepy

2)其次,来自 Anthony Chiu 的这段代码使用该 API 通过通知与多个设备进行通信:

  from bluepy.btle import Scanner, DefaultDelegate, Peripheral
    import threading

    class NotificationDelegate(DefaultDelegate):

    def __init__(self, number):
        DefaultDelegate.__init__(self)
        self.number = number

    def handleNotification(self, cHandle, data):
        print 'Notification:\nConnection:'+str(self.number)+ \nHandler:'+str(cHandle)+'\nMsg:'+data

    bt_addrs = ['00:15:83:00:45:98', '00:15:83:00:86:72']
    connections = []
    connection_threads = []
    scanner = Scanner(0)

    class ConnectionHandlerThread (threading.Thread):
        def __init__(self, connection_index):
            threading.Thread.__init__(self)
            self.connection_index = connection_index

        def run(self):
            connection = connections[self.connection_index]
            connection.setDelegate(NotificationDelegate(self.connection_index))
            while True:
                if connection.waitForNotifications(1):
                    connection.writeCharacteristic(37, 'Thank you for the notification!')

    while True:
        print'Connected: '+str(len(connection_threads))
        print 'Scanning...'
        devices = scanner.scan(2)
        for d in devices:
            print(d.addr)
            if d.addr in bt_addrs:
                p = Peripheral(d)
                connections.append(p)
                t = ConnectionHandlerThread(len(connections)-1)
                t.start()
                connection_threads.append(t)

3) 我将使用您可能尝试过的 bluetoothctl 编写手动连接选项。由于这里没有列出,我也将添加:

**使用 bluetoothctl 手动连接:** 要获取特征列表,您可以在建立连接并通过bluetoothctl 进入Generic Attribute Submenumenu gatt后使用“list-attributes”命令,它应该打印与上面相同的列表:

list-attributes 00:61:61:15:8D:60

要读取一个属性,您首先选择它,使用 -you guessed it-“select-attribute”命令:

select-attribute /org/bluez/hci0/dev_00_61_61_15_8D_60/service000a/char000b

之后,您可以发出“读取”命令,无需任何参数。

要连续读取特性(如果特性支持),请使用“通知”命令:

notify on

PS:这是我在 stackoverflow 上的第一个答案 :) 我也是 BLE 的新手,所以请耐心等待。我对您的项目感兴趣,感谢任何链接/联系方式:) 您可以在 alexandrudancu.com 上找到我


推荐阅读