99import sys
1010import zipfile
1111from tempfile import NamedTemporaryFile
12- from typing import BinaryIO , Optional
12+ from typing import BinaryIO , Dict , Optional
1313
1414from bleak import BleakClient , BleakScanner
1515from bleak .backends .device import BLEDevice
@@ -267,11 +267,22 @@ async def flash_ble(hub_kind: HubKind, firmware: bytes, metadata: dict):
267267
268268 print (f"Searching for { hub_kind .name } hub..." )
269269
270+ # TODO: add upstream feature to Bleak to allow getting device, adv tuple
271+ # as return value from find_device_by_filter()
272+ # https://github.com/hbldh/bleak/issues/1277
273+
274+ device_adv_map : Dict [str , AdvertisementData ] = {}
275+
276+ def map_and_match (device : BLEDevice , adv : AdvertisementData ):
277+ # capture the adv data for later use
278+ device_adv_map [device .address ] = adv
279+ return match_hub (hub_kind , adv )
280+
270281 # scan for hubs in bootloader mode, running official LEGO firmware or
271282 # running Pybricks firmware
272283
273284 device = await BleakScanner .find_device_by_filter (
274- lambda _d , a : match_hub ( hub_kind , a ) ,
285+ map_and_match ,
275286 service_uuids = [
276287 LWP3_BOOTLOADER_SERVICE_UUID ,
277288 LWP3_HUB_SERVICE_UUID ,
@@ -283,16 +294,18 @@ async def flash_ble(hub_kind: HubKind, firmware: bytes, metadata: dict):
283294 print ("timed out" , file = sys .stderr )
284295 return
285296
297+ adv_data = device_adv_map [device .address ]
298+
286299 # if not already in bootlaoder mode, we need to reboot into bootloader mode
287- if LWP3_HUB_SERVICE_UUID in device . metadata [ "uuids" ] :
300+ if LWP3_HUB_SERVICE_UUID in adv_data . service_uuids :
288301 print ("Found hub running official LEGO firmware." )
289302 await reboot_official_to_bootloader (hub_kind , device )
290- elif PYBRICKS_SERVICE_UUID in device . metadata [ "uuids" ] :
303+ elif PYBRICKS_SERVICE_UUID in adv_data . service_uuids :
291304 print ("Found hub running Pybricks firmware." )
292305 await reboot_pybricks_to_bootloader (hub_kind , device )
293306
294307 # if not previously in bootlaoder mode, scan again, this time only for bootloader
295- if LWP3_BOOTLOADER_SERVICE_UUID not in device . metadata [ "uuids" ] :
308+ if LWP3_BOOTLOADER_SERVICE_UUID not in adv_data . service_uuids :
296309 device = await BleakScanner .find_device_by_filter (
297310 lambda _d , a : match_hub (hub_kind , a ),
298311 service_uuids = [
0 commit comments