Skip to content

Commit 3810b40

Browse files
committed
tools: use common InfuseDeviceId type
Use the common `utils.argparse.InfuseDeviceId` class for device IDs so that behaviour is standardised across all tools and supports the IDs without the `0x` prefix. Signed-off-by: Jordan Yates <jordan@embeint.com>
1 parent 87fb8dc commit 3810b40

9 files changed

Lines changed: 82 additions & 67 deletions

File tree

src/infuse_iot/tools/annotate_events.py

Lines changed: 61 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
default_multicast_address,
2929
)
3030
from infuse_iot.time import InfuseTime
31-
from infuse_iot.util.argparse import ValidFile
31+
from infuse_iot.util.argparse import InfuseDeviceId, ValidFile
3232
from infuse_iot.util.console import choose_one
3333
from infuse_iot.zephyr.errno import errno
3434

@@ -37,12 +37,14 @@ class LabelType(enum.Enum):
3737
CUSTOM = "custom"
3838
MANUAL = "manual"
3939

40+
4041
class TimeCheckType(enum.Enum):
4142
NONE = "none"
4243
FORCE = "force"
4344
AUTO = "auto"
4445
DEFAULT = "default"
4546

47+
4648
class SubCommand(InfuseCommand):
4749
NAME = "annotate_events"
4850
HELP = "Annotate events on Infuse Tags"
@@ -58,44 +60,66 @@ class SubCommand(InfuseCommand):
5860
def add_parser(cls, parser):
5961
# Logger Selection parameters.
6062
logger_parser = parser.add_mutually_exclusive_group(required=True)
61-
logger_parser.add_argument("--onboard", dest="logger", action="store_const",
62-
const=rpc_enum_data_logger.FLASH_ONBOARD)
63-
logger_parser.add_argument("--external", dest="logger", action="store_const",
64-
const=rpc_enum_data_logger.FLASH_REMOVABLE)
65-
logger_parser.add_argument("--logger", "-l", type=annotate_wrapper.parse_logger,
66-
help="TDF Data Logger to write the event to")
63+
logger_parser.add_argument(
64+
"--onboard", dest="logger", action="store_const", const=rpc_enum_data_logger.FLASH_ONBOARD
65+
)
66+
logger_parser.add_argument(
67+
"--external", dest="logger", action="store_const", const=rpc_enum_data_logger.FLASH_REMOVABLE
68+
)
69+
logger_parser.add_argument(
70+
"--logger", "-l", type=annotate_wrapper.parse_logger, help="TDF Data Logger to write the event to"
71+
)
6772

6873
# Label selection parameters.
6974
label_group = parser.add_mutually_exclusive_group(required=True)
7075
label_group.add_argument(
71-
"--preset-labels", "-p", dest="labels", type=ValidFile,
72-
help="JSON file containing labels"
76+
"--preset-labels", "-p", dest="labels", type=ValidFile, help="JSON file containing labels"
7377
)
7478
label_group.add_argument(
75-
"--custom-labels", "-c", dest="labels", action="store_const", const=LabelType.CUSTOM,
76-
help="Specify custom labels at runtime"
79+
"--custom-labels",
80+
"-c",
81+
dest="labels",
82+
action="store_const",
83+
const=LabelType.CUSTOM,
84+
help="Specify custom labels at runtime",
7785
)
7886
label_group.add_argument(
79-
"--manual-labels", "-m", dest="labels", action="store_const", const=LabelType.MANUAL,
80-
help="Manually enter labels for each event"
87+
"--manual-labels",
88+
"-m",
89+
dest="labels",
90+
action="store_const",
91+
const=LabelType.MANUAL,
92+
help="Manually enter labels for each event",
8193
)
8294

