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/__init__.py +302 -0
- openzilo/__main__.py +4 -0
- openzilo/_audio.py +670 -0
- openzilo/_cli.py +751 -0
- openzilo/_cli_calibration.py +224 -0
- openzilo/_cli_config.py +46 -0
- openzilo/_client.py +364 -0
- openzilo/_codec.py +813 -0
- openzilo/_compatibility.py +209 -0
- openzilo/_device.py +243 -0
- openzilo/_errors.py +73 -0
- openzilo/_firmware_bundle.py +124 -0
- openzilo/_identity.py +23 -0
- openzilo/_imu_calibration.py +251 -0
- openzilo/_imu_profiles.py +194 -0
- openzilo/_live_audio.py +422 -0
- openzilo/_ota.py +257 -0
- openzilo/_pcm.py +87 -0
- openzilo/_protocol.py +303 -0
- openzilo/_recording.py +250 -0
- openzilo/_sensor.py +251 -0
- openzilo/_tasks.py +67 -0
- openzilo/_transport.py +371 -0
- openzilo/_version.py +2 -0
- openzilo-0.6.3.dist-info/METADATA +225 -0
- openzilo-0.6.3.dist-info/RECORD +30 -0
- openzilo-0.6.3.dist-info/WHEEL +5 -0
- openzilo-0.6.3.dist-info/entry_points.txt +2 -0
- openzilo-0.6.3.dist-info/licenses/LICENSE +373 -0
- openzilo-0.6.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Capability discovery v1. Product release strings are opaque identifiers."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import struct
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from ._errors import CompatibilityError, DeviceError, ProtocolError, TimeoutError, TransportError
|
|
10
|
+
from ._protocol import BinaryReader, SystemCommand, ensure_success
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from ._client import OpenZiloClient
|
|
14
|
+
from ._recording import AudioRecordingConfig
|
|
15
|
+
|
|
16
|
+
# These are contract versions, not firmware versions. IMU v2 starts capture on
|
|
17
|
+
# subscription; v1 required a separate gesture mode and is not interchangeable.
|
|
18
|
+
FEATURE_MAJORS = {"system": 1, "time_sync": 1, "audio_files": 1,
|
|
19
|
+
"recording_control": 1, "live_audio": 1, "imu": 2,
|
|
20
|
+
"key_events": 1, "double_tap": 1, "ota": 1, "gesture": 1,
|
|
21
|
+
"connection_rssi": 1}
|
|
22
|
+
FEATURE_NAMES = {1: "system", 2: "time_sync", 3: "audio_files", 4: "recording_control",
|
|
23
|
+
5: "live_audio", 6: "imu", 7: "key_events", 8: "double_tap",
|
|
24
|
+
9: "ota", 10: "gesture", 11: "imu_calibration", 12: "connection_rssi"}
|
|
25
|
+
_LIMITS = struct.Struct(">HHBBBBIIHHHHH")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class FeatureVersion:
|
|
30
|
+
name: str
|
|
31
|
+
major: int
|
|
32
|
+
minor: int
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class RecordingLimits:
|
|
37
|
+
sample_rate_hz: int
|
|
38
|
+
frame_duration_ms: int
|
|
39
|
+
channels_mask: int
|
|
40
|
+
outputs_mask: int
|
|
41
|
+
continue_outputs_mask: int
|
|
42
|
+
bitrate_min: int
|
|
43
|
+
bitrate_max: int
|
|
44
|
+
gain_min_q8: int
|
|
45
|
+
gain_max_q8: int
|
|
46
|
+
duration_min_ms: int
|
|
47
|
+
duration_max_ms: int
|
|
48
|
+
duration_step_ms: int
|
|
49
|
+
|
|
50
|
+
def validate(self, config: AudioRecordingConfig) -> None:
|
|
51
|
+
c = config
|
|
52
|
+
if not (c.sample_rate == self.sample_rate_hz and c.frame_duration_ms == self.frame_duration_ms
|
|
53
|
+
and 0 <= c.channels < 8 and self.channels_mask & (1 << c.channels)
|
|
54
|
+
and 0 <= int(c.output) < 8 and self.outputs_mask & (1 << int(c.output))
|
|
55
|
+
and self.bitrate_min <= c.bitrate <= self.bitrate_max
|
|
56
|
+
and self.gain_min_q8 <= c.gain_left_q8 <= self.gain_max_q8
|
|
57
|
+
and self.gain_min_q8 <= c.gain_right_q8 <= self.gain_max_q8
|
|
58
|
+
and (c.max_duration_ms == 0 or
|
|
59
|
+
self.duration_min_ms <= c.max_duration_ms <= self.duration_max_ms)
|
|
60
|
+
and c.max_duration_ms % self.duration_step_ms == 0
|
|
61
|
+
and (int(c.disconnect_policy) == 0 or
|
|
62
|
+
self.continue_outputs_mask & (1 << int(c.output)))):
|
|
63
|
+
raise CompatibilityError("Recording configuration exceeds device capabilities")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class DeviceCapabilities:
|
|
68
|
+
source: str # device, legacy_profile, unknown
|
|
69
|
+
firmware_version: str
|
|
70
|
+
model: str
|
|
71
|
+
board_target: str | None = None
|
|
72
|
+
build_id: str | None = None
|
|
73
|
+
boot_id: str | None = None
|
|
74
|
+
protocol_versions: tuple[int, ...] = ()
|
|
75
|
+
features: tuple[FeatureVersion, ...] = ()
|
|
76
|
+
recording_limits: RecordingLimits | None = None
|
|
77
|
+
reason: str | None = None
|
|
78
|
+
|
|
79
|
+
def supports(self, name: str, *, major: int | None = None, min_minor: int = 0) -> bool:
|
|
80
|
+
expected = FEATURE_MAJORS.get(name) if major is None else major
|
|
81
|
+
return any(f.name == name and f.major == expected and f.minor >= min_minor
|
|
82
|
+
for f in self.features)
|
|
83
|
+
|
|
84
|
+
def require(self, name: str) -> None:
|
|
85
|
+
if not self.supports(name):
|
|
86
|
+
raise CompatibilityError(
|
|
87
|
+
f"{name} contract is unavailable or unknown on {self.firmware_version} "
|
|
88
|
+
f"(source={self.source}); inspect device capabilities or upgrade firmware"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def parse_device_capabilities(body: bytes) -> DeviceCapabilities:
|
|
93
|
+
reader = BinaryReader(body)
|
|
94
|
+
ensure_success(reader.u16())
|
|
95
|
+
if reader.u8() != 1:
|
|
96
|
+
raise CompatibilityError("Unsupported capability schema; SDK upgrade required")
|
|
97
|
+
fields: dict[int, bytes] = {}
|
|
98
|
+
while reader.remaining:
|
|
99
|
+
tag, size = reader.u16(), reader.u16()
|
|
100
|
+
value = reader.bytes(size)
|
|
101
|
+
if tag & 0x8000:
|
|
102
|
+
raise CompatibilityError(f"Unknown required capability tag 0x{tag:04X}")
|
|
103
|
+
if tag in fields:
|
|
104
|
+
raise ProtocolError(f"Duplicate capability tag 0x{tag:04X}")
|
|
105
|
+
fields[tag] = value
|
|
106
|
+
for tag in (1, 2, 3, 4, 5, 6):
|
|
107
|
+
if not fields.get(tag):
|
|
108
|
+
raise ProtocolError(f"Missing capability tag {tag}")
|
|
109
|
+
try:
|
|
110
|
+
firmware, model, board, build = (fields[t].decode("utf-8", errors="strict")
|
|
111
|
+
for t in (1, 2, 3, 5))
|
|
112
|
+
except UnicodeDecodeError as exc:
|
|
113
|
+
raise ProtocolError("Invalid UTF-8 capability identity") from exc
|
|
114
|
+
if len(fields[4]) != 8 or len(fields[6]) % 2:
|
|
115
|
+
raise ProtocolError("Invalid boot identity or protocol list")
|
|
116
|
+
protocols = tuple(v[0] for v in struct.iter_unpack(">H", fields[6]))
|
|
117
|
+
if 4 not in protocols:
|
|
118
|
+
raise CompatibilityError("Device does not advertise protocol v4")
|
|
119
|
+
features = []
|
|
120
|
+
for tag, value in fields.items():
|
|
121
|
+
if 0x100 < tag <= 0x1FF:
|
|
122
|
+
if len(value) != 2 or value[0] == 0:
|
|
123
|
+
raise ProtocolError("Invalid feature contract")
|
|
124
|
+
name = FEATURE_NAMES.get(tag - 0x100, f"unknown_{tag - 0x100}")
|
|
125
|
+
features.append(FeatureVersion(name, *value))
|
|
126
|
+
limits = None
|
|
127
|
+
if 0x204 in fields:
|
|
128
|
+
if len(fields[0x204]) != _LIMITS.size:
|
|
129
|
+
raise ProtocolError("Invalid recording limits length")
|
|
130
|
+
rate, frame, channels, outputs, continuing, reserved, *ranges = _LIMITS.unpack(fields[0x204])
|
|
131
|
+
limits = RecordingLimits(rate, frame, channels, outputs, continuing, *ranges)
|
|
132
|
+
if (reserved or not rate or not frame or not channels or not outputs
|
|
133
|
+
or continuing & ~outputs or not limits.duration_step_ms
|
|
134
|
+
or limits.bitrate_min > limits.bitrate_max
|
|
135
|
+
or limits.gain_min_q8 > limits.gain_max_q8
|
|
136
|
+
or limits.duration_min_ms > limits.duration_max_ms):
|
|
137
|
+
raise ProtocolError("Invalid recording limits")
|
|
138
|
+
if any(f.name == "recording_control" and f.major == 1 for f in features):
|
|
139
|
+
if limits is None:
|
|
140
|
+
raise ProtocolError("Recording control v1 requires limits")
|
|
141
|
+
if limits.sample_rate_hz != 16000 or limits.frame_duration_ms != 20:
|
|
142
|
+
raise CompatibilityError("Recording contract v1 requires 16 kHz / 20 ms")
|
|
143
|
+
return DeviceCapabilities("device", firmware, model, board, build, fields[4].hex(),
|
|
144
|
+
protocols, tuple(features), limits)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _legacy_capabilities(firmware: str, model: str, reason: str) -> DeviceCapabilities:
|
|
148
|
+
# Exact released product build, validated in the 0001 hardware test report.
|
|
149
|
+
# No prefix/range matching: customer IDs are not semantic patch versions.
|
|
150
|
+
if firmware == "V2.001.0002.0001-prod-7fd1dfc9" and model == "Open Zilo":
|
|
151
|
+
return DeviceCapabilities(
|
|
152
|
+
"legacy_profile", firmware, model, board_target="ring_dvt2/nrf54l15/cpuapp",
|
|
153
|
+
build_id="7fd1dfc9e9c698c47b91e100580deddde66f210e",
|
|
154
|
+
protocol_versions=(4,),
|
|
155
|
+
features=tuple(FeatureVersion(n, m, 0) for n, m in (
|
|
156
|
+
("system", 1), ("time_sync", 1), ("audio_files", 1), ("recording_control", 1),
|
|
157
|
+
("live_audio", 1), ("imu", 2), ("key_events", 1), ("double_tap", 1), ("ota", 1))),
|
|
158
|
+
recording_limits=RecordingLimits(16000, 20, 6, 15, 10, 8000, 32000, 0, 1024, 20, 60000, 20),
|
|
159
|
+
reason=reason,
|
|
160
|
+
)
|
|
161
|
+
return DeviceCapabilities("unknown", firmware, model, reason=reason)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
async def get_device_capabilities(
|
|
165
|
+
client: OpenZiloClient, *, timeout_s: float | None = None, refresh: bool = False,
|
|
166
|
+
) -> DeviceCapabilities:
|
|
167
|
+
"""Discover once per connection. Timeout is unknown, never unsupported.
|
|
168
|
+
|
|
169
|
+
Legacy requests lack transaction IDs. Discovery is serialized and timeout
|
|
170
|
+
fallback is cached until reconnect to avoid same-connection retry ambiguity.
|
|
171
|
+
"""
|
|
172
|
+
from ._device import get_system_info
|
|
173
|
+
async with client._capability_lock:
|
|
174
|
+
if client.capabilities is not None and not refresh:
|
|
175
|
+
return client.capabilities
|
|
176
|
+
if client.capabilities is not None and client.capabilities.source != "device":
|
|
177
|
+
raise CompatibilityError("Reconnect before retrying legacy/unknown discovery")
|
|
178
|
+
client._capability_check_required = True
|
|
179
|
+
client.capabilities = None
|
|
180
|
+
connection = client._connection_token
|
|
181
|
+
info = await get_system_info(client, timeout_s=timeout_s)
|
|
182
|
+
try:
|
|
183
|
+
packet = await client.request(SystemCommand.GET_CAPABILITIES,
|
|
184
|
+
SystemCommand.CAPABILITIES_RESP, timeout_s=timeout_s)
|
|
185
|
+
except TimeoutError:
|
|
186
|
+
result = _legacy_capabilities(info.firmware_version, info.model,
|
|
187
|
+
"Capability discovery timed out; support is unknown")
|
|
188
|
+
except DeviceError as exc:
|
|
189
|
+
if exc.error_code != 5: # existing CMD_NOT_EXIST
|
|
190
|
+
raise
|
|
191
|
+
result = _legacy_capabilities(info.firmware_version, info.model,
|
|
192
|
+
"Device explicitly rejected capability discovery")
|
|
193
|
+
else:
|
|
194
|
+
result = parse_device_capabilities(packet.body)
|
|
195
|
+
if result.firmware_version != info.firmware_version or result.model != info.model:
|
|
196
|
+
raise ProtocolError("Capability identity differs from system information")
|
|
197
|
+
if connection is None or connection is not client._connection_token:
|
|
198
|
+
raise TransportError("Connection changed during capability discovery")
|
|
199
|
+
client.capabilities = result
|
|
200
|
+
return result
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# Only enhanced commands are guarded. Basic info, logs, file retrieval and time
|
|
204
|
+
# replies retain their existing baseline behaviour on unrecognized old devices.
|
|
205
|
+
COMMAND_FEATURES = {0x0107: "connection_rssi",
|
|
206
|
+
**{c: "recording_control" for c in (0x0512, 0x0514, 0x0516, 0x0518, 0x051A)},
|
|
207
|
+
0x050D: "live_audio", 0x0601: "imu", 0x0603: "imu", 0x0605: "imu",
|
|
208
|
+
0x0701: "double_tap", 0x0702: "gesture",
|
|
209
|
+
0x0703: "key_events", 0x0704: "key_events", 1005: "ota"}
|
openzilo/_device.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Connection helpers and device-level operations: system info, logs and time sync."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import math
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Awaitable, Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from ._protocol import (
|
|
13
|
+
BinaryReader,
|
|
14
|
+
BinaryWriter,
|
|
15
|
+
ensure_success,
|
|
16
|
+
LogCommand,
|
|
17
|
+
Packet,
|
|
18
|
+
read_error,
|
|
19
|
+
SystemCommand,
|
|
20
|
+
TimeCommand,
|
|
21
|
+
)
|
|
22
|
+
from ._transport import BleDeviceInfo, DEFAULT_SCAN_TIMEOUT_S
|
|
23
|
+
from ._client import DEFAULT_COMMAND_TIMEOUT_S, OpenZiloClient
|
|
24
|
+
from ._errors import ProtocolError, TimeoutError, TransportError
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class SystemInfo:
|
|
29
|
+
firmware_version: str
|
|
30
|
+
system_time: int
|
|
31
|
+
audio_storage_total: int
|
|
32
|
+
audio_storage_available: int
|
|
33
|
+
battery_percent: int
|
|
34
|
+
battery_charging: bool
|
|
35
|
+
sn: str
|
|
36
|
+
cpuid: str
|
|
37
|
+
model: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class LogStorageInfo:
|
|
42
|
+
page_size: int
|
|
43
|
+
total_len: int
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def scan_rings(
|
|
47
|
+
*,
|
|
48
|
+
address: str | None = None,
|
|
49
|
+
timeout_s: float = DEFAULT_SCAN_TIMEOUT_S,
|
|
50
|
+
on_devices_changed: Callable[[list[BleDeviceInfo]], None] | None = None,
|
|
51
|
+
) -> list[BleDeviceInfo]:
|
|
52
|
+
"""Scan ring candidates, or locate an explicit device address/identifier."""
|
|
53
|
+
return await OpenZiloClient.discover(
|
|
54
|
+
address=address,
|
|
55
|
+
timeout_s=timeout_s,
|
|
56
|
+
on_devices_changed=on_devices_changed,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def connect_ring(
|
|
61
|
+
*,
|
|
62
|
+
address: str | None = None,
|
|
63
|
+
device: BleDeviceInfo | None = None,
|
|
64
|
+
scan_timeout_s: float = DEFAULT_SCAN_TIMEOUT_S,
|
|
65
|
+
connect_timeout_s: float = 30.0,
|
|
66
|
+
command_timeout_s: float = DEFAULT_COMMAND_TIMEOUT_S,
|
|
67
|
+
auto_time_sync: bool = False,
|
|
68
|
+
negotiate_capabilities: bool = True,
|
|
69
|
+
allow_unverified_features: bool = False,
|
|
70
|
+
) -> OpenZiloClient:
|
|
71
|
+
"""Create and connect a OpenZiloClient."""
|
|
72
|
+
client = OpenZiloClient(
|
|
73
|
+
address=address,
|
|
74
|
+
device=device,
|
|
75
|
+
scan_timeout_s=scan_timeout_s,
|
|
76
|
+
connect_timeout_s=connect_timeout_s,
|
|
77
|
+
command_timeout_s=command_timeout_s,
|
|
78
|
+
allow_unverified_features=allow_unverified_features,
|
|
79
|
+
)
|
|
80
|
+
if auto_time_sync:
|
|
81
|
+
enable_time_sync(client)
|
|
82
|
+
await client.connect()
|
|
83
|
+
try:
|
|
84
|
+
if negotiate_capabilities:
|
|
85
|
+
from ._compatibility import get_device_capabilities
|
|
86
|
+
await get_device_capabilities(client, timeout_s=min(command_timeout_s, 3.0))
|
|
87
|
+
except BaseException:
|
|
88
|
+
await client.disconnect()
|
|
89
|
+
raise
|
|
90
|
+
return client
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def get_system_info(
|
|
94
|
+
client: OpenZiloClient,
|
|
95
|
+
*,
|
|
96
|
+
timeout_s: float | None = None,
|
|
97
|
+
) -> SystemInfo:
|
|
98
|
+
packet = await client.request(
|
|
99
|
+
SystemCommand.GET_INFO,
|
|
100
|
+
SystemCommand.INFO_RESP,
|
|
101
|
+
timeout_s=timeout_s,
|
|
102
|
+
)
|
|
103
|
+
return parse_system_info(packet.body)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
async def get_connection_rssi(
|
|
107
|
+
client: OpenZiloClient,
|
|
108
|
+
*,
|
|
109
|
+
timeout_s: float | None = None,
|
|
110
|
+
) -> int:
|
|
111
|
+
"""Read the ring's received connection signal strength in dBm."""
|
|
112
|
+
from ._compatibility import get_device_capabilities
|
|
113
|
+
if timeout_s is not None and (not math.isfinite(timeout_s) or timeout_s <= 0):
|
|
114
|
+
raise ValueError("timeout_s must be finite and positive")
|
|
115
|
+
await get_device_capabilities(client, timeout_s=timeout_s)
|
|
116
|
+
async with client._rssi_lock:
|
|
117
|
+
connection = client._connection_token
|
|
118
|
+
if connection is not None and client._rssi_failed_connection is connection:
|
|
119
|
+
raise TransportError("Reconnect before retrying an ambiguous RSSI query")
|
|
120
|
+
try:
|
|
121
|
+
packet = await client.request(
|
|
122
|
+
SystemCommand.GET_RSSI, SystemCommand.RSSI_RESP, timeout_s=timeout_s,
|
|
123
|
+
)
|
|
124
|
+
if connection is None or connection is not client._connection_token:
|
|
125
|
+
raise TransportError("Connection changed during RSSI query")
|
|
126
|
+
reader = BinaryReader(packet.body)
|
|
127
|
+
error = reader.u16()
|
|
128
|
+
if error:
|
|
129
|
+
if reader.remaining:
|
|
130
|
+
raise ProtocolError("Invalid RSSI error response length")
|
|
131
|
+
ensure_success(error)
|
|
132
|
+
if reader.remaining != 1:
|
|
133
|
+
raise ProtocolError("Invalid RSSI response length")
|
|
134
|
+
rssi = int.from_bytes(reader.bytes(1), "big", signed=True)
|
|
135
|
+
if not -127 <= rssi <= 20:
|
|
136
|
+
raise ProtocolError("RSSI is unavailable or outside the supported range")
|
|
137
|
+
return rssi
|
|
138
|
+
except (TimeoutError, ProtocolError, TransportError, asyncio.CancelledError):
|
|
139
|
+
# No transaction ID distinguishes a late reply from a new query.
|
|
140
|
+
client._rssi_failed_connection = connection
|
|
141
|
+
raise
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def parse_system_info(body: bytes) -> SystemInfo:
|
|
145
|
+
reader = BinaryReader(body)
|
|
146
|
+
ensure_success(read_error(reader))
|
|
147
|
+
firmware_version = reader.string_u16()
|
|
148
|
+
system_time = reader.u32()
|
|
149
|
+
audio_storage_total = reader.u32()
|
|
150
|
+
audio_storage_available = reader.u32()
|
|
151
|
+
battery_percent = reader.u16()
|
|
152
|
+
battery_charging = bool(reader.u8())
|
|
153
|
+
sn = reader.string_u16()
|
|
154
|
+
cpuid = reader.string_u16()
|
|
155
|
+
model = reader.string_u16()
|
|
156
|
+
return SystemInfo(
|
|
157
|
+
firmware_version=firmware_version,
|
|
158
|
+
system_time=system_time,
|
|
159
|
+
audio_storage_total=audio_storage_total,
|
|
160
|
+
audio_storage_available=audio_storage_available,
|
|
161
|
+
battery_percent=battery_percent,
|
|
162
|
+
battery_charging=battery_charging,
|
|
163
|
+
sn=sn,
|
|
164
|
+
cpuid=cpuid,
|
|
165
|
+
model=model,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
async def send_time_response(
|
|
170
|
+
client: OpenZiloClient,
|
|
171
|
+
request_time: int,
|
|
172
|
+
*,
|
|
173
|
+
response_time: int | None = None,
|
|
174
|
+
send_time: int | None = None,
|
|
175
|
+
) -> None:
|
|
176
|
+
"""Reply to a device time-sync request."""
|
|
177
|
+
now = int(time.time())
|
|
178
|
+
body = (
|
|
179
|
+
BinaryWriter()
|
|
180
|
+
.u32(request_time)
|
|
181
|
+
.u32(now if response_time is None else response_time)
|
|
182
|
+
.u32(now if send_time is None else send_time)
|
|
183
|
+
.build()
|
|
184
|
+
)
|
|
185
|
+
await client.send_command(TimeCommand.RESPONSE, body)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def enable_time_sync(client: OpenZiloClient) -> None:
|
|
189
|
+
"""Automatically respond once per request, after its connection is ready."""
|
|
190
|
+
if client._time_sync_enabled:
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
def handle_time_request(packet: Packet) -> Awaitable[None]:
|
|
194
|
+
# Automatic replies consume these requests; do not retain queue copies.
|
|
195
|
+
client._drain_queue(int(TimeCommand.REQUEST))
|
|
196
|
+
reader = BinaryReader(packet.body)
|
|
197
|
+
request_time = reader.u32()
|
|
198
|
+
response_time = int(time.time())
|
|
199
|
+
|
|
200
|
+
def body() -> bytes:
|
|
201
|
+
return (BinaryWriter().u32(request_time).u32(response_time)
|
|
202
|
+
.u32(int(time.time())).build())
|
|
203
|
+
|
|
204
|
+
return client._send_when_ready(TimeCommand.RESPONSE, body, client._connection_token)
|
|
205
|
+
|
|
206
|
+
client.add_packet_handler(TimeCommand.REQUEST, handle_time_request)
|
|
207
|
+
client._time_sync_enabled = True
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
async def get_log_storage(
|
|
211
|
+
client: OpenZiloClient,
|
|
212
|
+
*,
|
|
213
|
+
timeout_s: float | None = None,
|
|
214
|
+
) -> LogStorageInfo:
|
|
215
|
+
packet = await client.request(
|
|
216
|
+
LogCommand.GET_STORAGE,
|
|
217
|
+
LogCommand.STORAGE_RESP,
|
|
218
|
+
timeout_s=timeout_s,
|
|
219
|
+
)
|
|
220
|
+
reader = BinaryReader(packet.body)
|
|
221
|
+
ensure_success(read_error(reader))
|
|
222
|
+
return LogStorageInfo(page_size=reader.u32(), total_len=reader.u32())
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
async def read_log_chunk(
|
|
226
|
+
client: OpenZiloClient,
|
|
227
|
+
index: int,
|
|
228
|
+
offset: int,
|
|
229
|
+
size: int,
|
|
230
|
+
*,
|
|
231
|
+
timeout_s: float | None = None,
|
|
232
|
+
) -> bytes:
|
|
233
|
+
body = BinaryWriter().u32(index).u32(offset).u32(size).build()
|
|
234
|
+
packet = await client.request(
|
|
235
|
+
LogCommand.GET_LOG,
|
|
236
|
+
LogCommand.LOG_RESP,
|
|
237
|
+
body,
|
|
238
|
+
timeout_s=timeout_s,
|
|
239
|
+
)
|
|
240
|
+
reader = BinaryReader(packet.body)
|
|
241
|
+
ensure_success(read_error(reader))
|
|
242
|
+
data_len = reader.u32()
|
|
243
|
+
return reader.bytes(min(data_len, reader.remaining))
|
openzilo/_errors.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Exception types and device error codes."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from enum import IntEnum
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class OpenZiloError(Exception):
|
|
10
|
+
"""Base exception for OpenZilo errors."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TransportError(OpenZiloError):
|
|
14
|
+
"""BLE transport failed."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ProtocolError(OpenZiloError):
|
|
18
|
+
"""Packet framing, CRC, or body parsing failed."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CompatibilityError(OpenZiloError):
|
|
22
|
+
"""Required device contract is unsupported or has not been verified."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TimeoutError(OpenZiloError):
|
|
26
|
+
"""A device response did not arrive in time."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DeviceError(OpenZiloError):
|
|
30
|
+
"""The device returned a non-zero protocol error code."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, error_code: int, message: str | None = None) -> None:
|
|
33
|
+
self.error_code = error_code
|
|
34
|
+
super().__init__(message or f"Device returned error code {error_code}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AudioDecodeError(OpenZiloError):
|
|
38
|
+
"""Audio data could not be decoded into a playable WAV file."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SpeexDecoderUnavailable(AudioDecodeError):
|
|
42
|
+
"""The configured Speex decoder is unavailable."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class OpusDecoderUnavailable(AudioDecodeError):
|
|
46
|
+
"""No Opus decoder is available."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ErrorCode(IntEnum):
|
|
50
|
+
SUCCESS = 0
|
|
51
|
+
UNKNOWN = 1
|
|
52
|
+
DEVICE_BUSY = 2
|
|
53
|
+
FILE_NOT_EXIST = 3
|
|
54
|
+
CMD_GROUP_NOT_EXIST = 4
|
|
55
|
+
CMD_NOT_EXIST = 5
|
|
56
|
+
TIMEOUT = 6
|
|
57
|
+
PARAM_INVALID = 7
|
|
58
|
+
COMMUNICATION = 8
|
|
59
|
+
UNSUPPORTED_SCHEMA = 9
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
ERROR_MESSAGES = {
|
|
63
|
+
ErrorCode.SUCCESS: "success",
|
|
64
|
+
ErrorCode.UNKNOWN: "unknown error",
|
|
65
|
+
ErrorCode.DEVICE_BUSY: "device busy",
|
|
66
|
+
ErrorCode.FILE_NOT_EXIST: "file not exist",
|
|
67
|
+
ErrorCode.CMD_GROUP_NOT_EXIST: "command group not exist",
|
|
68
|
+
ErrorCode.CMD_NOT_EXIST: "command not exist",
|
|
69
|
+
ErrorCode.TIMEOUT: "operation timeout",
|
|
70
|
+
ErrorCode.PARAM_INVALID: "invalid parameter",
|
|
71
|
+
ErrorCode.COMMUNICATION: "communication error",
|
|
72
|
+
ErrorCode.UNSUPPORTED_SCHEMA: "unsupported schema",
|
|
73
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Strict, bounded verification of ring_sound distribution bundles."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import hashlib
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import struct
|
|
11
|
+
import zipfile
|
|
12
|
+
|
|
13
|
+
from cryptography.exceptions import InvalidSignature
|
|
14
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
15
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
16
|
+
|
|
17
|
+
DOMAIN = b"OpenZilo firmware bundle v1\x00"
|
|
18
|
+
MAX_PAYLOAD = 0x7A000 + 32
|
|
19
|
+
VERSION = r"V[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(?:-(?:debug|prod)-[0-9a-fA-F]{8})?"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class FirmwareBundle:
|
|
24
|
+
"""Verified metadata and immutable encrypted OTA bytes; no device checks yet."""
|
|
25
|
+
version: str
|
|
26
|
+
model: str
|
|
27
|
+
board: str
|
|
28
|
+
profile: str
|
|
29
|
+
security_version: int
|
|
30
|
+
source_versions: tuple[str, ...]
|
|
31
|
+
payload: bytes
|
|
32
|
+
signing_key_id: str
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def manifest(self) -> dict:
|
|
36
|
+
"""A fresh JSON-compatible copy of all verified manifest fields."""
|
|
37
|
+
return {
|
|
38
|
+
"schema": 1, "algorithm": "ECDSA-P256-SHA256", "image": "app",
|
|
39
|
+
"version": self.version, "model": self.model, "board": self.board,
|
|
40
|
+
"profile": self.profile, "security_version": self.security_version,
|
|
41
|
+
"source_versions": list(self.source_versions), "key_id": self.signing_key_id,
|
|
42
|
+
"payload": {"file": "app.ota.bin", "format": "RINGENC1", "size": len(self.payload),
|
|
43
|
+
"sha256": hashlib.sha256(self.payload).hexdigest()},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unique_object(pairs):
|
|
48
|
+
result = {}
|
|
49
|
+
for key, value in pairs:
|
|
50
|
+
if key in result:
|
|
51
|
+
raise ValueError("Duplicate manifest field")
|
|
52
|
+
result[key] = value
|
|
53
|
+
return result
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def inspect_firmware_bundle(bundle: bytes, *, trusted_public_key: bytes) -> FirmwareBundle:
|
|
57
|
+
"""Verify a ZIP using an independently trusted PEM P-256 public key.
|
|
58
|
+
|
|
59
|
+
The archive cannot supply its own trust anchor. Only the returned payload
|
|
60
|
+
goes over BLE. Device compatibility remains an update-time check.
|
|
61
|
+
"""
|
|
62
|
+
if not isinstance(bundle, (bytes, bytearray, memoryview)):
|
|
63
|
+
raise TypeError("bundle must contain ZIP bytes")
|
|
64
|
+
if not 0 < len(bundle) <= MAX_PAYLOAD + 32768:
|
|
65
|
+
raise ValueError("Firmware bundle size exceeds limit")
|
|
66
|
+
try:
|
|
67
|
+
with zipfile.ZipFile(io.BytesIO(bundle)) as archive:
|
|
68
|
+
entries = archive.infolist()
|
|
69
|
+
limits = {"manifest.json": 16384, "manifest.sig": 80, "app.ota.bin": MAX_PAYLOAD}
|
|
70
|
+
if len(entries) != 3 or {e.filename for e in entries} != set(limits):
|
|
71
|
+
raise ValueError("Bundle must contain exactly manifest.json, manifest.sig, app.ota.bin")
|
|
72
|
+
for entry in entries:
|
|
73
|
+
if (entry.flag_bits & 1 or entry.compress_type != zipfile.ZIP_STORED
|
|
74
|
+
or not 0 < entry.file_size <= limits[entry.filename]
|
|
75
|
+
or entry.compress_size != entry.file_size):
|
|
76
|
+
raise ValueError("Invalid bundle member size or compression")
|
|
77
|
+
raw, signature, payload = (archive.read(name) for name in limits)
|
|
78
|
+
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError) as exc:
|
|
79
|
+
raise ValueError("Invalid firmware ZIP") from exc
|
|
80
|
+
key = serialization.load_pem_public_key(trusted_public_key)
|
|
81
|
+
if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1):
|
|
82
|
+
raise ValueError("Expected a trusted P-256 public key")
|
|
83
|
+
try:
|
|
84
|
+
key.verify(signature, DOMAIN + raw, ec.ECDSA(hashes.SHA256()))
|
|
85
|
+
except InvalidSignature as exc:
|
|
86
|
+
raise ValueError("Firmware bundle signature verification failed") from exc
|
|
87
|
+
try:
|
|
88
|
+
meta = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object)
|
|
89
|
+
except (UnicodeError, json.JSONDecodeError) as exc:
|
|
90
|
+
raise ValueError("Invalid firmware manifest JSON") from exc
|
|
91
|
+
fields = {"schema", "algorithm", "key_id", "image", "version", "model", "board",
|
|
92
|
+
"profile", "security_version", "source_versions", "payload"}
|
|
93
|
+
if not isinstance(meta, dict) or set(meta) != fields:
|
|
94
|
+
raise ValueError("Invalid firmware manifest fields")
|
|
95
|
+
key_id = hashlib.sha256(key.public_bytes(serialization.Encoding.DER,
|
|
96
|
+
serialization.PublicFormat.SubjectPublicKeyInfo)).hexdigest()
|
|
97
|
+
if (type(meta["schema"]) is not int or meta["schema"] != 1
|
|
98
|
+
or meta["algorithm"] != "ECDSA-P256-SHA256" or meta["image"] != "app"
|
|
99
|
+
or meta["key_id"] != key_id):
|
|
100
|
+
raise ValueError("Unsupported firmware manifest or signing key ID")
|
|
101
|
+
for name in ("version", "model", "board", "profile"):
|
|
102
|
+
if not isinstance(meta[name], str) or not meta[name] or len(meta[name]) > 128:
|
|
103
|
+
raise ValueError(f"Invalid manifest {name}")
|
|
104
|
+
if not re.fullmatch(VERSION, meta["version"]) or len(meta["version"]) > 63:
|
|
105
|
+
raise ValueError("Invalid manifest version")
|
|
106
|
+
if meta["profile"] not in ("test", "production"):
|
|
107
|
+
raise ValueError("Invalid manifest profile")
|
|
108
|
+
if type(meta["security_version"]) is not int or not 1 <= meta["security_version"] <= 0x7FFFFFFF:
|
|
109
|
+
raise ValueError("Invalid manifest security version")
|
|
110
|
+
sources = meta["source_versions"]
|
|
111
|
+
if not isinstance(sources, list) or len(sources) > 64 or any(
|
|
112
|
+
not isinstance(v, str) or len(v) > 63 or not re.fullmatch(VERSION, v) for v in sources):
|
|
113
|
+
raise ValueError("Invalid manifest source versions")
|
|
114
|
+
info = meta["payload"]
|
|
115
|
+
if (not isinstance(info, dict) or set(info) != {"file", "size", "sha256", "format"}
|
|
116
|
+
or info["file"] != "app.ota.bin" or info["format"] != "RINGENC1"
|
|
117
|
+
or type(info["size"]) is not int or info["size"] != len(payload)
|
|
118
|
+
or info["sha256"] != hashlib.sha256(payload).hexdigest()):
|
|
119
|
+
raise ValueError("Firmware payload size or SHA-256 mismatch")
|
|
120
|
+
if (len(payload) <= 32 or payload[:8] != b"RINGENC1"
|
|
121
|
+
or struct.unpack_from("<II", payload, 8) != (1, len(payload) - 32)):
|
|
122
|
+
raise ValueError("Invalid encrypted APP header")
|
|
123
|
+
return FirmwareBundle(meta["version"], meta["model"], meta["board"], meta["profile"],
|
|
124
|
+
meta["security_version"], tuple(sources), payload, key_id)
|
openzilo/_identity.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Reproducible SDK source identity, including editable installations."""
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from hashlib import sha256
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from ._version import __version__
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class SdkIdentity:
|
|
10
|
+
version: str
|
|
11
|
+
source_sha256: str
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_sdk_identity() -> SdkIdentity:
|
|
15
|
+
"""Hash package Python sources only; never inspect device/user configuration."""
|
|
16
|
+
digest = sha256()
|
|
17
|
+
package = Path(__file__).parent
|
|
18
|
+
for source in sorted(package.rglob("*.py")):
|
|
19
|
+
digest.update(source.relative_to(package).as_posix().encode("utf-8") + b"\0")
|
|
20
|
+
content = source.read_bytes()
|
|
21
|
+
digest.update(len(content).to_bytes(8, "big"))
|
|
22
|
+
digest.update(content)
|
|
23
|
+
return SdkIdentity(__version__, digest.hexdigest())
|