Skip to content

Commit

Permalink
Ran black on code.
Browse files Browse the repository at this point in the history
  • Loading branch information
hbldh committed Aug 1, 2019
1 parent d8d15e4 commit 5072ab6
Show file tree
Hide file tree
Showing 17 changed files with 380 additions and 178 deletions.
8 changes: 5 additions & 3 deletions bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""Top-level package for bleak."""

__author__ = """Henrik Blidh"""
__email__ = "henrik.blidh@nedomkull.com"
__email__ = "henrik.blidh@gmail.com"

import re
import os
Expand Down Expand Up @@ -48,13 +48,15 @@
BleakClientBlueZDBus as BleakClient
) # noqa
elif platform.system() == "Darwin":
# TODO: Check if macOS version has Core Bluetooth, raise error otherwise.
from Foundation import NSClassFromString

if NSClassFromString("CBPeripheral") is None:
raise BleakError("Bleak requires the CoreBluetooth Framework")

from bleak.backends.corebluetooth.discovery import discover
from bleak.backends.corebluetooth.client import BleakClientCoreBluetooth as BleakClient
from bleak.backends.corebluetooth.client import (
BleakClientCoreBluetooth as BleakClient
)

elif platform.system() == "Windows":
# Requires Windows 10 Creators update at least, i.e. Window 10.0.16299
Expand Down
66 changes: 40 additions & 26 deletions bleak/backends/bluezdbus/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(self, address, loop=None, **kwargs):
# Connectivity methods

def set_disconnected_callback(
self, callback: Callable[[BaseBleakClient], None], **kwargs
self, callback: Callable[[BaseBleakClient], None], **kwargs
) -> None:
"""Set the disconnected callback.
The callback will be called on DBus PropChanged event with
Expand All @@ -81,7 +81,9 @@ async def connect(self, **kwargs) -> bool:

# A Discover must have been run before connecting to any devices. Do a quick one here
# to ensure that it has been done.
await discover(timeout=kwargs.get('timeout', 0.1), device=self.device, loop=self.loop)
await discover(
timeout=kwargs.get("timeout", 0.1), device=self.device, loop=self.loop
)

# Create system bus
self._bus = await txdbus_connect(reactor, busAddress="system").asFuture(
Expand Down Expand Up @@ -141,7 +143,8 @@ async def _cleanup(self) -> None:
await self._bus.delMatch(rule_id).asFuture(self.loop)

await asyncio.gather(
*(self.stop_notify(_uuid) for _uuid in self._subscriptions))
*(self.stop_notify(_uuid) for _uuid in self._subscriptions)
)

async def disconnect(self) -> bool:
"""Disconnect from the specified GATT server.
Expand Down Expand Up @@ -225,13 +228,9 @@ async def get_services(self) -> BleakGATTServiceCollection:
_descs.append([desc, object_path])

for char, object_path in _chars:
_service = list(
filter(lambda x: x.path == char["Service"], self.services)
)
_service = list(filter(lambda x: x.path == char["Service"], self.services))
self.services.add_characteristic(
BleakGATTCharacteristicBlueZDBus(
char, object_path, _service[0].uuid
)
BleakGATTCharacteristicBlueZDBus(char, object_path, _service[0].uuid)
)
self._char_path_to_uuid[object_path] = char.get("UUID")

Expand All @@ -243,9 +242,7 @@ async def get_services(self) -> BleakGATTServiceCollection:
)
)
self.services.add_descriptor(
BleakGATTDescriptorBlueZDBus(
desc, object_path, _characteristic[0].uuid
)
BleakGATTDescriptorBlueZDBus(desc, object_path, _characteristic[0].uuid)
)

self._services_resolved = True
Expand Down Expand Up @@ -349,14 +346,26 @@ async def write_gatt_char(
"""
characteristic = self.services.get_characteristic(str(_uuid))

if ("write" not in characteristic.properties and "write-without-response" not in characteristic.properties):
raise BleakError("Characteristic %s does not support write operations!" % str(_uuid))
if (
"write" not in characteristic.properties
and "write-without-response" not in characteristic.properties
):
raise BleakError(
"Characteristic %s does not support write operations!" % str(_uuid)
)
if not response and "write-without-response" not in characteristic.properties:
response = True
# Force response here, since the device only supports that.
if response and "write" not in characteristic.properties and "write-without-response" in characteristic.properties:
if (
response
and "write" not in characteristic.properties
and "write-without-response" in characteristic.properties
):
response = False
logger.warning("Characteristic %s does not support Write with response. Trying without..." % str(_uuid))
logger.warning(
"Characteristic %s does not support Write with response. Trying without..."
% str(_uuid)
)

