Skip to content

Commit

Permalink
BleakScanner: Use bool "passive" instead "scanning_mode" parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
bojanpotocnik committed Dec 5, 2022
1 parent ba172f0 commit d655ddd
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 43 deletions.
20 changes: 14 additions & 6 deletions bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,10 @@ class BleakScanner:
Optional list of service UUIDs to filter on. Only advertisements
containing this advertising data will be received. Required on
macOS >= 12.0, < 12.3 (unless you create an app with ``py2app``).
scanning_mode:
Set to ``"passive"`` to avoid the ``"active"`` scanning mode.
Passive scanning is not supported on macOS! Will raise
:class:`BleakError` if set to ``"passive"`` on macOS.
passive:
Use passive instead of active scanning mode. Passive scanning
is not supported on macOS! Will raise :class:`BleakError` if
set to ``True`` on macOS.
bluez:
Dictionary of arguments specific to the BlueZ backend.
cb:
Expand All @@ -114,7 +114,7 @@ def __init__(
self,
detection_callback: Optional[AdvertisementDataCallback] = None,
service_uuids: Optional[List[str]] = None,
scanning_mode: Literal["active", "passive"] = "active",
passive: bool = False,
*,
bluez: BlueZScannerArgs = {},
cb: CBScannerArgs = {},
Expand All @@ -125,10 +125,18 @@ def __init__(
get_platform_scanner_backend_type() if backend is None else backend
)

# Backward compatibility with scanning_mode: Literal["active", "passive"] parameter
scanning_mode = kwargs.get("scanning_mode")
if scanning_mode is not None:
_logger.debug(
f"Overwriting parameter passive={passive} with legacy scanning_mode={scanning_mode}"
)
passive = scanning_mode == "passive"

self._backend = PlatformBleakScanner(
detection_callback,
service_uuids,
scanning_mode,
passive,
bluez=bluez,
cb=cb,
**kwargs,
Expand Down
18 changes: 9 additions & 9 deletions bleak/backends/bluezdbus/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from dbus_fast import Variant

if sys.version_info[:2] < (3, 8):
from typing_extensions import Literal, TypedDict
from typing_extensions import TypedDict
else:
from typing import Literal, TypedDict
from typing import TypedDict

from ...exc import BleakError
from ..scanner import AdvertisementData, AdvertisementDataCallback, BaseBleakScanner
Expand Down Expand Up @@ -109,8 +109,8 @@ class BleakScannerBlueZDBus(BaseBleakScanner):
Optional list of service UUIDs to filter on. Only advertisements
containing this advertising data will be received. Specifying this
also enables scanning while the screen is off on Android.
scanning_mode:
Set to ``"passive"`` to avoid the ``"active"`` scanning mode.
passive:
Use passive instead of active scanning mode.
**bluez:
Dictionary of arguments specific to the BlueZ backend.
**adapter (str):
Expand All @@ -121,14 +121,14 @@ def __init__(
self,
detection_callback: Optional[AdvertisementDataCallback],
service_uuids: Optional[List[str]],
scanning_mode: Literal["active", "passive"],
passive: bool,
*,
bluez: BlueZScannerArgs,
**kwargs,
):
super(BleakScannerBlueZDBus, self).__init__(detection_callback, service_uuids)

self._scanning_mode = scanning_mode
self._passive_mode = passive

# kwarg "device" is for backwards compatibility
self._adapter: Optional[str] = kwargs.get("adapter", kwargs.get("device"))
Expand Down Expand Up @@ -162,12 +162,12 @@ def __init__(

self._or_patterns = bluez.get("or_patterns")

if self._scanning_mode == "passive" and service_uuids:
if self._passive_mode and service_uuids:
logger.warning(
"service uuid filtering is not implemented for passive scanning, use bluez or_patterns as a workaround"
)

if self._scanning_mode == "passive" and not self._or_patterns:
if self._passive_mode and not self._or_patterns:
raise BleakError("passive scanning mode requires bluez or_patterns")

async def start(self):
Expand All @@ -180,7 +180,7 @@ async def start(self):

self.seen_devices = {}

if self._scanning_mode == "passive":
if self._passive_mode:
self._stop = await manager.passive_scan(
adapter_path,
self._or_patterns,
Expand Down
15 changes: 7 additions & 8 deletions bleak/backends/corebluetooth/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from typing import Any, Dict, List, Optional

if sys.version_info[:2] < (3, 8):
from typing_extensions import Literal, TypedDict
from typing_extensions import TypedDict
else:
from typing import Literal, TypedDict
from typing import TypedDict

import objc
from CoreBluetooth import CBPeripheral
Expand Down Expand Up @@ -52,10 +52,9 @@ class BleakScannerCoreBluetooth(BaseBleakScanner):
Optional list of service UUIDs to filter on. Only advertisements
containing this advertising data will be received. Required on
macOS >= 12.0, < 12.3 (unless you create an app with ``py2app``).
scanning_mode:
Set to ``"passive"`` to avoid the ``"active"`` scanning mode. Not
supported on macOS! Will raise :class:`BleakError` if set to
``"passive"``
passive:
Use passive instead of active scanning mode. Not supported on
macOS! Will raise :class:`BleakError` if enabled.
**timeout (float):
The scanning timeout to be used, in case of missing
``stopScan_`` method.
Expand All @@ -65,7 +64,7 @@ def __init__(
self,
detection_callback: Optional[AdvertisementDataCallback],
service_uuids: Optional[List[str]],
scanning_mode: Literal["active", "passive"],
passive: bool = False,
*,
cb: CBScannerArgs,
**kwargs
Expand All @@ -76,7 +75,7 @@ def __init__(

self._use_bdaddr = cb.get("use_bdaddr", False)

if scanning_mode == "passive":
if passive:
raise BleakError("macOS does not support passive scanning")

self._manager = CentralManagerDelegate.alloc().init()
Expand Down
13 changes: 4 additions & 9 deletions bleak/backends/p4android/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@
else:
from asyncio import timeout as async_timeout

if sys.version_info[:2] < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal

from android.broadcast import BroadcastReceiver
from android.permissions import Permission, request_permissions
from jnius import cast, java_method
Expand All @@ -39,8 +34,8 @@ class BleakScannerP4Android(BaseBleakScanner):
Optional list of service UUIDs to filter on. Only advertisements
containing this advertising data will be received. Specifying this
also enables scanning while the screen is off on Android.
scanning_mode:
Set to ``"passive"`` to avoid the ``"active"`` scanning mode.
passive:
Use passive instead of active scanning mode.
"""

__scanner = None
Expand All @@ -49,12 +44,12 @@ def __init__(
self,
detection_callback: Optional[AdvertisementDataCallback],
service_uuids: Optional[List[str]],
scanning_mode: Literal["active", "passive"],
passive: bool,
**kwargs,
):
super(BleakScannerP4Android, self).__init__(detection_callback, service_uuids)

if scanning_mode == "passive":
if passive:
self.__scan_mode = defs.ScanSettings.SCAN_MODE_OPPORTUNISTIC
else:
self.__scan_mode = defs.ScanSettings.SCAN_MODE_LOW_LATENCY
Expand Down
15 changes: 4 additions & 11 deletions bleak/backends/winrt/scanner.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import asyncio
import logging
import sys
from typing import Dict, List, NamedTuple, Optional
from uuid import UUID

Expand All @@ -12,11 +11,6 @@
BluetoothLEScanningMode,
)

if sys.version_info[:2] < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal

from ...assigned_numbers import AdvertisementDataType
from ..scanner import AdvertisementData, AdvertisementDataCallback, BaseBleakScanner

Expand Down Expand Up @@ -64,16 +58,16 @@ class BleakScannerWinRT(BaseBleakScanner):
service_uuids:
Optional list of service UUIDs to filter on. Only advertisements
containing this advertising data will be received.
scanning_mode:
Set to ``"passive"`` to avoid the ``"active"`` scanning mode.
passive:
Use passive instead of active scanning mode.
"""

def __init__(
self,
detection_callback: Optional[AdvertisementDataCallback],
service_uuids: Optional[List[str]],
scanning_mode: Literal["active", "passive"],
passive: bool,
**kwargs,
):
super(BleakScannerWinRT, self).__init__(detection_callback, service_uuids)
Expand All @@ -82,8 +76,7 @@ def __init__(
self._advertisement_pairs: Dict[int, _RawAdvData] = {}
self._stopped_event = None

# case insensitivity is for backwards compatibility on Windows only
if scanning_mode.lower() == "passive":
if passive:
self._scanning_mode = BluetoothLEScanningMode.PASSIVE
else:
self._scanning_mode = BluetoothLEScanningMode.ACTIVE
Expand Down

0 comments on commit d655ddd

Please sign in to comment.