utils.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Utility functions for switchbot."""
  2. from collections.abc import Mapping
  3. from functools import lru_cache
  4. _REQUEST_ID_HEADERS = ("x-request-id", "x-amzn-requestid", "cf-ray")
  5. def extract_request_id(headers: Mapping[str, str]) -> str | None:
  6. """Extract a provider request identifier for log correlation."""
  7. normalized_headers = {name.lower(): value for name, value in headers.items()}
  8. return next(
  9. (
  10. value
  11. for name in _REQUEST_ID_HEADERS
  12. if (value := normalized_headers.get(name))
  13. ),
  14. None,
  15. )
  16. @lru_cache(maxsize=512)
  17. def format_mac_upper(mac: str) -> str:
  18. """Format the mac address string to uppercase with colons."""
  19. to_test = mac
  20. if len(to_test) == 17 and to_test.count(":") == 5:
  21. return to_test.upper()
  22. if len(to_test) == 17 and to_test.count("-") == 5:
  23. to_test = to_test.replace("-", "")
  24. elif len(to_test) == 14 and to_test.count(".") == 2:
  25. to_test = to_test.replace(".", "")
  26. if len(to_test) == 12:
  27. # bare 12-char hex, insert colons
  28. return ":".join(to_test.upper()[i : i + 2] for i in range(0, 12, 2))
  29. # Not sure how formatted, return original
  30. return mac.upper()