From f6356e3830d51ff6021e7714d4720147bf8b36ab Mon Sep 17 00:00:00 2001 From: Andrew Leech Date: Tue, 13 Aug 2019 18:22:34 +1000 Subject: [PATCH] .net: Enable active scanning during discovery and check scan responses for local name. --- bleak/backends/dotnet/discovery.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/bleak/backends/dotnet/discovery.py b/bleak/backends/dotnet/discovery.py index 22818e34..dded0062 100644 --- a/bleak/backends/dotnet/discovery.py +++ b/bleak/backends/dotnet/discovery.py @@ -18,7 +18,8 @@ from System import Array, Byte from Windows.Devices import Enumeration -from Windows.Devices.Bluetooth.Advertisement import BluetoothLEAdvertisementWatcher +from Windows.Devices.Bluetooth.Advertisement import \ + BluetoothLEAdvertisementWatcher, BluetoothLEScanningMode, BluetoothLEAdvertisementType from Windows.Storage.Streams import DataReader, IBuffer logger = logging.getLogger(__name__) @@ -47,6 +48,7 @@ async def discover( watcher = BluetoothLEAdvertisementWatcher() devices = {} + scan_responses = {} def _format_bdaddr(a): return ":".join("{:02X}".format(x) for x in a.to_bytes(6, byteorder="big")) @@ -63,8 +65,12 @@ def _format_event_args(e): def AdvertisementWatcher_Received(sender, e): if sender == watcher: logger.debug("Received {0}.".format(_format_event_args(e))) - if e.BluetoothAddress not in devices: - devices[e.BluetoothAddress] = e + if e.AdvertisementType == BluetoothLEAdvertisementType.ScanResponse: + if e.BluetoothAddress not in scan_responses: + scan_responses[e.BluetoothAddress] = e + else: + if e.BluetoothAddress not in devices: + devices[e.BluetoothAddress] = e def AdvertisementWatcher_Stopped(sender, e): if sender == watcher: @@ -77,6 +83,8 @@ def AdvertisementWatcher_Stopped(sender, e): watcher.Received += AdvertisementWatcher_Received watcher.Stopped += AdvertisementWatcher_Stopped + watcher.ScanningMode = BluetoothLEScanningMode.Active + # Watcher works outside of the Python process. watcher.Start() await asyncio.sleep(timeout, loop=loop) @@ -101,10 +109,13 @@ def AdvertisementWatcher_Stopped(sender, e): reader = DataReader.FromBuffer(md) reader.ReadBytes(b) data[m.CompanyId] = bytes(b) + local_name = d.Advertisement.LocalName + if not local_name and d.BluetoothAddress in scan_responses: + local_name = scan_responses[d.BluetoothAddress].Advertisement.LocalName found.append( BLEDevice( bdaddr, - d.Advertisement.LocalName, + local_name, d, uuids=uuids, manufacturer_data=data,