Skip to content

Commit

Permalink
Corrections based on code review
Browse files Browse the repository at this point in the history
  • Loading branch information
hbldh committed Feb 25, 2021
1 parent fd06dfe commit 843e0e2
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 20 deletions.
5 changes: 2 additions & 3 deletions bleak/backends/bluezdbus/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from bleak.backends.bluezdbus import defs

_mac_address_regex = re.compile("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$")
_service_handle_regex = re.compile("service([0-9A-Fa-f]*)")


def validate_mac_address(address):
Expand Down Expand Up @@ -52,6 +51,6 @@ def format_GATT_object(object_path, interfaces):

def extract_service_handle_from_path(path):
try:
return int(_service_handle_regex.search(path).groups()[-1], 16)
return int(path[-4:], 16)
except Exception as e:
raise BleakError(f"Could not parse service handle from path: {path} ({e})")
raise BleakError(f"Could not parse service handle from path: {path}") from e
2 changes: 2 additions & 0 deletions bleak/backends/corebluetooth/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ class BleakGATTServiceCoreBluetooth(BleakGATTService):
def __init__(self, obj: CBService):
super().__init__(obj)
self.__characteristics = []
# N.B. the `startHandle` method of the CBService is an undocumented Core Bluetooth feature,
# which Bleak takes advantage of in order to have a service handle to use.
self.__handle = int(self.obj.startHandle())

@property
Expand Down
16 changes: 9 additions & 7 deletions bleak/backends/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""
import abc
from uuid import UUID
from typing import List, Union, Iterator
from typing import Dict, List, Union, Iterator

from bleak import BleakError
from bleak.uuids import uuidstr_to_str
Expand Down Expand Up @@ -85,28 +85,30 @@ def __init__(self):

def __getitem__(
self, item: Union[str, int, UUID]
) -> Union[BleakGATTService, BleakGATTCharacteristic, BleakGATTDescriptor]:
) -> Union[BleakGATTService, BleakGATTCharacteristic, BleakGATTDescriptor, None]:
"""Get a service, characteristic or descriptor from uuid or handle"""
return self.services.get(
str(item), self.characteristics.get(item, self.descriptors.get(item, None))
return (
self.get_service(item)
or self.get_characteristic(item)
or self.get_descriptor(item)
)

def __iter__(self) -> Iterator[BleakGATTService]:
"""Returns an iterator over all BleakGATTService objects"""
return iter(self.services.values())

@property
def services(self) -> dict:
def services(self) -> Dict[int, BleakGATTService]:
"""Returns dictionary of handles mapping to BleakGATTService"""
return self.__services

@property
def characteristics(self) -> dict:
def characteristics(self) -> Dict[int, BleakGATTCharacteristic]:
"""Returns dictionary of handles mapping to BleakGATTCharacteristic"""
return self.__characteristics

@property
def descriptors(self) -> dict:
def descriptors(self) -> Dict[int, BleakGATTDescriptor]:
"""Returns a dictionary of integer handles mapping to BleakGATTDescriptor"""
return self.__descriptors

Expand Down
27 changes: 17 additions & 10 deletions examples/service_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,36 +26,43 @@ async def run(address, debug=False):
log.addHandler(h)

async with BleakClient(address) as client:
x = await client.is_connected()
log.info("Connected: {0}".format(x))
is_connected = await client.is_connected()
log.info(f"Connected: {is_connected}")

for service in client.services:
log.info(f"[Service] {service}")
for char in service.characteristics:
if "read" in char.properties:
try:
value = bytes(await client.read_gatt_char(char.uuid))
log.info(
f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}"
)
except Exception as e:
value = str(e).encode()
log.error(
f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}"
)

else:
value = None
log.info(
f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}"
)
log.info(
f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}"
)

for descriptor in char.descriptors:
try:
value = bytes(
await client.read_gatt_descriptor(descriptor.handle)
)
log.info(
f"\t\t[Descriptor] {descriptor}) | Value: {value}"
)
except Exception as e:
value = str(e).encode()
log.info(
f"\t\t[Descriptor] {descriptor}) | Value: {value} ".format(
descriptor.uuid,
descriptor.handle,
log.error(
f"\t\t[Descriptor] {descriptor}) | Value: {value}"
)
)


if __name__ == "__main__":
Expand Down

0 comments on commit 843e0e2

Please sign in to comment.