Files
controller-wisetopdataserver/python/biopro/util/address.py
T
2021-12-20 14:52:55 +08:00

82 lines
1.9 KiB
Python

"""This module provide the mac address type and transform functions."""
import struct as _struct
from typing import Any, Tuple, Iterable
ADDRESS = Tuple[int, int, int, int, int, int]
'''mac address type'''
EMPTY_ADDRESS = (0, 0, 0, 0, 0, 0)
'''empty mac address'''
def is_address_type(instance: Any) -> bool:
if isinstance(instance, tuple):
if len(instance) == 6:
if all(map(lambda v: isinstance(v, int), instance)):
return True
return False
def str_address(address: str) -> ADDRESS:
"""convert address string to python form.
input form ::
00:00:00:00:00:00
output form ::
(0, 0, 0, 0, 0, 0)
:param address:
:return:
"""
# noinspection PyPep8Naming
H = "0123456789ABCDEF"
def _str_hex_to_int(h: str) -> int:
h = h.upper()
return 16 * H.index(h[0]) + H.index(h[1])
try:
ret = tuple(map(_str_hex_to_int, address.split(':', 6)))
except IndexError as e:
raise ValueError('not a address : ' + address) from e
if len(ret) != 6:
raise ValueError('not a address : ' + address)
# noinspection PyTypeChecker
return ret
def address_str(data: Iterable[int]) -> str:
"""convert address to string in form like below ::
00:00:00:00:00:00
:param data: address
:return: address string
"""
return ':'.join(map(lambda v: '%02X' % v, data))
def address_bytes(address: ADDRESS) -> bytes:
"""convert address into bytes (little-endian) format.
:param address:
:return:
"""
return _struct.pack('6B', *reversed(address))
def bytes_address(address: bytes) -> ADDRESS:
"""convert address byte data to python form.
:param address: address data in little-endian bytes format
:return:
"""
# noinspection PyTypeChecker
return tuple(reversed(_struct.unpack('6B', address)))