Skip to content

Commit

Permalink
add permissions request method
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomasz Duda committed Oct 2, 2024
1 parent 3393c46 commit 2431e60
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 26 deletions.
9 changes: 9 additions & 0 deletions bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,15 @@ async def discover(

return scanner.discovered_devices

async def request_permissions(self, **kwargs) -> None:
"""
Request permissions for the BleakScanner.
Args:
**kwargs: Additional arguments to be passed to the :class:`BleakScanner` backend.
"""
await self._backend.request_permissions(**kwargs)

@property
def discovered_devices(self) -> List[BLEDevice]:
"""
Expand Down
61 changes: 36 additions & 25 deletions bleak/backends/p4android/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from android.broadcast import BroadcastReceiver
from android.permissions import Permission, request_permissions
from jnius import cast, java_method
from jnius import cast, java_method, autoclass

from ...exc import BleakError
from ..scanner import AdvertisementData, AdvertisementDataCallback, BaseBleakScanner
Expand Down Expand Up @@ -61,6 +61,41 @@ def __init__(
def __del__(self) -> None:
self.__stop()

async def request_permissions(self, **kwargs) -> None:
loop = asyncio.get_running_loop()
permission_acknowledged = loop.create_future()
def handle_permissions(permissions, grantResults):
if any(grantResults):
loop.call_soon_threadsafe(
permission_acknowledged.set_result, grantResults
)
else:
loop.call_soon_threadsafe(
permission_acknowledged.set_exception(
BleakError("User denied access to " + str(permissions))
)
)
if not kwargs.get("permissions"):
permissions = [
Permission.ACCESS_FINE_LOCATION,
Permission.ACCESS_COARSE_LOCATION,
Permission.ACCESS_BACKGROUND_LOCATION,
]
VERSION = autoclass('android.os.Build$VERSION')
if VERSION.SDK_INT >= 31:
permissions.extend([
Permission.BLUETOOTH_SCAN,
Permission.BLUETOOTH_CONNECT,
])
else:
permissions = kwargs.get("permissions")

request_permissions(
permissions,
handle_permissions,
)
await permission_acknowledged

async def start(self) -> None:
if BleakScannerP4Android.__scanner is not None:
raise BleakError("A BleakScanner is already scanning on this adapter.")
Expand All @@ -73,30 +108,6 @@ async def start(self) -> None:
if self.__callback is None:
self.__callback = _PythonScanCallback(self, loop)

permission_acknowledged = loop.create_future()

def handle_permissions(permissions, grantResults):
if any(grantResults):
loop.call_soon_threadsafe(
permission_acknowledged.set_result, grantResults
)
else:
loop.call_soon_threadsafe(
permission_acknowledged.set_exception(
BleakError("User denied access to " + str(permissions))
)
)

request_permissions(
[
Permission.ACCESS_FINE_LOCATION,
Permission.ACCESS_COARSE_LOCATION,
"android.permission.ACCESS_BACKGROUND_LOCATION",
],
handle_permissions,
)
await permission_acknowledged

self.__adapter = defs.BluetoothAdapter.getDefaultAdapter()
if self.__adapter is None:
raise BleakError("Bluetooth is not supported on this hardware platform")
Expand Down
9 changes: 9 additions & 0 deletions bleak/backends/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,15 @@ def set_scanning_filter(self, **kwargs) -> None:
"""
raise NotImplementedError()

@abc.abstractmethod
async def request_permissions(self, **kwargs) -> None:
"""Request permissions for the BleakScanner.
Args:
**kwargs: Additional arguments to be passed to the :class:`BleakScanner` backend.
"""
raise NotImplementedError()


def get_platform_scanner_backend_type() -> Type[BaseBleakScanner]:
"""
Expand Down
4 changes: 3 additions & 1 deletion examples/kivy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ async def example(self):
while self.running:
try:
self.line("scanning")
scanned_devices = await bleak.BleakScanner.discover(1)
scanner = bleak.BleakScanner()
await scanner.request_permissions()
scanned_devices = scanner.discover(1)
self.line("scanned", True)

if len(scanned_devices) == 0:
Expand Down

0 comments on commit 2431e60

Please sign in to comment.