1

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))
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22

2 Answers2

4

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/adapter-api.txt

https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt

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()
ukBaz
  • 6,985
  • 2
  • 8
  • 31
  • 1
    if anyone has problems with "pydbus no module named gi" then [this](https://askubuntu.com/questions/80448/what-would-cause-the-gi-module-to-be-missing-from-python) will help you – Kirill Martyuk Aug 11 '20 at 08:05
0

I found a solution, but it uses terminal.

Before using you need to install dependencies

Bluez

Code

def get_connected_devices():
    bounded_devices = check_output(['bt-device', '-l']).decode().split("\n")[1:-1]
    connected_devices = list()
    for device in bounded_devices:
        name = device[:device.rfind(' ')]
        #mac_address regex
        regex = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}\\.[0-9a-fA-F]{4}\\.[0-9a-fA-F]{4})$'
        mac_address = re.search(regex, device).group(0)

        device_info = check_output(['bt-device', '-i', mac_address]).decode()
        connection_state = device_info[device_info.find('Connected: ') + len('Connected: ')]
        if connection_state == '1':
            connected_devices.append({"name": name, "address": mac_address})
    return connected_devices