OpenZilo 0.6.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openzilo/_cli.py ADDED
@@ -0,0 +1,751 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Command-line interface (python -m openzilo)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import asyncio
8
+ import json
9
+ import importlib.util
10
+ import logging
11
+ import math
12
+ import os
13
+ import shlex
14
+ import sys
15
+ from dataclasses import asdict, replace
16
+ from pathlib import Path
17
+
18
+ from ._cli_calibration import cmd_imu_calibration
19
+ from ._imu_profiles import load_imu_calibration_profile, open_calibrated_imu_stream
20
+ from ._identity import get_sdk_identity
21
+ from ._compatibility import get_device_capabilities
22
+ from ._version import __version__
23
+ from ._transport import DEFAULT_SCAN_TIMEOUT_S
24
+ from ._cli_config import config_path, load_address, save_address
25
+ from ._errors import OpenZiloError, TimeoutError as DeviceTimeoutError
26
+ from ._sensor import start_sensor_report, stop_sensor_report, wait_sensor_data
27
+ from ._client import OpenZiloClient
28
+ from ._device import (
29
+ connect_ring,
30
+ enable_time_sync,
31
+ get_log_storage,
32
+ get_system_info,
33
+ get_connection_rssi,
34
+ read_log_chunk,
35
+ scan_rings,
36
+ )
37
+ from ._ota import update_firmware
38
+ from ._firmware_bundle import FirmwareBundle, inspect_firmware_bundle
39
+ from ._codec import (
40
+ build_playable_audio,
41
+ DEFAULT_BIT_DEPTH,
42
+ DEFAULT_CHANNELS,
43
+ DEFAULT_SAMPLE_RATE,
44
+ DEFAULT_SPEEX_QUALITY,
45
+ PcmConfig,
46
+ save_audio_bundle,
47
+ )
48
+ from ._audio import (
49
+ clear_audio_files,
50
+ download_audio_file,
51
+ get_audio_file_count,
52
+ ProgressPrinter,
53
+ receive_auto_audio_file,
54
+ )
55
+ from ._live_audio import receive_live_audio_file
56
+ from ._recording import (
57
+ AudioOutput, AudioDisconnectPolicy, get_audio_recording_config,
58
+ set_audio_recording_config, get_audio_recording_status,
59
+ start_audio_recording, stop_audio_recording, wait_audio_recording_finished,
60
+ )
61
+
62
+ _logger = logging.getLogger(__name__)
63
+
64
+
65
+ def add_connection_args(parser: argparse.ArgumentParser) -> None:
66
+ parser.add_argument("--address", help="BLE address/UUID; defaults to OPENZILO_ADDRESS or 'device use'.")
67
+ parser.add_argument("--scan-timeout", type=positive_seconds, default=DEFAULT_SCAN_TIMEOUT_S)
68
+ parser.add_argument("--connect-timeout", type=positive_seconds, default=30.0)
69
+ parser.add_argument("--allow-unverified-features", action="store_true",
70
+ help="Allow enhanced commands on unknown legacy firmware; does not override declared incompatibility.")
71
+ parser.set_defaults(needs_device=True)
72
+
73
+
74
+ def positive_seconds(value: str) -> float:
75
+ seconds = float(value)
76
+ if not math.isfinite(seconds) or seconds <= 0:
77
+ raise argparse.ArgumentTypeError("must be finite and greater than zero")
78
+ return seconds
79
+
80
+
81
+ async def cmd_device(args: argparse.Namespace) -> None:
82
+ if args.action == "forget":
83
+ config_path().unlink(missing_ok=True)
84
+ print("Saved device removed. OPENZILO_ADDRESS, if set, still applies.")
85
+ elif args.action == "show":
86
+ address = os.environ.get("OPENZILO_ADDRESS") or load_address()
87
+ print(f"device: {address or '(none; run openzilo device use)'}")
88
+ print(f"config: {config_path()}")
89
+ else:
90
+ address = args.address
91
+ if address is None:
92
+ print("Scanning for rings...", flush=True)
93
+ devices = await scan_rings(timeout_s=args.timeout)
94
+ if not devices:
95
+ raise ValueError("No rings found; wake the ring and run 'device use' again")
96
+ for index, device in enumerate(devices, 1):
97
+ print(f"{index}. {device.name or 'Ring'} {device.address} RSSI={device.rssi}")
98
+ choice = input("Select device number (Enter to cancel): ")
99
+ if not choice.strip():
100
+ return
101
+ if not choice.isdecimal() or not 1 <= int(choice) <= len(devices):
102
+ raise ValueError("Invalid device number; no device saved")
103
+ address = devices[int(choice) - 1].address
104
+ save_address(address)
105
+ print(f"Saved default device: {address.strip()}")
106
+
107
+
108
+ async def cmd_shell(args: argparse.Namespace) -> None:
109
+ print("OpenZilo shell: help lists commands; exit closes the shell. Device commands connect and disconnect automatically.")
110
+ print("Common commands: info | audio-config | audio-record recording.wav --seconds 5 | audio-status")
111
+ parser = build_parser()
112
+ while True:
113
+ try:
114
+ # No BLE session is active at the prompt. Read on the main thread so
115
+ # Ctrl+C cannot strand an input worker during asyncio shutdown.
116
+ line = input("openzilo> ")
117
+ except EOFError:
118
+ return
119
+ try:
120
+ words = shlex.split(line)
121
+ if not words:
122
+ continue
123
+ if words == ["exit"] or words == ["quit"]:
124
+ return
125
+ if words[0] == "help":
126
+ parser.parse_args([*words[1:], "--help"])
127
+ continue
128
+ command = parser.parse_args(words)
129
+ if command.func is cmd_shell:
130
+ print("Already in the interactive shell.")
131
+ continue
132
+ await dispatch(command, fallback_address=args.address)
133
+ except SystemExit as exc:
134
+ # argparse help and invalid commands must not terminate the shell.
135
+ if isinstance(exc.code, str):
136
+ print(exc.code, file=sys.stderr)
137
+ continue
138
+ except (OpenZiloError, OSError, ValueError, RuntimeError, EOFError) as exc:
139
+ print(f"Error: {exc}", file=sys.stderr)
140
+
141
+
142
+ async def cmd_sensor_stream(args: argparse.Namespace) -> None:
143
+ if getattr(args, "calibration_profile", None) and not getattr(args, "calibrated", False):
144
+ raise ValueError('--calibration-profile requires --calibrated')
145
+ # Open output before connecting so an invalid path cannot start device capture.
146
+ stream = None
147
+ if args.output:
148
+ args.output.parent.mkdir(parents=True, exist_ok=True)
149
+ stream = args.output.open("w", encoding="utf-8")
150
+ try:
151
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
152
+ connect_timeout_s=args.connect_timeout,
153
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
154
+ await get_device_capabilities(client, timeout_s=3.0)
155
+ enable_time_sync(client)
156
+ if getattr(args, "calibrated", False):
157
+ profile_path = getattr(args, "calibration_profile", None)
158
+ profile = load_imu_calibration_profile(profile_path) if profile_path else None
159
+ async with open_calibrated_imu_stream(client, profile, device_id=args.address) as calibrated:
160
+ print(f"IMU software calibration: {calibrated.config}", file=sys.stderr)
161
+ loop = asyncio.get_running_loop()
162
+ deadline = loop.time() + args.seconds
163
+ while (remaining := deadline-loop.time()) > 0:
164
+ try:
165
+ batch = await asyncio.wait_for(anext(calibrated), remaining)
166
+ except (DeviceTimeoutError, asyncio.TimeoutError):
167
+ break
168
+ print(json.dumps({"data_domain": "software_calibrated", "accel_unit": "g",
169
+ "gyro_unit": "deg/s", **asdict(batch)}),
170
+ file=stream or sys.stdout, flush=True)
171
+ return
172
+ info = await start_sensor_report(client)
173
+ print(f"IMU: {info}", file=sys.stderr)
174
+ try:
175
+ loop = asyncio.get_running_loop()
176
+ deadline = loop.time() + args.seconds
177
+ while (remaining := deadline - loop.time()) > 0:
178
+ try:
179
+ batch = await wait_sensor_data(client, timeout_s=remaining)
180
+ except DeviceTimeoutError:
181
+ break
182
+ print(json.dumps(asdict(batch)), file=stream or sys.stdout, flush=True)
183
+ finally:
184
+ await stop_sensor_report(client)
185
+ finally:
186
+ if stream:
187
+ stream.close()
188
+
189
+
190
+ def add_audio_decode_args(parser: argparse.ArgumentParser) -> None:
191
+ parser.add_argument("--ffmpeg", default="ffmpeg", help="ffmpeg executable path.")
192
+ parser.add_argument("--pcm-sample-rate", type=int, default=DEFAULT_SAMPLE_RATE)
193
+ parser.add_argument("--pcm-channels", type=int, default=DEFAULT_CHANNELS, choices=(1, 2))
194
+ parser.add_argument("--pcm-bit-depth", type=int, default=DEFAULT_BIT_DEPTH, choices=(8, 16))
195
+ parser.add_argument("--speex-quality", type=int, default=DEFAULT_SPEEX_QUALITY)
196
+ parser.add_argument("--speex-bits-size", type=int, default=None)
197
+ parser.add_argument(
198
+ "--allow-framed-blocks",
199
+ action="store_true",
200
+ help="Allow legacy 1026-byte outer blocks when parsing Speex packets.",
201
+ )
202
+
203
+
204
+ def pcm_config_from_args(args: argparse.Namespace) -> PcmConfig:
205
+ return PcmConfig(
206
+ sample_rate=args.pcm_sample_rate,
207
+ channels=args.pcm_channels,
208
+ bit_depth=args.pcm_bit_depth,
209
+ )
210
+
211
+
212
+ async def cmd_scan(args: argparse.Namespace) -> None:
213
+ seen = {}
214
+
215
+ def changed(devices):
216
+ for device in devices:
217
+ if seen.get(device.address) != device:
218
+ name = device.name or "Ring (name pending)"
219
+ print(f"name={name!r} address={device.address} rssi={device.rssi} "
220
+ f"matched_service={device.matched_service}", flush=True)
221
+ seen[device.address] = device
222
+
223
+ devices = await scan_rings(address=args.address, timeout_s=args.timeout,
224
+ on_devices_changed=changed)
225
+ if not devices:
226
+ print("No matching devices found.")
227
+
228
+
229
+ async def cmd_connect(args: argparse.Namespace) -> None:
230
+ client = await connect_ring(address=args.address, scan_timeout_s=args.scan_timeout,
231
+ connect_timeout_s=args.connect_timeout,
232
+ allow_unverified_features=getattr(args, "allow_unverified_features", False))
233
+ try:
234
+ print(f"connected: {client.is_connected}")
235
+ finally:
236
+ await client.disconnect()
237
+
238
+
239
+ async def cmd_capabilities(args: argparse.Namespace) -> None:
240
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
241
+ connect_timeout_s=args.connect_timeout,
242
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
243
+ capabilities = await get_device_capabilities(client, timeout_s=args.timeout)
244
+ result = {"sdk": asdict(get_sdk_identity()), "device": asdict(capabilities)}
245
+ if args.command == "doctor":
246
+ result["host"] = {"opus_decoder_installed": importlib.util.find_spec("av") is not None}
247
+ result["notes"] = ["Capabilities describe support, not current busy state or BLE readiness."]
248
+ print(json.dumps(result, ensure_ascii=False, indent=2))
249
+
250
+
251
+ async def cmd_rssi(args: argparse.Namespace) -> None:
252
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
253
+ connect_timeout_s=args.connect_timeout,
254
+ allow_unverified_features=args.allow_unverified_features) as client:
255
+ rssi = await get_connection_rssi(client, timeout_s=args.timeout)
256
+ print(f"{rssi} dBm")
257
+
258
+
259
+ async def cmd_info(args: argparse.Namespace) -> None:
260
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
261
+ connect_timeout_s=args.connect_timeout,
262
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
263
+ enable_time_sync(client)
264
+ info = await get_system_info(client)
265
+
266
+ print(f"firmware_version: {info.firmware_version}")
267
+ print(f"system_time: {info.system_time}")
268
+ print(f"audio_storage_total: {info.audio_storage_total}")
269
+ print(f"audio_storage_available: {info.audio_storage_available}")
270
+ print(f"battery_percent: {info.battery_percent}")
271
+ print(f"battery_charging: {info.battery_charging}")
272
+ print(f"sn: {info.sn}")
273
+ print(f"cpuid: {info.cpuid}")
274
+ print(f"model: {info.model}")
275
+
276
+
277
+ async def cmd_time_sync(args: argparse.Namespace) -> None:
278
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
279
+ connect_timeout_s=args.connect_timeout,
280
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
281
+ enable_time_sync(client)
282
+ print(f"time sync auto-response enabled for {args.seconds:g}s")
283
+ await asyncio.sleep(args.seconds)
284
+ print("time sync session ended")
285
+
286
+
287
+ async def cmd_audio_count(args: argparse.Namespace) -> None:
288
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
289
+ connect_timeout_s=args.connect_timeout,
290
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
291
+ count = await get_audio_file_count(client)
292
+ print(f"audio file count: {count}")
293
+
294
+
295
+ async def cmd_audio_download(args: argparse.Namespace) -> None:
296
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
297
+ connect_timeout_s=args.connect_timeout,
298
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
299
+ count = await get_audio_file_count(client)
300
+ print(f"audio file count: {count}")
301
+ info, data = await download_audio_file(
302
+ client,
303
+ args.file_index,
304
+ progress=ProgressPrinter(prefix="audio"),
305
+ timeout_s=args.timeout,
306
+ )
307
+
308
+ bundle = save_audio_bundle(
309
+ file_index=args.file_index,
310
+ data=data,
311
+ metadata={"record_time": info.record_time},
312
+ output_path=args.output,
313
+ pcm_config=pcm_config_from_args(args),
314
+ quality=args.speex_quality,
315
+ bits_size=args.speex_bits_size,
316
+ allow_framed_blocks=args.allow_framed_blocks,
317
+ ffmpeg_path=args.ffmpeg,
318
+ )
319
+ print(f"raw recording saved: {bundle.raw_path} ({bundle.raw_size} bytes)")
320
+ print(f"decoded recording saved: {bundle.play_path} ({bundle.play_size} bytes)")
321
+ print(f"audio format: {bundle.play_description or bundle.format_label}")
322
+ print(f"file info: {info}")
323
+
324
+
325
+ async def cmd_audio_receive(args: argparse.Namespace) -> None:
326
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
327
+ connect_timeout_s=args.connect_timeout,
328
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
329
+ print("Connected. Make a recording; waiting for local save or legacy automatic upload.", flush=True)
330
+ index, data = await receive_auto_audio_file(client, timeout_s=args.timeout)
331
+ bundle = save_audio_bundle(file_index=index, data=data, output_path=args.output, ffmpeg_path=args.ffmpeg)
332
+ print(f"Saved {bundle.raw_path} and {bundle.play_path}: {bundle.play_description}")
333
+
334
+
335
+ async def cmd_audio_live(args: argparse.Namespace) -> None:
336
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
337
+ connect_timeout_s=args.connect_timeout,
338
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
339
+ await get_device_capabilities(client, timeout_s=3.0)
340
+ print("Subscribing to live audio. Flash retention follows the ring's recording configuration.", flush=True)
341
+ recording = await receive_live_audio_file(
342
+ client, timeout_s=args.timeout,
343
+ on_subscribed=lambda: print("Subscribed. Hold the record button now; release to finish.", flush=True),
344
+ )
345
+ bundle = save_audio_bundle(
346
+ file_index=recording.start.session_id, data=recording.data,
347
+ metadata={"record_time": recording.start.record_time},
348
+ output_path=args.output, ffmpeg_path=args.ffmpeg,
349
+ )
350
+ print(f"Saved {bundle.raw_path} and {bundle.play_path}: {bundle.play_description}")
351
+
352
+
353
+ async def _apply_recording_args(client: OpenZiloClient, args: argparse.Namespace):
354
+ config = await get_audio_recording_config(client)
355
+ changes = {}
356
+ for name in ("channels", "bitrate", "gain_left_q8", "gain_right_q8", "max_duration_ms"):
357
+ if getattr(args, name, None) is not None:
358
+ changes[name] = getattr(args, name)
359
+ if getattr(args, "destination", None) is not None:
360
+ changes["output"] = {"auto": AudioOutput.AUTO, "flash": AudioOutput.FLASH,
361
+ "live": AudioOutput.LIVE, "both": AudioOutput.LIVE_AND_FLASH}[args.destination]
362
+ if getattr(args, "disconnect", None) is not None:
363
+ changes["disconnect_policy"] = {"stop": AudioDisconnectPolicy.STOP,
364
+ "save": AudioDisconnectPolicy.CONTINUE_SAVING}[args.disconnect]
365
+ return await set_audio_recording_config(client, replace(config, **changes)) if changes else config
366
+
367
+
368
+ async def cmd_audio_config(args: argparse.Namespace) -> None:
369
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
370
+ connect_timeout_s=args.connect_timeout,
371
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
372
+ await get_device_capabilities(client, timeout_s=3.0)
373
+ print(await _apply_recording_args(client, args))
374
+
375
+
376
+ async def cmd_audio_status(args: argparse.Namespace) -> None:
377
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
378
+ connect_timeout_s=args.connect_timeout,
379
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
380
+ await get_device_capabilities(client, timeout_s=3.0)
381
+ print(await get_audio_recording_status(client))
382
+
383
+
384
+ async def cmd_audio_stop(args: argparse.Namespace) -> None:
385
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
386
+ connect_timeout_s=args.connect_timeout,
387
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
388
+ await get_device_capabilities(client, timeout_s=3.0)
389
+ await stop_audio_recording(client, args.session_id, cancel=args.cancel)
390
+ print(await wait_audio_recording_finished(client, args.session_id))
391
+
392
+
393
+ async def cmd_audio_record(args: argparse.Namespace) -> None:
394
+ if not math.isfinite(args.seconds) or not 0.02 <= args.seconds <= 60:
395
+ raise ValueError("seconds must be 0.02..60")
396
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
397
+ connect_timeout_s=args.connect_timeout,
398
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
399
+ await get_device_capabilities(client, timeout_s=3.0)
400
+ config = await _apply_recording_args(client, args)
401
+ session = None
402
+ stopper = None
403
+
404
+ async def timed_stop():
405
+ await asyncio.sleep(args.seconds)
406
+ await stop_audio_recording(client, session)
407
+
408
+ async def subscribed():
409
+ nonlocal session, stopper
410
+ session = await start_audio_recording(client)
411
+ print(f"Recording session {session}", flush=True)
412
+ stopper = asyncio.create_task(timed_stop())
413
+
414
+ try:
415
+ if config.output in (AudioOutput.LIVE, AudioOutput.LIVE_AND_FLASH):
416
+ recording = await receive_live_audio_file(client, on_subscribed=subscribed)
417
+ data = recording.data
418
+ else:
419
+ session = await start_audio_recording(client)
420
+ print(f"Recording session {session}", flush=True)
421
+ stopper = asyncio.create_task(timed_stop())
422
+ await stopper
423
+ status = await wait_audio_recording_finished(client, session)
424
+ if status.file_index is None:
425
+ raise RuntimeError("Recording ended without a saved file")
426
+ _, data = await download_audio_file(client, status.file_index)
427
+ if stopper is not None:
428
+ await stopper
429
+ status = await wait_audio_recording_finished(client, session)
430
+ print(status)
431
+ finally:
432
+ if stopper is not None and not stopper.done():
433
+ stopper.cancel()
434
+ await asyncio.gather(stopper, return_exceptions=True)
435
+ if session is not None and client.is_connected:
436
+ try:
437
+ await stop_audio_recording(client, session)
438
+ except Exception as exc:
439
+ _logger.warning("Could not confirm stop of session %s; query status before reuse: %s", session, exc)
440
+ bundle = save_audio_bundle(file_index=status.file_index if status.saved else session,
441
+ data=data, output_path=args.output, ffmpeg_path=args.ffmpeg)
442
+ print(f"Saved {bundle.raw_path} and {bundle.play_path}")
443
+
444
+
445
+ def _print_firmware_bundle(bundle: FirmwareBundle, *, json_output: bool = False) -> None:
446
+ manifest = bundle.manifest
447
+ if json_output:
448
+ print(json.dumps({"signature_verified": True, "manifest": manifest}, ensure_ascii=False, indent=2))
449
+ return
450
+ print("signature: verified")
451
+ for name, value in manifest.items():
452
+ if name == "payload":
453
+ for field, item in value.items():
454
+ print(f"payload.{field}: {item}")
455
+ elif name == "source_versions":
456
+ print(f"source_versions: {', '.join(value) if value else 'any'}")
457
+ else:
458
+ print(f"{name}: {value}")
459
+
460
+
461
+ async def cmd_ota_inspect(args: argparse.Namespace) -> None:
462
+ bundle = inspect_firmware_bundle(args.firmware.read_bytes(),
463
+ trusted_public_key=args.public_key.read_bytes())
464
+ _print_firmware_bundle(bundle, json_output=args.json)
465
+
466
+
467
+ async def cmd_ota_update(args: argparse.Namespace) -> None:
468
+ # Reject corrupt or invalid input before opening a BLE session.
469
+ data = args.firmware.read_bytes()
470
+ public_key = args.public_key.read_bytes()
471
+ bundle = inspect_firmware_bundle(data, trusted_public_key=public_key)
472
+ if bundle.profile == "test" and not args.allow_test_firmware:
473
+ raise ValueError("Test firmware requires --allow-test-firmware")
474
+ _print_firmware_bundle(bundle)
475
+ print("OTA transfer progress is not installation confirmation; keep the ring nearby.")
476
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
477
+ connect_timeout_s=args.connect_timeout,
478
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
479
+ await get_device_capabilities(client, timeout_s=3.0)
480
+ info = await update_firmware(
481
+ client, data,
482
+ trusted_public_key=public_key, allow_test_firmware=args.allow_test_firmware,
483
+ progress=ProgressPrinter(prefix="OTA transfer"),
484
+ timeout_s=args.timeout, total_timeout_s=args.total_timeout,
485
+ reboot_timeout_s=args.reboot_timeout,
486
+ )
487
+ print(f"Firmware update verified after reboot: {info.firmware_version}")
488
+
489
+
490
+ async def cmd_audio_decode(args: argparse.Namespace) -> None:
491
+ data = args.input.read_bytes()
492
+ playable = build_playable_audio(
493
+ data,
494
+ pcm_config=pcm_config_from_args(args),
495
+ quality=args.speex_quality,
496
+ bits_size=args.speex_bits_size,
497
+ allow_framed_blocks=args.allow_framed_blocks,
498
+ ffmpeg_path=args.ffmpeg,
499
+ )
500
+ args.output.parent.mkdir(parents=True, exist_ok=True)
501
+ args.output.write_bytes(playable.bytes)
502
+ print(f"decoded recording saved: {args.output} ({len(playable.bytes)} bytes)")
503
+ print(f"audio format: {playable.description or playable.label}")
504
+
505
+
506
+ async def cmd_audio_clear(args: argparse.Namespace) -> None:
507
+ if not args.yes:
508
+ raise SystemExit("Refusing to clear audio files without --yes.")
509
+
510
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
511
+ connect_timeout_s=args.connect_timeout,
512
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
513
+ await clear_audio_files(client)
514
+ print("audio files cleared")
515
+
516
+
517
+ async def cmd_log_storage(args: argparse.Namespace) -> None:
518
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
519
+ connect_timeout_s=args.connect_timeout,
520
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
521
+ storage = await get_log_storage(client)
522
+ print(f"page_size: {storage.page_size}")
523
+ print(f"total_len: {storage.total_len}")
524
+
525
+
526
+ async def cmd_log_read(args: argparse.Namespace) -> None:
527
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
528
+ connect_timeout_s=args.connect_timeout,
529
+ allow_unverified_features=getattr(args, "allow_unverified_features", False)) as client:
530
+ data = await read_log_chunk(client, args.index, args.offset, args.size)
531
+
532
+ if args.output:
533
+ args.output.write_bytes(data)
534
+ print(f"wrote {len(data)} bytes to {args.output}")
535
+ return
536
+
537
+ if args.text:
538
+ print(data.decode(args.encoding, errors="replace"))
539
+ else:
540
+ print(data.hex(" "))
541
+
542
+
543
+ def build_parser() -> argparse.ArgumentParser:
544
+ parser = argparse.ArgumentParser(
545
+ description="OpenZilo device CLI.",
546
+ epilog="Quick start: scan → device use ADDRESS → info → shell. See docs/cli.zh-CN.md.",
547
+ )
548
+ parser.add_argument("--version", action="version", version=__version__)
549
+ subparsers = parser.add_subparsers(dest="command", required=True)
550
+
551
+ device = subparsers.add_parser("device", help="Select, show or forget the default ring.")
552
+ device_commands = device.add_subparsers(dest="action", required=True)
553
+ use = device_commands.add_parser("use", help="Save an address, or scan and select interactively.")
554
+ use.add_argument("address", nargs="?", help="BLE address/UUID; omit to scan and choose.")
555
+ use.add_argument("--timeout", type=positive_seconds, default=DEFAULT_SCAN_TIMEOUT_S)
556
+ use.set_defaults(func=cmd_device)
557
+ for action in ("show", "forget"):
558
+ device_commands.add_parser(action).set_defaults(func=cmd_device)
559
+
560
+ capabilities = device_commands.add_parser("capabilities", help="Query device contracts and limits as JSON.")
561
+ add_connection_args(capabilities)
562
+ capabilities.add_argument("--timeout", type=positive_seconds, default=3.0)
563
+ capabilities.set_defaults(func=cmd_capabilities)
564
+ doctor = subparsers.add_parser("doctor", help="Report SDK identity, device contracts and decoder availability.")
565
+ add_connection_args(doctor)
566
+ doctor.add_argument("--timeout", type=positive_seconds, default=3.0)
567
+ doctor.set_defaults(func=cmd_capabilities)
568
+
569
+ shell = subparsers.add_parser("shell", help="Interactive device terminal; help and exit are built in.")
570
+ shell.add_argument("--address", help="Override the default device for this shell.")
571
+ shell.set_defaults(func=cmd_shell)
572
+
573
+ sensor = subparsers.add_parser("sensor-stream", help="Capture IMU batches as JSON lines, then stop reports.")
574
+ add_connection_args(sensor)
575
+ sensor.add_argument("--seconds", type=positive_seconds, default=10.0)
576
+ sensor.add_argument("--output", type=Path, help="Write JSONL to a file instead of stdout.")
577
+ sensor.add_argument("--calibrated", action="store_true", help="Apply a matching local software profile; output g and deg/s.")
578
+ sensor.add_argument("--calibration-profile", type=Path, help="Profile JSON override for --calibrated.")
579
+ sensor.set_defaults(func=cmd_sensor_stream)
580
+
581
+ calibration = subparsers.add_parser("imu-calibrate", help="Local software IMU calibration; no firmware writes.")
582
+ add_connection_args(calibration)
583
+ calibration.add_argument("action", choices=("show", "accel", "quick", "full", "reset"))
584
+ calibration.add_argument("--seconds", type=positive_seconds, default=5.0,
585
+ help="Static seconds per face; quick uses at least 20 seconds.")
586
+ calibration.add_argument("--profile", type=Path, help="Override local calibration JSON path.")
587
+ calibration.set_defaults(func=cmd_imu_calibration)
588
+
589
+ scan = subparsers.add_parser("scan", help="Scan nearby devices.")
590
+ scan.add_argument("--address", default=None, help="Target device address/identifier; return as soon as found.")
591
+ scan.add_argument("--timeout", type=positive_seconds, default=DEFAULT_SCAN_TIMEOUT_S)
592
+ scan.set_defaults(func=cmd_scan)
593
+
594
+ connect = subparsers.add_parser("connect", help="Connect and disconnect once.")
595
+ add_connection_args(connect)
596
+ connect.set_defaults(func=cmd_connect)
597
+
598
+ info = subparsers.add_parser("info", help="Print system information.")
599
+ add_connection_args(info)
600
+ info.set_defaults(func=cmd_info)
601
+
602
+ rssi = subparsers.add_parser("rssi", help="Read the ring's received connection RSSI in dBm.")
603
+ add_connection_args(rssi)
604
+ rssi.add_argument("--timeout", type=positive_seconds, default=3.0)
605
+ rssi.set_defaults(func=cmd_rssi)
606
+
607
+ time_sync = subparsers.add_parser(
608
+ "time-sync",
609
+ help="Auto-respond to device time-sync requests.",
610
+ )
611
+ add_connection_args(time_sync)
612
+ time_sync.add_argument("--seconds", type=float, default=30.0)
613
+ time_sync.set_defaults(func=cmd_time_sync)
614
+
615
+ audio_count = subparsers.add_parser(
616
+ "audio-count",
617
+ help="Print stored audio file count.",
618
+ )
619
+ add_connection_args(audio_count)
620
+ audio_count.set_defaults(func=cmd_audio_count)
621
+
622
+ def recording_options(command):
623
+ command.add_argument("--destination", choices=("auto", "flash", "live", "both"))
624
+ command.add_argument("--disconnect", choices=("stop", "save"))
625
+ command.add_argument("--channels", type=int, choices=(1, 2))
626
+ command.add_argument("--bitrate", type=int)
627
+ command.add_argument("--gain-left-q8", type=int)
628
+ command.add_argument("--gain-right-q8", type=int)
629
+ command.add_argument("--max-duration-ms", type=int)
630
+
631
+ audio_config = subparsers.add_parser("audio-config", help="Read/set volatile recording defaults (extended firmware).")
632
+ add_connection_args(audio_config)
633
+ recording_options(audio_config)
634
+ audio_config.set_defaults(func=cmd_audio_config)
635
+
636
+ audio_status = subparsers.add_parser("audio-status", help="Read the latest recording session state.")
637
+ add_connection_args(audio_status)
638
+ audio_status.set_defaults(func=cmd_audio_status)
639
+
640
+ audio_stop = subparsers.add_parser("audio-stop", help="Stop/cancel a recording session and confirm completion.")
641
+ add_connection_args(audio_stop)
642
+ audio_stop.add_argument("session_id", type=int)
643
+ audio_stop.add_argument("--cancel", action="store_true")
644
+ audio_stop.set_defaults(func=cmd_audio_stop)
645
+
646
+ audio_record = subparsers.add_parser("audio-record", help="Remotely record, stop and save the result.")
647
+ add_connection_args(audio_record)
648
+ recording_options(audio_record)
649
+ audio_record.set_defaults(destination="flash", disconnect="stop", func=cmd_audio_record)
650
+ audio_record.add_argument("output", type=Path)
651
+ audio_record.add_argument("--seconds", type=float, default=5.0)
652
+ audio_record.add_argument("--ffmpeg", default="ffmpeg")
653
+
654
+ audio_download = subparsers.add_parser(
655
+ "audio-download",
656
+ help="Download one audio file.",
657
+ )
658
+ add_connection_args(audio_download)
659
+ audio_download.add_argument("file_index", type=int)
660
+ audio_download.add_argument("output", type=Path)
661
+ audio_download.add_argument("--timeout", type=float, default=30.0)
662
+ add_audio_decode_args(audio_download)
663
+ audio_download.set_defaults(func=cmd_audio_download)
664
+
665
+ for name, handler, description in (
666
+ ("audio-receive", cmd_audio_receive, "Wait for a saved recording and download it (old/new firmware)."),
667
+ ("audio-live", cmd_audio_live, "Receive live Opus; Flash retention follows device configuration."),
668
+ ):
669
+ audio_receive = subparsers.add_parser(name, help=description)
670
+ add_connection_args(audio_receive)
671
+ audio_receive.add_argument("output", type=Path)
672
+ audio_receive.add_argument("--timeout", type=float, default=60.0)
673
+ audio_receive.add_argument("--ffmpeg", default="ffmpeg")
674
+ audio_receive.set_defaults(func=handler)
675
+
676
+ inspect = subparsers.add_parser("ota-inspect", help="Verify a firmware ZIP and display all metadata without BLE.")
677
+ inspect.add_argument("firmware", type=Path)
678
+ inspect.add_argument("--public-key", type=Path, required=True, help="Independently trusted PEM P-256 public key.")
679
+ inspect.add_argument("--json", action="store_true", help="Print verified metadata as JSON.")
680
+ inspect.set_defaults(func=cmd_ota_inspect)
681
+
682
+ ota = subparsers.add_parser(
683
+ "ota-update", help="Install an official APP update package and verify the running version.",
684
+ )
685
+ add_connection_args(ota)
686
+ ota.add_argument("firmware", type=Path, help="Signed APP OTA ZIP containing verified release metadata.")
687
+ ota.add_argument("--public-key", type=Path, required=True, help="Independently trusted PEM P-256 public key for ZIPs.")
688
+ ota.add_argument("--allow-test-firmware", action="store_true", help="Permit signed test-profile firmware.")
689
+ ota.add_argument("--timeout", type=float, default=30.0, help="Per-operation timeout in seconds.")
690
+ ota.add_argument("--total-timeout", type=float, default=600.0, help="Overall transfer time limit.")
691
+ ota.add_argument("--reboot-timeout", type=float, default=90.0, help="Reboot and verification time limit.")
692
+ ota.set_defaults(func=cmd_ota_update)
693
+
694
+ audio_decode = subparsers.add_parser(
695
+ "audio-decode",
696
+ help="Decode a downloaded recording bin into WAV.",
697
+ )
698
+ audio_decode.add_argument("input", type=Path)
699
+ audio_decode.add_argument("output", type=Path)
700
+ add_audio_decode_args(audio_decode)
701
+ audio_decode.set_defaults(func=cmd_audio_decode)
702
+
703
+ audio_clear = subparsers.add_parser(
704
+ "audio-clear",
705
+ help="Clear all stored audio files.",
706
+ )
707
+ add_connection_args(audio_clear)
708
+ audio_clear.add_argument("--yes", action="store_true", help="Confirm clearing.")
709
+ audio_clear.set_defaults(func=cmd_audio_clear)
710
+
711
+ log_storage = subparsers.add_parser("log-storage", help="Print log storage info.")
712
+ add_connection_args(log_storage)
713
+ log_storage.set_defaults(func=cmd_log_storage)
714
+
715
+ log_read = subparsers.add_parser("log-read", help="Read one log chunk.")
716
+ add_connection_args(log_read)
717
+ log_read.add_argument("index", type=int)
718
+ log_read.add_argument("offset", type=int)
719
+ log_read.add_argument("size", type=int)
720
+ log_read.add_argument("--output", type=Path, default=None)
721
+ log_read.add_argument("--text", action="store_true", help="Decode as text.")
722
+ log_read.add_argument("--encoding", default="utf-8")
723
+ log_read.set_defaults(func=cmd_log_read)
724
+
725
+ return parser
726
+
727
+
728
+ async def dispatch(args: argparse.Namespace, *, fallback_address: str | None = None) -> None:
729
+ if getattr(args, "needs_device", False):
730
+ args.address = args.address or fallback_address or os.environ.get("OPENZILO_ADDRESS") or load_address()
731
+ if not args.address or not args.address.strip():
732
+ raise ValueError("No device selected. Run 'openzilo device use', set OPENZILO_ADDRESS, or pass --address.")
733
+ await args.func(args)
734
+
735
+
736
+ async def main() -> None:
737
+ parser = build_parser()
738
+ args = parser.parse_args()
739
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
740
+ await dispatch(args)
741
+
742
+
743
+ def run() -> None:
744
+ try:
745
+ asyncio.run(main())
746
+ except KeyboardInterrupt:
747
+ print("Interrupted.", file=sys.stderr)
748
+ raise SystemExit(130) from None
749
+ except (OpenZiloError, OSError, ValueError, RuntimeError, EOFError) as exc:
750
+ print(f"Error: {exc}", file=sys.stderr)
751
+ raise SystemExit(1) from None