BlueZをD-Busから使う方法について
システムに接続されているBluetoothアダプタを表示する方法を調べました。
linuxではhciconfigを使うとBluetoothアダプタの情報が表示されます。
pi@raspberrypi: $ hciconfig
hci0: Type: BR/EDR Bus: USB
BD Address: 00:09:DD:42:7A:EB ACL MTU: 310:10 SCO MTU: 64:8
UP RUNNING PSCAN
RX bytes:10484 acl:149 sco:0 events:470 errors:0
TX bytes:5074 acl:139 sco:0 commands:88 errors:0
get-adapter.py
- dbus-python を使いました。
- 参考にしたbluezのコードがdbus-pythonを使っていたので。
get_adapter.py
# !/usr/bin/python
import dbus
SERVICE_NAME = "org.bluez"
ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter1"
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object(SERVICE_NAME, "/"),
"org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
for path, ifaces in objects.iteritems():
adapter = ifaces.get(ADAPTER_INTERFACE)
if adapter is None:
continue
print path
bdaddress = adapter.get("Address")
if bdaddress is None:
continue
print bdaddress
- システムのdbusを取得して、bluezのmanagerを取得して、bluezのobjectsを取得
- bluezのobjectsからAdapter1を含むadapterを取得して、pathを表示
- adapterからAddressのプロパティを取得して、アドレスを表示
実行結果
pi@raspberrypi: $ ./get-adapter.py
/org/bluez/hci0
00:09:DD:42:7A:EB
参考
- bluezのtest/bluezutils.py https://git.kernel.org/cgit/bluetooth/bluez.git/tree/test/bluezutils.py
- bluezのdoc/adapter-api.txt https://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/adapter-api.txt
- https://dbus.freedesktop.org/doc/dbus-python/