Skip to content

Commit 87fb8dc

Browse files
committed
util: argparse: device ID helper class
Add a helper class for specifying Infuse IoT device IDs that evaluates to an integer but opaquely handles different ID forms. Signed-off-by: Jordan Yates <jordan@embeint.com>
1 parent 8f5d3df commit 87fb8dc

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/infuse_iot/util/argparse.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,13 @@ def to_ctype(cls, addr_type: rpc_enum_bt_le_addr_type, value: int) -> rpc_struct
7979
def integer_value(cls, string) -> int:
8080
"""Integer value from address string"""
8181
return cast(int, cls(string))
82+
83+
84+
class InfuseDeviceId:
85+
"""Infuse-IoT Device ID"""
86+
87+
def __new__(cls, string) -> int: # type: ignore
88+
try:
89+
return int(string, 16)
90+
except ValueError as e:
91+
raise argparse.ArgumentTypeError(f"{string} is not a valid hex ID") from e

tests/util/test_argparse.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import pytest
88

9-
from infuse_iot.util.argparse import BtLeAddress, ValidDir, ValidFile
9+
from infuse_iot.util.argparse import BtLeAddress, InfuseDeviceId, ValidDir, ValidFile
1010

1111
assert "TOXTEMPDIR" in os.environ, "you must run these tests using tox"
1212

@@ -46,3 +46,16 @@ def test_bt_le_address():
4646
assert isinstance(addr, int)
4747
addr = BtLeAddress("123456aaFF4A")
4848
assert isinstance(addr, int)
49+
50+
51+
def test_infuse_device_id():
52+
with pytest.raises(argparse.ArgumentTypeError):
53+
InfuseDeviceId("NotHex")
54+
with pytest.raises(argparse.ArgumentTypeError):
55+
InfuseDeviceId("aabb::00")
56+
assert InfuseDeviceId("0x00aa") == 0xAA
57+
assert InfuseDeviceId("00aa") == 0xAA
58+
assert InfuseDeviceId("0x99") == 0x99
59+
assert InfuseDeviceId("99") == 0x99
60+
assert InfuseDeviceId("0x1234aa43bc") == 0x1234AA43BC
61+
assert InfuseDeviceId("1234aa43bc") == 0x1234AA43BC

0 commit comments

Comments
 (0)