Skip to content

Commit

Permalink
Merge pull request #324 from hbldh/cleanups
Browse files Browse the repository at this point in the history
Cleanups
  • Loading branch information
dlech committed Oct 23, 2020
2 parents 9bf0c4f + b692791 commit d7e9558
Show file tree
Hide file tree
Showing 21 changed files with 59 additions and 117 deletions.
14 changes: 14 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ All notable changes to this project will be documented in this file.
The format is based on `Keep a Changelog <https://keepachangelog.com/en/1.0.0/>`_,
and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_.

`Unreleased`_
--------------

Fixed
-----

* Fixed use of bare exceptions.

Removed
~~~~~~~

* Removed duplicate definition of BLEDevice in BlueZ backend.
* Removed unused imports.


`0.9.1`_ (2020-10-22)
---------------------
Expand Down
12 changes: 6 additions & 6 deletions bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,23 @@
from bleak.backends.bluezdbus.discovery import discover # noqa
from bleak.backends.bluezdbus.scanner import (
BleakScannerBlueZDBus as BleakScanner,
) # noqa
) # noqa: F401
from bleak.backends.bluezdbus.client import (
BleakClientBlueZDBus as BleakClient,
) # noqa
) # noqa: F401
elif platform.system() == "Darwin":
try:
from CoreBluetooth import CBPeripheral
from CoreBluetooth import CBPeripheral # noqa: F401
except Exception as ex:
raise BleakError("Bleak requires the CoreBluetooth Framework") from ex

from bleak.backends.corebluetooth.discovery import discover # noqa
from bleak.backends.corebluetooth.discovery import discover # noqa: F401
from bleak.backends.corebluetooth.scanner import (
BleakScannerCoreBluetooth as BleakScanner,
) # noqa
) # noqa: F401
from bleak.backends.corebluetooth.client import (
BleakClientCoreBluetooth as BleakClient,
) # noqa
) # noqa: F401

elif platform.system() == "Windows":
# Requires Windows 10 Creators update at least, i.e. Window 10.0.16299
Expand Down
11 changes: 3 additions & 8 deletions bleak/backends/bluezdbus/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,18 @@
import subprocess
import uuid
import warnings
from asyncio import Future
from functools import wraps, partial
from typing import Callable, Any, Union
from typing import Callable, Union

from twisted.internet.error import ConnectionDone

