Skip to content

Commit 478d3f8

Browse files
author
Olaf Fricke
committed
Characteristics are addressed by uuid and the bleak client has to be used without context manager to work on a raspi
1 parent 5cc8c72 commit 478d3f8

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

custom_components/ble_monitor/ble_parser/get_beacon_key.py

+16-17
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,19 @@
2020
import sys
2121

2222
from bleak import BleakClient
23+
from bleak.uuids import normalize_uuid_16
2324

2425
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}$"
2526

2627
UUID_SERVICE = "fe95"
2728

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+
2836
MI_KEY1 = bytes([0x90, 0xCA, 0x85, 0xDE])
2937
MI_KEY2 = bytes([0x92, 0xAB, 0x54, 0xFA])
3038
SUBSCRIBE_TRUE = bytes([0x01, 0x00])
@@ -99,23 +107,11 @@ async def get_beacon_key(mac, product_id):
99107

100108
# Connect
101109
print("Connection in progress...")
102-
async with BleakClient(mac, services=[UUID_SERVICE]) as client:
110+
client = BleakClient(mac)
111+
try:
112+
await client.connect()
103113
print("Successful connection!")
104114

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-
119115
# An asyncio future object is needed for callback handling
120116
future = asyncio.get_event_loop().create_future()
121117

@@ -153,9 +149,12 @@ async def get_beacon_key(mac, product_id):
153149
print(f"beaconKey: '{beacon_key}'")
154150
print(f"firmware_version: '{firmware_version}'")
155151

156-
# Device will disconnect when block exits.
157152
print("Disconnection in progress...")
158-
print("Disconnected!")
153+
except Exception as e:
154+
print(e)
155+
finally:
156+
await client.disconnect()
157+
print("Disconnected!")
159158

160159

161160
async def main(argv):

0 commit comments

Comments
 (0)