Skip to content

Commit

Permalink
feat: optimize gap parser (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Jun 15, 2023
1 parent 46e68f4 commit 7df2658
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 20 deletions.
6 changes: 6 additions & 0 deletions src/bluetooth_data_tools/gap.pxd
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import cython


cdef str BLE_UUID

cdef object from_bytes

cdef class BLEGAPAdvertisement:

cdef public object local_name
Expand All @@ -27,3 +31,5 @@ cdef cython.uint TYPE_TX_POWER_LEVEL
gap_type_num=cython.uint
)
cpdef parse_advertisement_data(object data)

cdef _decode_advertisement_data(cython.bytes encoded_struct)
71 changes: 51 additions & 20 deletions src/bluetooth_data_tools/gap.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""GATT Advertisement and Scan Response Data (GAP)."""
import logging
from enum import IntEnum
from functools import lru_cache
from typing import Dict, Iterable, List, Tuple
from uuid import UUID

BLE_UUID = "0000-1000-8000-00805f9b34fb"
_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -77,13 +77,16 @@ class BLEGAPType(IntEnum):

_bytes = bytes

from_bytes = int.from_bytes


def _decode_advertisement_data(
encoded_struct: _bytes,
) -> Iterable[Tuple[int, bytes]]:
) -> list[Tuple[int, bytes]]:
"""Decode a BLE GAP AD structure."""
offset = 0
total_length = len(encoded_struct)
msgs: list[Tuple[int, bytes]] = []
while offset < total_length:
try:
length = encoded_struct[offset]
Expand All @@ -92,10 +95,10 @@ def _decode_advertisement_data(
# Maybe zero padding
offset += 1
continue
return
break
type_ = encoded_struct[offset + 1]
if not type_:
return
break
start = offset + 2
end = start + length - 1
value = encoded_struct[start:end]
Expand All @@ -106,11 +109,13 @@ def _decode_advertisement_data(
encoded_struct,
ex,
)
return
break

yield type_, value
msgs.append((type_, value))
offset += 1 + length

return msgs


TYPE_SHORT_LOCAL_NAME = BLEGAPType.TYPE_SHORT_LOCAL_NAME.value
TYPE_COMPLETE_LOCAL_NAME = BLEGAPType.TYPE_COMPLETE_LOCAL_NAME.value
Expand All @@ -128,6 +133,36 @@ def _decode_advertisement_data(
TYPE_SERVICE_DATA_128BIT_UUID = BLEGAPType.TYPE_SERVICE_DATA_128BIT_UUID.value
TYPE_TX_POWER_LEVEL = BLEGAPType.TYPE_TX_POWER_LEVEL.value

bytes_ = bytes


@lru_cache(maxsize=256)
def _uint64_bytes_as_uuid(uint64_bytes: bytes_) -> str:
"""Convert an integer to a UUID str."""
int_value = from_bytes(uint64_bytes, "little")
hex = "%032x" % int_value
return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:]}"


@lru_cache(maxsize=256)
def _uint16_bytes_as_uuid(uuid16_bytes: bytes_) -> str:
"""Convert a 16-bit UUID to a UUID str."""
uuid_int = from_bytes(uuid16_bytes, "little")
return f"0000{uuid_int:04x}-{BLE_UUID}"


@lru_cache(maxsize=256)
def _uint32_bytes_as_uuid(uuid32_bytes: bytes_) -> str:
"""Convert a 32-bit UUID to a UUID str."""
uuid_int = from_bytes(uuid32_bytes, "little")
return f"{uuid_int:08x}-{BLE_UUID}"


@lru_cache(maxsize=256)
def _manufacturer_id_bytes_to_int(manufacturer_id_bytes: bytes_) -> int:
"""Convert manufacturer ID bytes to an int."""
return from_bytes(manufacturer_id_bytes, "little")


def parse_advertisement_data(
data: Iterable[bytes],
Expand All @@ -142,33 +177,29 @@ def parse_advertisement_data(
for gap_data in data:
for gap_type_num, gap_value in _decode_advertisement_data(gap_data):
if gap_type_num == TYPE_SHORT_LOCAL_NAME and not local_name:
local_name = gap_value.decode("utf-8", errors="replace")
local_name = gap_value.decode("utf-8", "replace")
elif gap_type_num == TYPE_COMPLETE_LOCAL_NAME:
local_name = gap_value.decode("utf-8", errors="replace")
local_name = gap_value.decode("utf-8", "replace")
elif gap_type_num == TYPE_MANUFACTURER_SPECIFIC_DATA:
manufacturer_id = int.from_bytes(gap_value[:2], "little")
manufacturer_data[manufacturer_id] = gap_value[2:]
manufacturer_data[
_manufacturer_id_bytes_to_int(gap_value[:2])
] = gap_value[2:]
elif gap_type_num in {
TYPE_16BIT_SERVICE_UUID_COMPLETE,
TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE,
}:
uuid_int = int.from_bytes(gap_value[:2], "little")
service_uuids.append(f"0000{uuid_int:04x}-{BLE_UUID}")
service_uuids.append(_uint16_bytes_as_uuid(gap_value[:2]))
elif gap_type_num in {
TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE,
TYPE_128BIT_SERVICE_UUID_COMPLETE,
}:
uuid_str = str(UUID(int=int.from_bytes(gap_value[:16], "little")))
service_uuids.append(uuid_str)
service_uuids.append(_uint64_bytes_as_uuid(gap_value[:16]))
elif gap_type_num == TYPE_SERVICE_DATA:
uuid_int = int.from_bytes(gap_value[:2], "little")
service_data[f"0000{uuid_int:04x}-{BLE_UUID}"] = gap_value[2:]
service_data[_uint16_bytes_as_uuid(gap_value[:2])] = gap_value[2:]
elif gap_type_num == TYPE_SERVICE_DATA_32BIT_UUID:
uuid_int = int.from_bytes(gap_value[:4], "little")
service_data[f"{uuid_int:08x}-{BLE_UUID}"] = gap_value[4:]
service_data[_uint32_bytes_as_uuid(gap_value[:4])] = gap_value[4:]
elif gap_type_num == TYPE_SERVICE_DATA_128BIT_UUID:
uuid_str = str(UUID(int=int.from_bytes(gap_value[:16], "little")))
service_data[uuid_str] = gap_value[16:]
service_data[_uint64_bytes_as_uuid(gap_value[:16])] = gap_value[16:]
elif gap_type_num == TYPE_TX_POWER_LEVEL:
tx_power = int.from_bytes(gap_value, "little", signed=True)

Expand Down

0 comments on commit 7df2658

Please sign in to comment.