|
20 | 20 | import sys
|
21 | 21 |
|
22 | 22 | from bleak import BleakClient
|
| 23 | +from bleak.uuids import normalize_uuid_16 |
23 | 24 |
|
24 | 25 | MAC_PATTERN = r"^[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}$"
|
25 | 26 |
|
26 | 27 | UUID_SERVICE = "fe95"
|
27 | 28 |
|
| 29 | +# The characteristics of the 'fe95' service have unique uuid values and thus can be addressed via their uuid |
| 30 | +# this can be checked by using the service explorer from https://github.com/hbldh/bleak/blob/master/examples/service_explorer.py |
| 31 | +HANDLE_AUTH = normalize_uuid_16(0x0001) |
| 32 | +HANDLE_FIRMWARE_VERSION = normalize_uuid_16(0x0004) |
| 33 | +HANDLE_AUTH_INIT = normalize_uuid_16(0x0010) |
| 34 | +HANDLE_BEACON_KEY = normalize_uuid_16(0x0014) |
| 35 | + |
28 | 36 | MI_KEY1 = bytes([0x90, 0xCA, 0x85, 0xDE])
|
29 | 37 | MI_KEY2 = bytes([0x92, 0xAB, 0x54, 0xFA])
|
30 | 38 | SUBSCRIBE_TRUE = bytes([0x01, 0x00])
|
@@ -99,23 +107,11 @@ async def get_beacon_key(mac, product_id):
|
99 | 107 |
|
100 | 108 | # Connect
|
101 | 109 | print("Connection in progress...")
|
102 |
| - async with BleakClient(mac, services=[UUID_SERVICE]) as client: |
| 110 | + client = BleakClient(mac) |
| 111 | + try: |
| 112 | + await client.connect() |
103 | 113 | print("Successful connection!")
|
104 | 114 |
|
105 |
| - # Map the characteristics name to the handle ids (uuids won't work) |
106 |
| - # The service explorer from https://github.com/hbldh/bleak/blob/master/examples/service_explorer.py shows the characteristics |
107 |
| - # (use 'python service_explorer.py --address <MAC> --service fe95' to dump the 'Xiaomi Inc.' service) |
108 |
| - for service in client.services: |
109 |
| - for char in service.characteristics: |
110 |
| - if (char.description == 'token'): |
111 |
| - HANDLE_AUTH = char.handle |
112 |
| - elif (char.description == 'Version'): |
113 |
| - HANDLE_FIRMWARE_VERSION = char.handle |
114 |
| - elif (char.description == 'Authentication'): |
115 |
| - HANDLE_AUTH_INIT = char.handle |
116 |
| - elif (char.description == 'beacon_key'): |
117 |
| - HANDLE_BEACON_KEY = char.handle |
118 |
| - |
119 | 115 | # An asyncio future object is needed for callback handling
|
120 | 116 | future = asyncio.get_event_loop().create_future()
|
121 | 117 |
|
@@ -153,9 +149,12 @@ async def get_beacon_key(mac, product_id):
|
153 | 149 | print(f"beaconKey: '{beacon_key}'")
|
154 | 150 | print(f"firmware_version: '{firmware_version}'")
|
155 | 151 |
|
156 |
| - # Device will disconnect when block exits. |
157 | 152 | print("Disconnection in progress...")
|
158 |
| - print("Disconnected!") |
| 153 | + except Exception as e: |
| 154 | + print(e) |
| 155 | + finally: |
| 156 | + await client.disconnect() |
| 157 | + print("Disconnected!") |
159 | 158 |
|
160 | 159 |
|
161 | 160 | async def main(argv):
|
|
0 commit comments