pythonlinuxbluetoothbluezpybluez

Python: How to get connected bluetooth devices? (Linux)


I need all connected bluetooth devices to my computer. I found library, but i can't get connected devices

Simple inquiry example:

    import bluetooth

    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    print("Found {} devices.".format(len(nearby_devices)))

    for addr, name in nearby_devices:
        print("  {} - {}".format(addr, name))

Solution

  • The snippet of code in the question is doing a scan for new devices rather than reporting on connected devices.

    The PyBluez library is not under active development so I tend to avoid it.

    BlueZ (the Bluetooth stack on Linux) offers a set of API's through D-Bus that are accessible with Python using D-Bus bindings. I prefer pydbus for most situations.

    The BlueZ API is documented at:

    https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/org.bluez.Adapter.rst

    https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/org.bluez.Device.rst

    As an example of how to implement this in Python3:

    import pydbus
    
    bus = pydbus.SystemBus()
    
    adapter = bus.get('org.bluez', '/org/bluez/hci0')
    mngr = bus.get('org.bluez', '/')
    
    def list_connected_devices():
        mngd_objs = mngr.GetManagedObjects()
        for path in mngd_objs:
            con_state = mngd_objs[path].get('org.bluez.Device1', {}).get('Connected', False)
            if con_state:
                addr = mngd_objs[path].get('org.bluez.Device1', {}).get('Address')
                name = mngd_objs[path].get('org.bluez.Device1', {}).get('Name')
                print(f'Device {name} [{addr}] is connected')
    
    if __name__ == '__main__':
        list_connected_devices()