Skip to content

Commit

Permalink
feat: switch to using aiooui for mac lookups (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Feb 24, 2024
1 parent ef99662 commit 3623907
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 23 deletions.
13 changes: 12 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ sphinx-rtd-theme = {version = "^1.0", optional = true}
myst-parser = {version = "^0.18", optional = true}
home-assistant-bluetooth = ">=1.3.0"
mac-vendor-lookup = ">=0.1.11"
aiohttp = ">=3.6.0"
aiooui = ">=0.1.1"

[tool.poetry.extras]
docs = [
Expand Down
25 changes: 4 additions & 21 deletions src/ibeacon_ble/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
from __future__ import annotations

import asyncio
import contextlib
import struct
from dataclasses import dataclass
from typing import cast
from uuid import UUID

import aiohttp
import aiooui
from home_assistant_bluetooth import BluetoothServiceInfo
from mac_vendor_lookup import AsyncMacLookup

UNPACK_IBEACON = struct.Struct(">HHb").unpack

Expand Down Expand Up @@ -83,23 +80,9 @@ def is_ibeacon_service_info(service_info: BluetoothServiceInfo) -> bool:
class iBeaconParser:
"""Parse iBeacon BLE advertisements."""

def __init__(self) -> None:
"""Initialize the parser."""
self._mac_vendor_lookup: AsyncMacLookup | None = None

async def async_setup(self) -> None:
self._mac_vendor_lookup = AsyncMacLookup()
with contextlib.suppress(asyncio.TimeoutError, aiohttp.ClientError):
# We don't care if this fails since it only
# improves the data we get.
await self._mac_vendor_lookup.load_vendors()

def _async_get_vendor(self, mac_address: str) -> str | None:
"""Lookup the vendor."""
assert self._mac_vendor_lookup is not None # nosec
oui = self._mac_vendor_lookup.sanitise(mac_address)[:6]
vendor: bytes | None = self._mac_vendor_lookup.prefixes.get(oui.encode())
return vendor.decode()[:254] if vendor is not None else None
if not aiooui.is_loaded():
await aiooui.async_load()

def parse(self, service_info: BluetoothServiceInfo) -> iBeaconAdvertisement | None:
if not is_ibeacon_service_info(service_info):
Expand Down Expand Up @@ -132,7 +115,7 @@ def parse(self, service_info: BluetoothServiceInfo) -> iBeaconAdvertisement | No

vendor = None
if ":" in service_info.address:
vendor = self._async_get_vendor(service_info.address)
vendor = aiooui.get_vendor(service_info.address)

return iBeaconAdvertisement(
name=service_info.name,
Expand Down

0 comments on commit 3623907

Please sign in to comment.