8395
# Time sync parameters.
8496
time_group = parser.add_mutually_exclusive_group()
8597
time_group.add_argument(
86-
"--force-time", "-f", dest="time", action="store_const", const=TimeCheckType.FORCE,
87-
help="Forcibly update the tag's time before writing annotations"
98+
"--force-time",
99+
"-f",
100+
dest="time",
101+
action="store_const",
102+
const=TimeCheckType.FORCE,
103+
help="Forcibly update the tag's time before writing annotations",
88104
)
89105
time_group.add_argument(
90-
"--auto-time", "-a", dest="time", action="store_const", const=TimeCheckType.AUTO,
91-
help="Automatically update the tag's time if it is not current"
106+
"--auto-time",
107+
"-a",
108+
dest="time",
109+
action="store_const",
110+
const=TimeCheckType.AUTO,
111+
help="Automatically update the tag's time if it is not current",
92112
)
93113
time_group.add_argument(
94-
"--skip-time", "-s", dest="time", action="store_const", const=TimeCheckType.NONE,
95-
help="Do not update the tag's time before writing annotations"
114+
"--skip-time",
115+
"-s",
116+
dest="time",
117+
action="store_const",
118+
const=TimeCheckType.NONE,
119+
help="Do not update the tag's time before writing annotations",
96120
)
97121

98-
parser.add_argument("--id", type=lambda x: int(x, 0), help="Device to log events to")
122+
parser.add_argument("--id", type=InfuseDeviceId, help="Device to log events to")
99123

100124
def __init__(self, args):
101125
self._label_type = args.labels
@@ -147,18 +171,14 @@ def load_tag_time(self):
147171
sync_request_sent = datetime.now()
148172
assert self.rpc_client is not None
149173
hdr, rsp = self.rpc_client.run_standard_cmd(
150-
time_get.COMMAND_ID,
151-
Auth.DEVICE,
152-
bytes(params),
153-
time_get.response.from_buffer_copy
174+
time_get.COMMAND_ID, Auth.DEVICE, bytes(params), time_get.response.from_buffer_copy
154175
)
155176
sync_response_received = datetime.now()
156177

157178
if hdr is None:
158179
raise RuntimeError("Failed to get time from tag")
159180
if hdr.return_code != 0:
160-
raise RuntimeError(f"Error getting time from tag ({hdr.return_code}): "
161-
f"{errno.strerror(-hdr.return_code)}")
181+
raise RuntimeError(f"Error getting time from tag ({hdr.return_code}): {errno.strerror(-hdr.return_code)}")
162182

163183
assert isinstance(rsp, time_get.response)
164184
time_response: time_get.response = rsp
@@ -179,7 +199,7 @@ def check_tag_needs_sync(self) -> bool:
179199
f"Tag's clock is out of sync. Update the tag's time?\n"
180200
f"Tag: {tag_datetime_now}\n"
181201
f"System: {self._time_of_sync}",
182-
["Yes", "No"]
202+
["Yes", "No"],
183203
)
184204
update = not bool(selection)
185205
except IndexError:
@@ -190,25 +210,19 @@ def check_tag_needs_sync(self) -> bool:
190210
def sync_tag_time(self):
191211
# Update the tag's time to the current time.
192212
now = datetime.now().timestamp()
193-
params = time_set.request(
194-
InfuseTime.epoch_time_from_unix(now)
195-
)
213+
params = time_set.request(InfuseTime.epoch_time_from_unix(now))
196214

197215
sync_request_sent = datetime.now()
198216
assert self.rpc_client is not None
199217
hdr, _ = self.rpc_client.run_standard_cmd(
200-
time_set.COMMAND_ID,
201-
Auth.DEVICE,
202-
bytes(params),
203-
time_set.response.from_buffer_copy
218+
time_set.COMMAND_ID, Auth.DEVICE, bytes(params), time_set.response.from_buffer_copy
204219
)
205220

206221
sync_response_received = datetime.now()
207222
if hdr is None:
208223
raise RuntimeError("Failed to set time on tag")
209224
if hdr.return_code != 0:
210-
raise RuntimeError(f"Error setting time on tag ({hdr.return_code}): "
211-
f"{errno.strerror(-hdr.return_code)}")
225+
raise RuntimeError(f"Error setting time on tag ({hdr.return_code}): {errno.strerror(-hdr.return_code)}")
212226

