device = await BleakScanner.find_device_by_address(ble_address, timeout=20.0) if not device: raise BleakError(f"A device with address {ble_address} could not be found.") async withBleakClient(device)as client:
asyncdefprint_services(ble_address: str): device = await BleakScanner.find_device_by_address(ble_address, timeout=20.0) ifnot device: raise BleakError(f"A device with address {ble_address} could not be found.") asyncwith BleakClient(device) as client: svcs = await client.get_services() print("Services:") # 这里将打印该设备的所以服务 for service in svcs: print(service)
""" Service Explorer ---------------- An example showing how to access and print out the services, characteristics and descriptors of a connected GATT server. Created on 2019-03-25 by hbldh <[email protected]> """ import sys import platform import asyncio import logging from bleak import BleakClient ADDRESS = ( "54:B7:E5:79:F4:49" if platform.system() != "Darwin" else"0000fff0-0000-1000-8000-00805f9b34fb" ) iflen(sys.argv) == 2: ADDRESS = sys.argv[1] asyncdefrun(address, debug=False): log = logging.getLogger(__name__) if debug: import sys log.setLevel(logging.DEBUG) h = logging.StreamHandler(sys.stdout) h.setLevel(logging.DEBUG) log.addHandler(h) asyncwith BleakClient(address) as client: log.info(f"Connected: {client.is_connected}") for service in client.services: log.info(f"[Service] {service}") for char in service.characteristics: if"read"in char.properties: try: value = bytes(await client.read_gatt_char(char.uuid)) log.info( f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}" ) except Exception as e: log.error( f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {e}" ) else: value = None log.info( f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}" ) for descriptor in char.descriptors: try: value = bytes( await client.read_gatt_descriptor(descriptor.handle) ) log.info(f"\t\t[Descriptor] {descriptor}) | Value: {value}") except Exception as e: log.error(f"\t\t[Descriptor] {descriptor}) | Value: {e}") if __name__ == "__main__": loop = asyncio.get_event_loop() loop.set_debug(True) loop.run_until_complete(run(ADDRESS, True))