事前に bluetoothctl で ペアリングをしておく必要があります。
プログラム
get_services.py
#! /usr/bin/python
import asyncio
from bleak import BleakScanner, BleakClient
# 対象デバイスの MAC アドレスを設定
TARGET_MAC_ADDRESS = "2C:BC:BB:65:E8:5A" # ここに対象デバイスの MAC アドレスを入力
# デバイスをスキャンして、接続後にサービスと characteristic を取得する関数
async def connect_and_list_characteristics():
print(f"Scanning for device with MAC address: {TARGET_MAC_ADDRESS}")
# BLE デバイスのスキャン
devices = await BleakScanner.discover(return_adv=True)
target_device = None
# 指定した MAC アドレスに一致するデバイスを探す
for device, adv_data in devices.values():
if device.address == TARGET_MAC_ADDRESS:
target_device = device
print(f"Found device with MAC address: {device.address}")
print(f" Name: {device.name}")
print(f" RSSI: {adv_data.rssi}")
print(f" UUIDs: {adv_data.service_uuids}")
break
if target_device is None:
print(f"No device found with MAC address: {TARGET_MAC_ADDRESS}")
return
# デバイスに接続して GATT サービスと characteristic の UUID を取得
async with BleakClient(target_device) as client:
print(f"Connected to {TARGET_MAC_ADDRESS}")
# GATT サービスを取得
# services = await client.get_services()
services = client.services
# サービスと characteristic の UUID を列挙
for service in services:
print(f"Service: {service.uuid}")
for characteristic in service.characteristics:
print(f" Characteristic: {characteristic.uuid} - Properties: {characteristic.properties}")
if __name__ == "__main__":
asyncio.run(connect_and_list_characteristics())
実行結果
$ ./get_services.py
Scanning for device with MAC address: 2C:BC:BB:65:E8:5A
Found device with MAC address: 2C:BC:BB:65:E8:5A
Name: LV-HATR
RSSI: -69
UUIDs: ['7def8317-7300-4ee6-8849-46face74ca2a']
Connected to 2C:BC:BB:65:E8:5A
Service: 00001801-0000-1000-8000-00805f9b34fb
Characteristic: 00002a05-0000-1000-8000-00805f9b34fb - Properties: ['indicate']
Service: 7def8317-7300-4ee6-8849-46face74ca2a
Characteristic: 7def8317-7302-4ee6-8849-46face74ca2a - Properties: ['write']
Characteristic: 7def8317-7301-4ee6-8849-46face74ca2a - Properties: ['read', 'notify']