1

I'm trying to connect a LE device to my Linux laptop through a python script. Nevertheless, the device address must be specified as "random" for the connection to happen, and the examples that I have (mainly https://www.bluetooth.com/blog/the-bluetooth-for-linux-developers-study-guide/) doesn't show any way of doing it.

The device-api from BlueZ (https://github.com/bluez/bluez/blob/master/doc/device-api.txt) list it as one of its properties, but my knowledge is still incomplete, and I couldn't manage to find a way of setting this property.

Any idea, indication or example will be immensely helpful.

Following is my script

PATH_DA_BSN = "/org/bluez/hci0/dev_CA_DB_17_8A_02_97"

ADAPTER_NAME = "hci0"
BLUEZ_SERVICE_NAME = "org.bluez"
BLUEZ_NAMESPACE = "/org/bluez/"
DEVICE_INTERFACE = BLUEZ_SERVICE_NAME + ".Device1"
ADAPTER_INTERFACE = BLUEZ_SERVICE_NAME + ".Adapter1"

def connect():
    global bus
    global device_interface
    try:
        device_interface.Connect()
    except Exception as e:
        print("Failed to connect")
        print(e.get_dbus_name())
        print(e.get_dbus_message())
        if ("UnknownObject" in e.get_dbus_name()):
            print("Try scanning first to resolve this problem")
        return bluetooth_constants.RESULT_EXCEPTION
    else:
        print("Connected OK")
        return bluetooth_constants.RESULT_OK

bus = dbus.SystemBus()

bsn_proxy = bus.get_object(BLUEZ_SERVICE_NAME, PATH_DA_BSN)
device_interface = dbus.Interface(bsn_proxy, DEVICE_INTERFACE)

adapter_path = BLUEZ_NAMESPACE + ADAPTER_NAME

# acquire the adapter interface so we can call its methods
adapter_object = bus.get_object(BLUEZ_SERVICE_NAME, adapter_path)
adapter_interface = dbus.Interface(adapter_object, ADAPTER_INTERFACE)


print("Connecting to " + PATH_DA_BSN)
connect()

2 Answers2

1

The AddressType is already set from when the device was discovered.

You can iterate through the already discovered devices using D-Bus's GetManagedObjects functionality to find what the address type is set to for each device.

An example using the pydbus bindings:

>>> import pydbus
>>> bus = pydbus.SystemBus()
>>> mngr = bus.get('org.bluez', '/')
>>> mngd_objs = mngr.GetManagedObjects()
>>> for path, iface in mngd_objs.items():
...     if 'org.bluez.Device1' in iface.keys():
...         print(iface.get('org.bluez.Device1', {}).get('AddressType'))
... 
public
random
random
public
public
public
random
public
public
public
random
ukBaz
  • 6,985
  • 2
  • 8
  • 31
0

you have 2 options:

  1. Do a discovery and connect when the device is found. In this case Bluez will already know the addresstype.
  2. Call the method ConnectDevice which is available on an adapter. In this method you can pass the ‘random’ parameter. Keep in mind this method is marked as experimental.

I recommend option 1