List nearby/discoverable bluetooth devices, including already paired, in Python, on Linux
Since the adoption of the version 5 of the Bluetooth API most of the functions used in the @Micke solutions were dropped and the interaction
with the bus take place throught the ObjectManager.GetManagedObjects [1]
import dbus
def proxyobj(bus, path, interface):
""" commodity to apply an interface to a proxy object """
obj = bus.get_object('org.bluez', path)
return dbus.Interface(obj, interface)
def filter_by_interface(objects, interface_name):
""" filters the objects based on their support
for the specified interface """
result = []
for path in objects.keys():
interfaces = objects[path]
for interface in interfaces.keys():
if interface == interface_name:
result.append(path)
return result
bus = dbus.SystemBus()
# we need a dbus object manager
manager = proxyobj(bus, "/", "org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
# once we get the objects we have to pick the bluetooth devices.
# They support the org.bluez.Device1 interface
devices = filter_by_interface(objects, "org.bluez.Device1")
# now we are ready to get the informations we need
bt_devices = []
for device in devices:
obj = proxyobj(bus, device, 'org.freedesktop.DBus.Properties')
bt_devices.append({
"name": str(obj.Get("org.bluez.Device1", "Name")),
"addr": str(obj.Get("org.bluez.Device1", "Address"))
})
In the bt_device
list there are dictionaries with the desired data:
ie
for example
[{
'name': 'BBC micro:bit [zigiz]',
'addr': 'E0:7C:62:5A:B1:8C'
}, {
'name': 'BBC micro:bit [putup]',
'addr': 'FC:CC:69:48:5B:32'
}]
Reference:
[1] http://www.bluez.org/bluez-5-api-introduction-and-porting-guide/
How to find visible bluetooth devices in Python?
PyBluez:
from bluetooth import *
print "performing inquiry..."
nearby_devices = discover_devices(lookup_names = True)
print "found %d devices" % len(nearby_devices)
for name, addr in nearby_devices:
print " %s - %s" % (addr, name)
See also Programming Bluetooth using Python
The important thing is you can use lookup_names = True
from bluez Docs:
if lookup_names is False, returns a list of bluetooth addresses.
if lookup_names is True, returns a list of (address, name) tuples
How to list bluetooth devices near me using PowerShell
The PowerShell command :
Get-ChildItem -Path HKLM:\SYSTEM\ControlSet001\Services\DeviceAssociationService\State\Store\ | Select-String -Pattern Bluetooth
will print devices already paired :
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\DeviceAssociationService\State\Store\Bluetooth#BluetoothXX:XX:XX:XX:XX:b2-YY:YY:YY:YY:YY:YY
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\DeviceAssociationService\State\Store\Bluetooth#BluetoothXX:XX:XX:XX:XX:b2-ZZ:ZZ:ZZ:ZZ:ZZ:ZZ
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\DeviceAssociationService\State\Store\BluetoothLE#BluetoothLEXX:XX:XX:XX:XX:b2-WW:WW:WW:WW:WW:WW
The XX:XX:XX:XX:XX
values is your Bluetooth MAC adress.
Bluetooth - listening to a pairing even in a Linux device in Python
Good morning, there is a library written in Python that handle Bluetooth connection for you already PyBluez
to install use sudo pip install pybluez
here is an example on how to use sockets to communicate with bluetooth devices
import bluetooth
bd_addr = "01:23:45:67:89:AB"
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("hello!!")
sock.close()
the complete guide is at Bluetooth Programming with PyBluez
`
Python: How to get connected bluetooth devices? (Linux)
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()
Related Topics
How to Sort Pandas Dataframe from One Column
Proxies With Python 'Requests' Module
How to Plot Multiple Dataframes in Subplots
Typeerror: 'Str' Does Not Support the Buffer Interface
Runtimeerror: Invalid Display Variable
How to Delete a Directory Created with Tempfile.Mkdtemp
Ctypes Loading a C Shared Library That Has Dependencies
Linux Bash Script Running Multiple Python
How to Install Lxml for Python Without Administative Rights on Linux
Python Script Prints Output of Os.System Before Print
Creating Pyqt5 Buttons in a Loop: All Buttons Trigger the Same Callback
A Way to "Listen" for Changes to a File System from Python on Linux
Subprocess.Popen(): Oserror: [Errno 8] Exec Format Error in Python
How to Cleanly Kill Subprocesses in Python