from bleak.backends.device import BLEDevice
from bleak.backends.service import BleakGATTServiceCollection
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.exc import BleakError
from bleak.backends.client import BaseBleakClient
from bleak.backends.bluezdbus import defs, signals, utils, get_reactor
from bleak.backends.bluezdbus.scanner import BleakScannerBlueZDBus
from bleak.backends.bluezdbus.utils import get_device_object_path, get_managed_objects
from bleak.backends.bluezdbus.utils import get_managed_objects
from bleak.backends.bluezdbus.service import BleakGATTServiceBlueZDBus
from bleak.backends.bluezdbus.characteristic import BleakGATTCharacteristicBlueZDBus
from bleak.backends.bluezdbus.descriptor import BleakGATTDescriptorBlueZDBus
Expand Down Expand Up @@ -300,7 +298,7 @@ async def pair(self, *args, **kwargs) -> bool:
interface=defs.DEVICE_INTERFACE,
destination=defs.BLUEZ_SERVICE,
).asFuture(loop)
except RemoteError as e:
except RemoteError:
await self._cleanup_all()
raise BleakError(
"Device with address {0} could not be paired with.".format(self.address)
Expand Down Expand Up @@ -356,9 +354,6 @@ async def is_connected(self) -> bool:
except RemoteError as e:
if e.errName != "org.freedesktop.DBus.Error.UnknownObject":
raise
except Exception as e:
# Do not want to silence unknown errors. Send this upwards.
raise
return is_connected

# GATT services methods
Expand Down
3 changes: 1 addition & 2 deletions bleak/backends/bluezdbus/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ def _device_info(path, props):
address = None
rssi = props.get("RSSI", "?")
return name, address, rssi, path
except Exception as e:
# logger.exception(e, exc_info=True)
except Exception:
return None, None, None, None


Expand Down
5 changes: 2 additions & 3 deletions bleak/backends/bluezdbus/scanner.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import asyncio
import pathlib
from typing import Callable, Any, Union, List
from typing import Callable, List

from bleak.backends.scanner import BaseBleakScanner
from bleak.backends.device import BLEDevice
Expand Down Expand Up @@ -48,8 +48,7 @@ def _device_info(path, props):
address = None
rssi = props.get("RSSI", "?")
return name, address, rssi, path
except Exception as e:
# logger.exception(e, exc_info=True)
except Exception:
return None, None, None, None


Expand Down
3 changes: 1 addition & 2 deletions bleak/backends/bluezdbus/service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from uuid import UUID
from typing import Union, List
from typing import List

from bleak.backends.service import BleakGATTService
from bleak.backends.bluezdbus.characteristic import BleakGATTCharacteristicBlueZDBus
Expand Down
3 changes: 1 addition & 2 deletions bleak/backends/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
"""
import abc
import asyncio
import uuid
from typing import Callable, Any, Union
from typing import Callable, Union

from bleak.backends.service import BleakGATTServiceCollection
from bleak.backends.characteristic import BleakGATTCharacteristic
Expand Down
2 changes: 1 addition & 1 deletion bleak/backends/corebluetooth/CentralManagerDelegate.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
try:
_mac_version = list(map(int, platform.mac_ver()[0].split(".")))
_IS_PRE_10_13 = _mac_version[0] == 10 and _mac_version[1] < 13
except: # noqa For building docs
except Exception:
_mac_version = ""
_IS_PRE_10_13 = False

Expand Down
5 changes: 1 addition & 4 deletions bleak/backends/corebluetooth/PeripheralDelegate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@
NSData,
NSError,
)
from CoreBluetooth import (
CBCharacteristicWriteWithResponse,
CBCharacteristicWriteWithoutResponse,
)
from CoreBluetooth import CBCharacteristicWriteWithResponse

from bleak.exc import BleakError

Expand Down
4 changes: 2 additions & 2 deletions bleak/backends/corebluetooth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@

import logging
import uuid
from typing import Callable, Any, Union
from typing import Callable, Union
import asyncio

from Foundation import NSData, CBUUID
from Foundation import NSData
from CoreBluetooth import (
CBCharacteristicWriteWithResponse,
CBCharacteristicWriteWithoutResponse,
Expand Down
52 changes: 1 addition & 51 deletions bleak/backends/corebluetooth/device.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
from bleak.backends._manufacturers import MANUFACTURERS

from Foundation import NSDictionary

Expand Down Expand Up @@ -48,7 +47,7 @@ def _update_uuids(self, advertisementData: NSDictionary):
chuuids = [cb_uuid_to_str(u) for u in cbuuids]
if "uuids" in self.metadata:
for uuid in chuuids:
if not uuid in self.metadata["uuids"]:
if uuid not in self.metadata["uuids"]:
self.metadata["uuids"].append(uuid)
else:
self.metadata["uuids"] = chuuids
Expand All @@ -65,52 +64,3 @@ def _update_manufacturer(self, advertisementData: NSDictionary):
@property
def rssi(self):
return self._rssi


class BLEDevice(object):
"""A simple wrapper class representing a BLE server detected during
a `discover` call.
- When using Windows backend, `details` attribute is a
`Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement` object, unless
it is created with the Windows.Devices.Enumeration discovery method, then is is a
`Windows.Devices.Enumeration.DeviceInformation`
- When using Linux backend, `details` attribute is a
dict with keys `path` which has the string path to the DBus device object and `props`
which houses the properties dictionary of the D-Bus Device.
- When using macOS backend, `details` attribute will be a CBPeripheral object
"""

def __init__(self, address, name, details=None, **kwargs):
self.address = address
self.name = name if name else "Unknown"
self.details = details
self.metadata = kwargs

@property
def rssi(self):
"""Get the signal strength in dBm"""
if isinstance(self.details, dict) and "props" in self.details:
rssi = self.details["props"].get("RSSI", 0) # Should not be set to 0...
elif hasattr(self.details, "RawSignalStrengthInDBm"):
rssi = self.details.RawSignalStrengthInDBm
elif hasattr(self.details, "Properties"):
rssi = {p.Key: p.Value for p in self.details.Properties}[
"System.Devices.Aep.SignalStrength"
]
else:
rssi = None
return int(rssi) if rssi is not None else None

def __str__(self):
if self.name == "Unknown":
if "manufacturer_data" in self.metadata:
ks = list(self.metadata["manufacturer_data"].keys())
if len(ks):
mf = MANUFACTURERS.get(ks[0], MANUFACTURERS.get(0xFFFF))
value = self.metadata["manufacturer_data"].get(
ks[0], MANUFACTURERS.get(0xFFFF)
)
# TODO: Evaluate how to interpret the value of the company identifier...
return "{0}: {1} ({2})".format(self.address, mf, value)
return "{0}: {1}".format(self.address, self.name)
5 changes: 2 additions & 3 deletions bleak/backends/corebluetooth/scanner.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import logging
import asyncio
import pathlib
import uuid
from typing import Callable, Any, Union, List
from typing import Callable, Union, List

from bleak.backends.corebluetooth.CentralManagerDelegate import CentralManagerDelegate
from bleak.backends.corebluetooth.utils import cb_uuid_to_str
Expand Down Expand Up @@ -160,5 +159,5 @@ def is_scanning(self):
# TODO: Evaluate if newer macOS than 10.11 has isScanning.
try:
return self._manager.isScanning_
except:
except Exception:
return None
4 changes: 2 additions & 2 deletions bleak/backends/corebluetooth/service.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from bleak.backends.corebluetooth.utils import cb_uuid_to_str
from typing import List, Union
from typing import List

from Foundation import CBService, CBUUID
from Foundation import CBService

from bleak.backends.corebluetooth.characteristic import (
BleakGATTCharacteristicCoreBluetooth,
Expand Down
12 changes: 3 additions & 9 deletions bleak/backends/dotnet/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,12 @@
from System import UInt64, Object
from System.Runtime.InteropServices.WindowsRuntime import EventRegistrationToken
from Windows.Foundation import IAsyncOperation, TypedEventHandler
from Windows.Storage.Streams import DataReader, DataWriter, IBuffer
from Windows.Devices.Enumeration import (
DevicePairingResult,
DevicePairingResultStatus,
DeviceUnpairingResult,
DeviceUnpairingResultStatus,
DevicePairingKinds,
DevicePairingProtectionLevel,
DeviceInformationCustomPairing,
DevicePairingRequestedEventArgs,
)
from Windows.Devices.Bluetooth import (
BluetoothLEDevice,
Expand All @@ -54,11 +50,9 @@
BluetoothAddressType,
)
from Windows.Devices.Bluetooth.GenericAttributeProfile import (
GattDeviceService,
GattDeviceServicesResult,
GattCharacteristic,
GattCharacteristicsResult,
GattDescriptor,
GattDescriptorsResult,
GattCommunicationStatus,
GattReadResult,
Expand Down Expand Up @@ -340,7 +334,7 @@ def handler(sender, args):

try:
custom_pairing.PairingRequested -= handler
except Exception as e:
except Exception:
# TODO: Find a way to remove WinRT events...
pass
finally:
Expand Down Expand Up @@ -524,7 +518,7 @@ async def read_gatt_char(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
use_cached=False,
**kwargs
**kwargs,
) -> bytearray:
"""Perform read operation on the specified GATT characteristic.
Expand Down Expand Up @@ -749,7 +743,7 @@ async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
**kwargs
**kwargs,
) -> None:
"""Activate notifications/indications on a characteristic.
Expand Down
2 changes: 1 addition & 1 deletion bleak/backends/dotnet/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# Import of Bleak CLR->UWP Bridge. It is not needed here, but it enables loading of Windows.Devices
from BleakBridge import Bridge # noqa: F401

from System import Array, Byte, Object
from System import Array, Object
from Windows.Devices import Enumeration
from Windows.Devices.Bluetooth.Advertisement import (
BluetoothLEAdvertisementWatcher,
Expand Down
5 changes: 1 addition & 4 deletions bleak/backends/dotnet/scanner.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import logging
import asyncio
import pathlib
import uuid
from functools import wraps
from typing import Callable, Any, Union, List
from typing import Callable, Union, List

from bleak.backends.device import BLEDevice
from bleak.backends.dotnet.utils import BleakDataReader
from bleak.exc import BleakError, BleakDotNetTaskError
from bleak.backends.scanner import BaseBleakScanner

# Import of Bleak CLR->UWP Bridge. It is not needed here, but it enables loading of Windows.Devices
Expand Down
3 changes: 1 addition & 2 deletions bleak/backends/dotnet/service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from uuid import UUID
from typing import List, Union
from typing import List

from bleak.backends.service import BleakGATTService
from bleak.backends.dotnet.characteristic import BleakGATTCharacteristicDotNet
Expand Down
7 changes: 4 additions & 3 deletions bleak/backends/dotnet/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,12 @@ async def wrap_Task(task):
return task.Result


async def wrap_IAsyncOperation(op, return_type):
async def wrap_IAsyncOperation(op: IAsyncOperation, return_type):
"""Enables await on .NET Task using asyncio.Event and a lambda callback.
Args:
task (System.Threading.Tasks.Task): .NET async task object to await.
op (Windows.Foundation.IAsyncOperation[TResult]): .NET async operation object to await.
result_type (TResult): The .NET type of the result of the async operation.
Returns:
The results of the the .NET Task.
Expand Down Expand Up @@ -117,7 +118,7 @@ def detach_buffer(self):
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self.writer.Dispose()
except:
except Exception:
pass
del self.writer
self.writer = None
Loading

0 comments on commit d7e9558

Please sign in to comment.