【问题标题】:BlueZ-pyDbus 2 client connected in HCI0在 HCI0 中连接的 BlueZ-pyDbus 2 客户端
【发布时间】:2020-08-24 05:47:43
【问题描述】:

我已通过 pyDbus 同时成功连接到 2 个 BLE 服务器。但是,当我想读/写第一个 BLE 服务器时,我无法这样做。我检查了这个问题,发现第二个 BLE 服务器连接克服了第一个。附上一段sn-p的代码:

def device_Init(macAdd):

     adapter = bus.get('org.bluez','/org/bluez/hci0')
     dev = bus.get('org.bluez','/dev_(the macAdd)')
     mngr = bus.get('org.bluez','/')
    
     dev.Connect()

当然,当需要断开连接时,请发出dev.Disconnect()

如何分离两个连接设备之间的连接、读/写和断开部分?我尝试创建另一个函数但没有成功。

【问题讨论】:

    标签: python bluetooth-lowenergy raspberry-pi3 dbus bluez


    【解决方案1】:

    您的代码的问题在于,当您使用不同的设备地址再次创建 dev 属性时,它会被覆盖。您可以为第二个设备设置第二个变量。

    然而,一个更 Pythonic 的方式可能是有一个你实例化两次的类。

    这是一个示例:

    from time import sleep
    import pydbus
    
    bus = pydbus.SystemBus()
    
    mngr = bus.get('org.bluez', '/')
    
    def get_characteristic_path(dev_path, uuid):
        mng_objs = mngr.GetManagedObjects()
        for path in mng_objs:
            chr_uuid = mng_objs[path].get('org.bluez.GattCharacteristic1', {}).get('UUID')
            if path.startswith(dev_path) and chr_uuid == uuid:
               return path
    
    class MyRemoteDevice:
        CHAR_UUID = 'e95dda90-251d-470a-a062-fa1922dfa9a8'
    
        def __init__(self, mac_addr):
            device_path = f"/org/bluez/hci0/dev_{mac_addr.replace(':', '_')}"
            self.device = bus.get('org.bluez', device_path)
    
            # Placeholder for characteristic details
            self.characteristic = None
    
        def _get_gatt_details(self):
            char_path = get_characteristic_path(self.device._path,
                                                MyRemoteDevice.CHAR_UUID)
            self.characteristic = bus.get('org.bluez', char_path)
    
    
        def connect(self):
            self.device.Connect()
            # Check GATT services have been resolved before continuing
            while not self.device.ServicesResolved:
                sleep(0.25)
            self._get_gatt_details()
    
        def disconnect(self):
            self.device.Disconnect()
    
        def read(self):
            return self.characteristic.ReadValue({})
    
        def write(self, new_value):
            self.characteristic.WriteValue(new_value, {})
    
    
    my_first_dev = MyRemoteDevice('11:22:33:44:55:66')
    my_second_dev = MyRemoteDevice('22:33:44:55:66:77')
    
    my_first_dev.connect()
    my_second_dev.connect()
    
    print(my_first_dev.read())
    print(my_second_dev.read())
    
    my_first_dev.disconnect()
    my_second_dev.disconnect()
    
    
    

    【讨论】:

    • 再次感谢。只是想知道。是否可以在 pyDbus 中同时使用 2 个蓝牙(RPI 和 USB 蓝牙加密狗)(例如 HCI0 和 HCI1)。其次,使用 pyDbus 创建 GATT 服务器的可行性如何?只是古玩
    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2017-06-25
    • 2010-11-18
    • 1970-01-01
    相关资源
    最近更新 更多