bluetoothbluezpairing

Bluetooth - How to remove pairing information on Python3


I want to remove pairing information on Python3.

I know how to remove it on bluetoothctl. The command is bluetoothctl remove xx:xx:xx:xx:xx:xx. But, I want to use only Python3.

My device is Raspberry PI. I use BlueZ.

The source code to remove is below.

#!/usr/bin/env python3
import re
import dbus

bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")

path = [str(p) for p in manager.GetManagedObjects().keys()]

# get the device path to remove 
path = list(filter(lambda s: re.match(r"/org/bluez/hci0/dev[_0-9A-F]+$", s), path))

for p in path:
  # I wish this method exists.
  # manager.RemoveObject(dbus.String(p))
  pass

I checked Bluetooth SIG, BlueZ and D-Bus(freedesktop).

Thanks.


Solution

  • The BlueZ adapter interface has a RemoveDevice method which is what bluetoothctl uses to remove devices.

    The API information is at:

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

    An example of how to remove all the devices is below:

    import dbus
    bus = dbus.SystemBus()
    manager = dbus.Interface(bus.get_object("org.bluez", "/"),
                             "org.freedesktop.DBus.ObjectManager")
    dongle = dbus.Interface(bus.get_object("org.bluez", "/org/bluez/hci0"),
                            "org.bluez.Adapter1")
    
    devices = [obj for obj, info in manager.GetManagedObjects().items() 
               if 'org.bluez.Device1' in info]
    
    
    for dev in devices:
        dongle.RemoveDevice(dev)