Skip to content

Commit

Permalink
Merged #99.
Browse files Browse the repository at this point in the history
May improve #95 on Windows.

Merge branch 'andrewleech-scan_responses' into develop
  • Loading branch information
hbldh committed Sep 7, 2019
2 parents 53863aa + f6356e3 commit e35b1d8
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions bleak/backends/dotnet/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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"))
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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,
Expand Down

0 comments on commit e35b1d8

Please sign in to comment.