Skip to content

Commit

Permalink
feat: use a single function to normalize mac addresses (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Jun 11, 2024
1 parent 0b1cc0f commit 7ce8654
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/uiprotect/data/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from pydantic import PrivateAttr, ValidationError # type: ignore[assignment]

from ..exceptions import ClientError
from ..utils import utc_now
from ..utils import normalize_mac, utc_now
from .base import (
RECENT_EVENT_MAX,
ProtectBaseObject,
Expand Down Expand Up @@ -226,7 +226,7 @@ def unifi_dict_to_dict(cls, data: dict[str, Any]) -> dict[str, Any]:
items[item["id"]] = item
data["idLookup"][item["id"]] = ref
if "mac" in item:
cleaned_mac = item["mac"].lower().replace(":", "")
cleaned_mac = normalize_mac(item["mac"])
data["macLookup"][cleaned_mac] = ref
data[key] = items

Expand Down Expand Up @@ -312,8 +312,7 @@ def has_media(self) -> bool:

def get_device_from_mac(self, mac: str) -> ProtectAdoptableDeviceModel | None:
"""Retrieve a device from MAC address."""
mac = mac.lower().replace(":", "").replace("-", "").replace("_", "")
ref = self.mac_lookup.get(mac)
ref = self.mac_lookup.get(normalize_mac(mac))
if ref is None:
return None

Expand Down Expand Up @@ -387,7 +386,7 @@ def _process_add_packet(
getattr(self, key)[obj.id] = obj
ref = ProtectDeviceRef(model=obj.model, id=obj.id)
self.id_lookup[obj.id] = ref
self.mac_lookup[obj.mac.lower().replace(":", "")] = ref
self.mac_lookup[normalize_mac(obj.mac)] = ref
else:
_LOGGER.debug("Unexpected bootstrap model type for add: %s", obj.model)
return None
Expand Down Expand Up @@ -419,7 +418,7 @@ def _process_remove_packet(
device = devices.pop(device_id, None)
if device is None:
return None
self.mac_lookup.pop(device.mac.lower().replace(":", ""), None)
self.mac_lookup.pop(normalize_mac(device.mac), None)

self._create_stat(packet, None, False)
return WSSubscriptionMessage(
Expand Down
6 changes: 6 additions & 0 deletions src/uiprotect/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,3 +624,9 @@ def clamp_value(value: float, step_size: float) -> float:
"""Clamps value to multiples of step size."""
ratio = 1 / step_size
return int(value * ratio) / ratio


@lru_cache(maxsize=1024)
def normalize_mac(mac: str) -> str:
"""Normalize MAC address."""
return mac.lower().replace(":", "").replace("-", "").replace("_", "")

0 comments on commit 7ce8654

Please sign in to comment.