213227
# Update sync point to reflect new time on tag, assuming the tag's time doesn't change for
214228
# the duration of the connection.
@@ -249,8 +263,11 @@ def connection_listener(self):
249263
evt = self._client.receive()
250264
if evt is None:
251265
continue
252-
if isinstance(evt, ClientNotificationConnectionDropped) and \
253-
evt.infuse_id == self._device_id and not self.complete:
266+
if (
267+
isinstance(evt, ClientNotificationConnectionDropped)
268+
and evt.infuse_id == self._device_id
269+
and not self.complete
270+
):
254271
# Ensure the connection wasn't caused by the script existing.
255272
print("\n" * (len(self._labels))) # Clear any pending input lines
256273
print(f"Lost connection to {self._device_id:016x}")
@@ -267,10 +284,10 @@ def run(self):
267284
cl.start()
268285

269286
while not self.complete:
270-
with Live(self.draw_connecting(), refresh_per_second=4) as live, \
271-
self._client.connection(
272-
self._device_id, GatewayRequestConnectionRequest.DataType.COMMAND
273-
) as mtu:
287+
with (
288+
Live(self.draw_connecting(), refresh_per_second=4) as live,
289+
self._client.connection(self._device_id, GatewayRequestConnectionRequest.DataType.COMMAND) as mtu,
290+
):
274291
self.connected = True
275292
live.transient = True
276293
live.stop()
@@ -293,15 +310,10 @@ def run(self):
293310
params = annotate_wrapper.annotate_factory(self._logger, timestamp, label)
294311

295312
hdr, _ = self.rpc_client.run_standard_cmd(
296-
annotate.COMMAND_ID,
297-
Auth.DEVICE,
298-
bytes(params),
299-
annotate.response.from_buffer_copy
313+
annotate.COMMAND_ID, Auth.DEVICE, bytes(params), annotate.response.from_buffer_copy
300314
)
301315

302316
if hdr is None:
303317
print("Failed to send annotation event to tag")
304318
continue
305-
annotate_wrapper.handle_response_generic(
306-
hdr.return_code, self._logger, now, label
307-
)
319+
annotate_wrapper.handle_response_generic(hdr.return_code, self._logger, now, label)

src/infuse_iot/tools/audio_record.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
default_multicast_address,
2323
)
2424
from infuse_iot.tdf import TDF
25+
from infuse_iot.util.argparse import InfuseDeviceId
2526
from infuse_iot.util.console import Console
2627

2728

@@ -47,7 +48,7 @@ def __init__(self, args):
4748
def add_parser(cls, parser):
4849
addr_group = parser.add_mutually_exclusive_group(required=True)
4950
addr_group.add_argument("--gateway", action="store_true", help="Run command on local gateway")
50-
addr_group.add_argument("--id", type=lambda x: int(x, 0), help="Infuse ID to run command on")
51+
addr_group.add_argument("--id", type=InfuseDeviceId, help="Infuse ID to run command on")
5152
parser.add_argument(
5253
"--conn-timeout", type=int, default=10000, help="Timeout to wait for a connection to the device (ms)"
5354
)

src/infuse_iot/tools/bt_log.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
default_multicast_address,
1919
)
2020
from infuse_iot.tdf import TDF
21+
from infuse_iot.util.argparse import InfuseDeviceId
2122
from infuse_iot.util.console import Console
2223

2324

@@ -35,7 +36,7 @@ def __init__(self, args):
3536

