0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python3: GATT の Characteristic を調べる

Posted at

事前に 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']
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?