-
Notifications
You must be signed in to change notification settings - Fork 295
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
BleakScanner: Add async iterator scanning capability
Add `devices()` async iterator method to the `BleakScanner` which yields results of the ongoing scan, together with its class-method counterpart `scan()`.
- Loading branch information
1 parent
2abe80d
commit 4646aea
Showing
4 changed files
with
102 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
""" | ||
Scan/Discovery Async Iterator | ||
-------------- | ||
Example showing how to scan for BLE devices using async iterator instead of callback function | ||
Created on 2023-07-07 by bojanpotocnik <info@bojanpotocnik.com> | ||
""" | ||
import asyncio | ||
|
||
from bleak import BleakScanner | ||
|
||
|
||
async def main(): | ||
x = 5 | ||
print(f"Scanning for {x} devices...") | ||
async for bd, ad in BleakScanner.scan(): | ||
print(f"{x}. {bd!r} with {ad!r}") | ||
x -= 1 | ||
if x == 0: | ||
break | ||
|
||
# Ensure that asyncio loop has time to stop the scanner via the context manager exit | ||
await asyncio.sleep(0.1) | ||
|
||
x = 6 | ||
print(f"\nScanning for a device with name longer than {x} characters...") | ||
async with BleakScanner() as scanner: | ||
async for bd, ad in scanner.devices(): | ||
found = len(bd.name or "") > x or len(ad.local_name or "") > x | ||
print(f"Found{' it' if found else ''} {bd!r} with {ad!r}") | ||
if found: | ||
break | ||
|
||
|
||
if __name__ == "__main__": | ||
asyncio.run(main()) |