3637
@classmethod
3738
def add_parser(cls, parser):
38-
parser.add_argument("--id", type=lambda x: int(x, 0), required=True, help="Infuse ID to receive logs for")
39+
parser.add_argument("--id", type=InfuseDeviceId, required=True, help="Infuse ID to receive logs for")
3940
parser.add_argument("--data", action="store_true", help="Subscribe to the data characteristic as well")
4041
parser.add_argument(
4142
"--conn-timeout", type=int, default=10000, help="Timeout to wait for a connection to the device (ms)"

src/infuse_iot/tools/cloud.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
from infuse_iot.api_client.types import File, Unset
5050
from infuse_iot.commands import InfuseCommand
5151
from infuse_iot.credentials import get_api_key
52-
from infuse_iot.util.argparse import ValidRelease
52+
from infuse_iot.util.argparse import InfuseDeviceId, ValidRelease
5353
from infuse_iot.util.console import choose_one, user_confirm, user_response
5454
from infuse_iot.util.version import Version
5555

@@ -188,11 +188,11 @@ def add_parser(cls, parser):
188188

189189
info_parser = tool_parser.add_parser("info", help="General device information")
190190
info_parser.set_defaults(command_fn=cls.info)
191-
info_parser.add_argument("--id", type=str, required=True, help="Infuse-IoT device ID")
191+
info_parser.add_argument("--id", type=InfuseDeviceId, required=True, help="Infuse-IoT device ID")
192192

193193
kv_parser = tool_parser.add_parser("kv_state", help="Key-Value device state")
194194
kv_parser.set_defaults(command_fn=cls.kv_state)
195-
kv_parser.add_argument("--id", type=str, required=True, help="Infuse-IoT device ID")
195+
kv_parser.add_argument("--id", type=InfuseDeviceId, required=True, help="Infuse-IoT device ID")
196196
kv_parser.add_argument("--schedules", action="store_true", help="Display task schedules")
197197
kv_display = kv_parser.add_mutually_exclusive_group()
198198
kv_display.add_argument("--hex", action="store_true", help="Display values as hex strings instead of decoding")
@@ -202,7 +202,7 @@ def add_parser(cls, parser):
202202

203203
dfu_parser = tool_parser.add_parser("dfu", help="Manage device firmware upgrades")
204204
dfu_parser.set_defaults(command_fn=cls.dfu)
205-
dfu_parser.add_argument("--id", type=str, required=True, help="Infuse-IoT device ID")
205+
dfu_parser.add_argument("--id", type=InfuseDeviceId, required=True, help="Infuse-IoT device ID")
206206
dfu_action = dfu_parser.add_mutually_exclusive_group(required=True)
207207
dfu_action.add_argument("--schedule", type=str, help="Release ID to upgrade to")
208208
dfu_action.add_argument("--status", action="store_true", help="Check DFU status")
@@ -212,8 +212,7 @@ def run(self):
212212
self.args.command_fn(self, client)
213213

214214
def info(self, client: Client):
215-
id_int = int(self.args.id, 0)
216-
id_str = f"{id_int:016x}"
215+
id_str = f"{self.args.id:016x}"
217216
info = get_device_by_device_id.sync(client=client, device_id=id_str)
218217
if info is None:
219218
sys.exit(f"No device with Infuse-IoT ID {id_str} found")
@@ -300,8 +299,7 @@ def _kv_display(self, table: list[tuple[str, str, Any]], key_val: str, name_base
300299
key_val = ""
301300

302301
def kv_state(self, client: Client):
303-
id_int = int(self.args.id, 0)
304-
id_str = f"{id_int:016x}"
302+
id_str = f"{self.args.id:016x}"
305303

306304
kv_state = get_device_kv_entries_by_device_id.sync(client=client, device_id=id_str)
307305
if not isinstance(kv_state, list):
@@ -336,8 +334,7 @@ def kv_state(self, client: Client):
336334
print(tabulate(table))
337335

338336
def dfu(self, client: Client):
339-
id_int = int(self.args.id, 0)
340-
id_str = f"{id_int:016x}"
337+
id_str = f"{self.args.id:016x}"
341338

342339
if self.args.schedule:
343340
body = models.NewDeviceApplicationUpdate(self.args.schedule)

src/infuse_iot/tools/ota_upgrade.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
LocalClient,
3131
default_multicast_address,
3232
)
33-
from infuse_iot.util.argparse import ValidFile, ValidRelease
33+
from infuse_iot.util.argparse import InfuseDeviceId, ValidFile, ValidRelease
3434
from infuse_iot.util.crc import crc16_ccitt
3535
from infuse_iot.zephyr.errno import errno
3636

@@ -104,7 +104,7 @@ def add_parser(cls, parser):
104104
"--conn-timeout", type=int, default=10000, help="Timeout to wait for a connection to the device (ms)"
105105
)
106106
explicit = parser.add_mutually_exclusive_group()
107-
explicit.add_argument("--id", type=lambda x: int(x, 0), help="Single device to upgrade")
107+
explicit.add_argument("--id", type=InfuseDeviceId, help="Single device to upgrade")
108108
explicit.add_argument("--list", type=ValidFile, help="File containing a list of IDs to upgrade")
109109