if response or (self._bluez_version[0] == 5 and self._bluez_version[1] > 50):
# TODO: Add OnValueUpdated handler for response=True?
Expand Down Expand Up @@ -551,10 +560,11 @@ def _properties_changed_callback(self, message):
"""

logger.debug('DBUS: path: {}, domain: {}, body: {}'
.format(message.path,
message.body[0],
message.body[1]))
logger.debug(
"DBUS: path: {}, domain: {}, body: {}".format(
message.path, message.body[0], message.body[1]
)
)

if message.body[0] == defs.GATT_CHARACTERISTIC_INTERFACE:
if message.path in self._notification_callbacks:
Expand All @@ -567,20 +577,24 @@ def _properties_changed_callback(self, message):
message.path, message.body[1]
)
elif message.body[0] == defs.DEVICE_INTERFACE:
device_path = '/org/bluez/%s/dev_%s' % (self.device,
self.address.replace(':', '_'))
device_path = "/org/bluez/%s/dev_%s" % (
self.device,
self.address.replace(":", "_"),
)
if message.path == device_path:
message_body_map = message.body[1]
if 'Connected' in message_body_map and \
not message_body_map['Connected']:
logger.debug("Device {} disconnected."
.format(self.address))
if (
"Connected" in message_body_map
and not message_body_map["Connected"]
):
logger.debug("Device {} disconnected.".format(self.address))

self.loop.create_task(self._cleanup())

if self._disconnected_callback is not None:
self._disconnected_callback(self)


def _data_notification_wrapper(func, char_map):
@wraps(func)
def args_parser(sender, data):
Expand Down
60 changes: 39 additions & 21 deletions bleak/backends/bluezdbus/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ def parse_msg(message):
devices[msg_path] = (
{**devices[msg_path], **changed} if msg_path in devices else changed
)
elif message.member == "InterfacesRemoved" and message.body[1][0] == defs.BATTERY_INTERFACE:
elif (
message.member == "InterfacesRemoved"
and message.body[1][0] == defs.BATTERY_INTERFACE
):
logger.info(
"{0}, {1} ({2}): {3}".format(
message.member, message.interface, message.path, message.body
Expand All @@ -125,21 +128,27 @@ def parse_msg(message):
bus = await client.connect(reactor, "system").asFuture(loop)

# Add signal listeners
rules.append(await bus.addMatch(
parse_msg,
interface="org.freedesktop.DBus.ObjectManager",
member="InterfacesAdded",
).asFuture(loop))
rules.append(await bus.addMatch(
parse_msg,
interface="org.freedesktop.DBus.ObjectManager",
member="InterfacesRemoved",
).asFuture(loop))
rules.append(await bus.addMatch(
parse_msg,
interface="org.freedesktop.DBus.Properties",
member="PropertiesChanged",
).asFuture(loop))
rules.append(
await bus.addMatch(
parse_msg,
interface="org.freedesktop.DBus.ObjectManager",
member="InterfacesAdded",
).asFuture(loop)
)
rules.append(
await bus.addMatch(
parse_msg,
interface="org.freedesktop.DBus.ObjectManager",
member="InterfacesRemoved",
).asFuture(loop)
)
rules.append(
await bus.addMatch(
parse_msg,
interface="org.freedesktop.DBus.Properties",
member="PropertiesChanged",
).asFuture(loop)
)

# Find the HCI device to use for scanning and get cached device properties
objects = await bus.callRemote(
Expand All @@ -162,7 +171,7 @@ def parse_msg(message):
interface="org.bluez.Adapter1",
destination="org.bluez",
signature="a{sv}",
body=[{"Transport": "le"}]
body=[{"Transport": "le"}],
).asFuture(loop)
await bus.callRemote(
adapter_path,
Expand Down Expand Up @@ -193,13 +202,22 @@ def parse_msg(message):
discovered_devices = []
for path, props in devices.items():
if not props:
logger.debug("Disregarding %s since no properties could be obtained." % path)
logger.debug(
"Disregarding %s since no properties could be obtained." % path
)
continue
name, address, _, path = _device_info(path, props)
uuids = props.get("UUIDs", [])
manufacturer_data = props.get('ManufacturerData', {})
discovered_devices.append(BLEDevice(address, name, {"path": path, "props": props}, uuids=uuids,
manufacturer_data=manufacturer_data))
manufacturer_data = props.get("ManufacturerData", {})
discovered_devices.append(
BLEDevice(
address,
name,
{"path": path, "props": props},
uuids=uuids,
manufacturer_data=manufacturer_data,
)
)

for rule in rules:
await bus.delMatch(rule).asFuture(loop)
Expand Down
2 changes: 1 addition & 1 deletion bleak/backends/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):

@abc.abstractmethod
async def set_disconnected_callback(
self, callback: Callable[['BaseBleakClient'], None], **kwargs
self, callback: Callable[["BaseBleakClient"], None], **kwargs
) -> None:
"""Set the disconnect callback.
The callback will only be called on unsolicited disconnect event.
Expand Down
Loading

0 comments on commit 5072ab6

Please sign in to comment.