110110
def progress_table(self):

src/infuse_iot/tools/provision.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from infuse_iot.api_client.models import Board, Device, DeviceMetadata, Error, NewDevice
2121
from infuse_iot.commands import InfuseCommand
2222
from infuse_iot.credentials import get_api_key
23+
from infuse_iot.util.argparse import InfuseDeviceId
2324
from infuse_iot.util.console import choose_one
2425
from infuse_iot.util.soc import nrf, soc, stm
2526

@@ -49,7 +50,7 @@ def add_parser(cls, parser):
4950
parser.add_argument(
5051
"--id",
5152
"-i",
52-
type=lambda x: int(x, 0),
53+
type=InfuseDeviceId,
5354
help="Infuse device ID to provision as",
5455
)
5556
parser.add_argument(

src/infuse_iot/tools/rpc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
LocalClient,
2323
default_multicast_address,
2424
)
25+
from infuse_iot.util.argparse import InfuseDeviceId
2526

2627

2728
class SubCommand(InfuseCommand):
@@ -33,7 +34,7 @@ class SubCommand(InfuseCommand):
3334
def add_parser(cls, parser):
3435
addr_group = parser.add_mutually_exclusive_group(required=True)
3536
addr_group.add_argument("--gateway", action="store_true", help="Run command on local gateway")
36-
addr_group.add_argument("--id", type=lambda x: int(x, 0), help="Infuse ID to run command on")
37+
addr_group.add_argument("--id", type=InfuseDeviceId, help="Infuse ID to run command on")
3738
parser.add_argument("--conn-log", action="store_true", help="Request logs from remote device")
3839
parser.add_argument(
3940
"--conn-timeout", type=int, default=10000, help="Timeout to wait for a connection to the device (ms)"

src/infuse_iot/tools/rpc_cloud.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from infuse_iot.commands import InfuseCommand, InfuseRpcCommand, wrapper_from_command_id
2323
from infuse_iot.credentials import get_api_key
2424
from infuse_iot.definitions.rpc import id_type_mapping
25+
from infuse_iot.util.argparse import InfuseDeviceId
2526
from infuse_iot.zephyr.errno import errno
2627

2728

@@ -36,7 +37,7 @@ def add_parser(cls, parser):
3637

3738
parser_queue = subparser.add_parser("queue", help="Queue a RPC to be sent")
3839
parser_queue.set_defaults(_tool_action="queue")
39-
parser_queue.add_argument("--id", required=True, type=lambda x: int(x, 0), help="Infuse ID to run command on")
40+
parser_queue.add_argument("--id", required=True, type=InfuseDeviceId, help="Infuse ID to run command on")
4041
parser_queue.add_argument("--queue-timeout", type=int, default=600, help="Timeout to send command in seconds")
4142
parser_queue.add_argument("--print-params", action="store_true", help="Print queued RPC request")
4243
command_list_parser = parser_queue.add_subparsers(title="commands", metavar="<command>", required=True)

src/infuse_iot/tools/tdf_list.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
)
2121
from infuse_iot.tdf import TDF
2222
from infuse_iot.time import InfuseTime
23+
from infuse_iot.util.argparse import InfuseDeviceId
2324

2425

2526
class SubCommand(InfuseCommand):
@@ -31,7 +32,7 @@ class SubCommand(InfuseCommand):
3132
def add_parser(cls, parser):
3233
parser.add_argument("--array-all", action="store_true", help="Display all array values, not just the last")
3334
parser.add_argument(
34-
"--id", type=lambda x: int(x, 0), action="append", default=[], help="Limit displayed TDFs by device ID"
35+
"--id", type=InfuseDeviceId, action="append", default=[], help="Limit displayed TDFs by device ID"
3536
)
3637
parser.add_argument("--min-rssi", type=int, help="Minimum RSSI to display TDF")
3738

0 commit comments

Comments
 (0)