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
openzilo/_audio.py
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Saved recording transfer: listing, downloading and automatic receive."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from enum import IntEnum
|
|
10
|
+
from functools import wraps
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ._errors import ProtocolError, TimeoutError, TransportError
|
|
14
|
+
from ._protocol import AudioCommand, BinaryReader, BinaryWriter, ensure_success, Packet, read_error
|
|
15
|
+
from ._client import OpenZiloClient
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class AudioFileInfo:
|
|
20
|
+
file_index: int
|
|
21
|
+
record_time: int
|
|
22
|
+
data_size: int
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class AudioDataFrame:
|
|
27
|
+
file_index: int
|
|
28
|
+
frame_offset: int
|
|
29
|
+
frame_size: int
|
|
30
|
+
is_end: bool
|
|
31
|
+
data: bytes
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class AudioRecordResult:
|
|
36
|
+
file_index: int
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
AudioProgressCallback = Callable[[int, int], None]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ProgressPrinter:
|
|
43
|
+
def __init__(self, *, prefix: str = "progress") -> None:
|
|
44
|
+
self.prefix = prefix
|
|
45
|
+
self._last_percent = -1
|
|
46
|
+
|
|
47
|
+
def __call__(self, current: int, total: int) -> None:
|
|
48
|
+
percent = int(current * 100 / total) if total else 0
|
|
49
|
+
if percent == self._last_percent:
|
|
50
|
+
return
|
|
51
|
+
self._last_percent = percent
|
|
52
|
+
print(f"{self.prefix}: {current}/{total} bytes ({percent}%)")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _audio_operation(function: Callable[..., Awaitable[Any]]) -> Callable[..., Awaitable[Any]]:
|
|
56
|
+
@wraps(function)
|
|
57
|
+
async def guarded(client: OpenZiloClient, *args: Any, **kwargs: Any) -> Any:
|
|
58
|
+
task = asyncio.current_task()
|
|
59
|
+
if client._firmware_update_active:
|
|
60
|
+
raise ProtocolError("Firmware update owns this connection")
|
|
61
|
+
if client._audio_owner is not None and client._audio_owner is not task:
|
|
62
|
+
raise ProtocolError("Another audio operation is already active")
|
|
63
|
+
nested = client._audio_owner is task
|
|
64
|
+
client._audio_owner = task
|
|
65
|
+
try:
|
|
66
|
+
return await function(client, *args, **kwargs)
|
|
67
|
+
finally:
|
|
68
|
+
if not nested:
|
|
69
|
+
client._audio_owner = None
|
|
70
|
+
return guarded
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _PacketInbox:
|
|
74
|
+
"""Temporarily own several commands in notification order, without duplicate queues."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, client: OpenZiloClient, commands: tuple[IntEnum, ...]) -> None:
|
|
77
|
+
self.client = client
|
|
78
|
+
self.commands = commands
|
|
79
|
+
self.queue: asyncio.Queue[Packet] = asyncio.Queue(maxsize=client._receive_queue_size)
|
|
80
|
+
self.error: ProtocolError | None = None
|
|
81
|
+
self.registered: list[IntEnum] = []
|
|
82
|
+
|
|
83
|
+
def _receive(self, packet: Packet) -> None:
|
|
84
|
+
if self.queue.full():
|
|
85
|
+
self.error = ProtocolError("Audio receive queue overflow; recording is incomplete")
|
|
86
|
+
else:
|
|
87
|
+
self.queue.put_nowait(packet)
|
|
88
|
+
|
|
89
|
+
def __enter__(self) -> "_PacketInbox":
|
|
90
|
+
try:
|
|
91
|
+
for command in self.commands:
|
|
92
|
+
if self.client._handlers[int(command)]:
|
|
93
|
+
raise ProtocolError("Audio command already has a packet handler")
|
|
94
|
+
for command in self.commands:
|
|
95
|
+
pending = self.client._queues[int(command)]
|
|
96
|
+
while not pending.empty():
|
|
97
|
+
self._receive(pending.get_nowait())
|
|
98
|
+
self.client.add_packet_handler(command, self._receive, queue_packets=False)
|
|
99
|
+
self.registered.append(command)
|
|
100
|
+
except Exception:
|
|
101
|
+
self.__exit__(None, None, None)
|
|
102
|
+
raise
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def __exit__(self, *_args: Any) -> None:
|
|
106
|
+
for command in self.registered:
|
|
107
|
+
self.client.remove_packet_handler(command, self._receive)
|
|
108
|
+
# A legacy automatic upload may arrive entirely in one notification.
|
|
109
|
+
# Return its remaining frames to the ordinary queue after selecting the first.
|
|
110
|
+
while not self.queue.empty():
|
|
111
|
+
packet = self.queue.get_nowait()
|
|
112
|
+
if not self.client.is_connected:
|
|
113
|
+
continue
|
|
114
|
+
target = self.client._queues[packet.command]
|
|
115
|
+
if target.full():
|
|
116
|
+
self.client._report_protocol_error(ProtocolError("Audio receive queue overflow"))
|
|
117
|
+
else:
|
|
118
|
+
target.put_nowait(packet)
|
|
119
|
+
|
|
120
|
+
async def wait(self, timeout_s: float | None) -> Packet:
|
|
121
|
+
if self.error is not None:
|
|
122
|
+
raise self.error
|
|
123
|
+
timeout = self.client.command_timeout_s if timeout_s is None else timeout_s
|
|
124
|
+
if self.client._disconnected.is_set() and self.queue.empty():
|
|
125
|
+
raise TransportError("BLE disconnected while receiving audio")
|
|
126
|
+
packet_task = asyncio.create_task(self.queue.get())
|
|
127
|
+
error_task = asyncio.create_task(self.client._protocol_errors.get())
|
|
128
|
+
disconnected = asyncio.create_task(self.client._disconnected.wait())
|
|
129
|
+
tasks = {packet_task, error_task, disconnected}
|
|
130
|
+
try:
|
|
131
|
+
done, _ = await asyncio.wait(tasks, timeout=max(0.0, timeout),
|
|
132
|
+
return_when=asyncio.FIRST_COMPLETED)
|
|
133
|
+
if self.error is not None:
|
|
134
|
+
raise self.error
|
|
135
|
+
if error_task in done:
|
|
136
|
+
raise error_task.result()
|
|
137
|
+
if packet_task in done:
|
|
138
|
+
return packet_task.result()
|
|
139
|
+
if disconnected in done:
|
|
140
|
+
raise TransportError("BLE disconnected while receiving audio")
|
|
141
|
+
raise TimeoutError("Timed out waiting for recording data or completion")
|
|
142
|
+
finally:
|
|
143
|
+
for task in tasks:
|
|
144
|
+
if not task.done():
|
|
145
|
+
task.cancel()
|
|
146
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def parse_audio_record_result(body: bytes) -> AudioRecordResult:
|
|
150
|
+
reader = BinaryReader(body)
|
|
151
|
+
ensure_success(reader.u16()) # Firmware error replies can contain only two bytes.
|
|
152
|
+
result = AudioRecordResult(reader.u32())
|
|
153
|
+
if reader.remaining:
|
|
154
|
+
raise ProtocolError("Unexpected recording result bytes")
|
|
155
|
+
return result
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@_audio_operation
|
|
159
|
+
async def wait_audio_record_result(
|
|
160
|
+
client: OpenZiloClient, *, timeout_s: float | None = None,
|
|
161
|
+
) -> AudioRecordResult:
|
|
162
|
+
"""Wait for 050A local-save completion; does not download or start recording."""
|
|
163
|
+
packet = await client.wait_for_command(AudioCommand.RECORD_RESULT, timeout_s=timeout_s)
|
|
164
|
+
return parse_audio_record_result(packet.body)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def get_audio_file_count(
|
|
168
|
+
client: OpenZiloClient,
|
|
169
|
+
*,
|
|
170
|
+
timeout_s: float | None = None,
|
|
171
|
+
) -> int:
|
|
172
|
+
packet = await client.request(
|
|
173
|
+
AudioCommand.GET_LIST,
|
|
174
|
+
AudioCommand.LIST_RESP,
|
|
175
|
+
timeout_s=timeout_s,
|
|
176
|
+
)
|
|
177
|
+
reader = BinaryReader(packet.body)
|
|
178
|
+
ensure_success(read_error(reader))
|
|
179
|
+
return reader.u32()
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@_audio_operation
|
|
183
|
+
async def get_audio_file_info(
|
|
184
|
+
client: OpenZiloClient,
|
|
185
|
+
file_index: int,
|
|
186
|
+
*,
|
|
187
|
+
timeout_s: float | None = None,
|
|
188
|
+
) -> AudioFileInfo:
|
|
189
|
+
"""Start the normal 0x0503 extraction flow and return recording metadata."""
|
|
190
|
+
body = BinaryWriter().u16(0).u32(file_index).build()
|
|
191
|
+
packet = await client.request(
|
|
192
|
+
AudioCommand.START_EXTRACT,
|
|
193
|
+
AudioCommand.FILE_INFO_RESP,
|
|
194
|
+
body,
|
|
195
|
+
timeout_s=timeout_s,
|
|
196
|
+
)
|
|
197
|
+
return parse_audio_file_info(packet.body)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@_audio_operation
|
|
201
|
+
async def read_audio_frame(
|
|
202
|
+
client: OpenZiloClient,
|
|
203
|
+
file_index: int,
|
|
204
|
+
frame_offset: int,
|
|
205
|
+
*,
|
|
206
|
+
timeout_s: float | None = None,
|
|
207
|
+
) -> AudioDataFrame:
|
|
208
|
+
body = _audio_frame_request_body(file_index, frame_offset)
|
|
209
|
+
packet = await client.request(
|
|
210
|
+
AudioCommand.NEXT_FRAME,
|
|
211
|
+
AudioCommand.DATA_FRAME,
|
|
212
|
+
body,
|
|
213
|
+
timeout_s=timeout_s,
|
|
214
|
+
)
|
|
215
|
+
return parse_audio_data_frame(packet.body)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@_audio_operation
|
|
219
|
+
async def end_audio_extract(
|
|
220
|
+
client: OpenZiloClient,
|
|
221
|
+
file_index: int,
|
|
222
|
+
*,
|
|
223
|
+
timeout_s: float | None = None,
|
|
224
|
+
ignore_timeout: bool = True,
|
|
225
|
+
) -> None:
|
|
226
|
+
body = BinaryWriter().u16(0).u32(file_index).build()
|
|
227
|
+
try:
|
|
228
|
+
packet = await client.request(
|
|
229
|
+
AudioCommand.END_EXTRACT,
|
|
230
|
+
AudioCommand.EXTRACT_DONE,
|
|
231
|
+
body,
|
|
232
|
+
timeout_s=timeout_s,
|
|
233
|
+
)
|
|
234
|
+
except TimeoutError:
|
|
235
|
+
if ignore_timeout:
|
|
236
|
+
return
|
|
237
|
+
raise
|
|
238
|
+
reader = BinaryReader(packet.body)
|
|
239
|
+
ensure_success(read_error(reader))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _audio_frame_request_body(file_index: int, frame_offset: int) -> bytes:
|
|
243
|
+
# Keep the reserved bytes required by the 12-byte 0x0506 request body.
|
|
244
|
+
return BinaryWriter().u16(0).u32(file_index).u32(frame_offset).u16(0).build()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
async def _wait_audio_data_frame(
|
|
248
|
+
client: OpenZiloClient,
|
|
249
|
+
file_index: int,
|
|
250
|
+
*,
|
|
251
|
+
timeout_s: float | None = None,
|
|
252
|
+
) -> AudioDataFrame:
|
|
253
|
+
timeout = client.command_timeout_s if timeout_s is None else timeout_s
|
|
254
|
+
deadline = asyncio.get_running_loop().time() + max(0.001, timeout)
|
|
255
|
+
while True:
|
|
256
|
+
remaining = deadline - asyncio.get_running_loop().time()
|
|
257
|
+
if remaining <= 0:
|
|
258
|
+
raise TimeoutError(
|
|
259
|
+
f"Timed out waiting for audio frame for file_index={file_index}"
|
|
260
|
+
)
|
|
261
|
+
packet = await client.wait_for_command(
|
|
262
|
+
AudioCommand.DATA_FRAME,
|
|
263
|
+
timeout_s=remaining,
|
|
264
|
+
)
|
|
265
|
+
frame = parse_audio_data_frame(packet.body)
|
|
266
|
+
if frame.file_index == file_index:
|
|
267
|
+
return frame
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
async def _request_audio_retry(
|
|
271
|
+
client: OpenZiloClient,
|
|
272
|
+
file_index: int,
|
|
273
|
+
frame_offset: int,
|
|
274
|
+
) -> None:
|
|
275
|
+
await client.send_command(
|
|
276
|
+
AudioCommand.NEXT_FRAME,
|
|
277
|
+
_audio_frame_request_body(file_index, frame_offset),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
@_audio_operation
|
|
282
|
+
async def receive_auto_audio_file(
|
|
283
|
+
client: OpenZiloClient,
|
|
284
|
+
*,
|
|
285
|
+
timeout_s: float | None = None,
|
|
286
|
+
) -> tuple[int, bytes]:
|
|
287
|
+
"""Receive one saved recording from either firmware generation.
|
|
288
|
+
|
|
289
|
+
Legacy firmware pushes 0505; new firmware sends 050A and the SDK downloads
|
|
290
|
+
that file explicitly. Returns (file_index, original bytes), which may be
|
|
291
|
+
Speex or OP2C. Live-only recordings use receive_live_audio_file instead.
|
|
292
|
+
Competing audio operations are rejected.
|
|
293
|
+
"""
|
|
294
|
+
if not client.is_connected:
|
|
295
|
+
raise TransportError("BLE client is not connected")
|
|
296
|
+
|
|
297
|
+
with _PacketInbox(client, (AudioCommand.RECORD_RESULT, AudioCommand.DATA_FRAME)) as inbox:
|
|
298
|
+
packet = await inbox.wait(timeout_s)
|
|
299
|
+
if packet.command == AudioCommand.RECORD_RESULT:
|
|
300
|
+
result = parse_audio_record_result(packet.body)
|
|
301
|
+
info, data = await download_audio_file(client, result.file_index, quick=False, timeout_s=timeout_s)
|
|
302
|
+
return info.file_index, data
|
|
303
|
+
frame = parse_audio_data_frame(packet.body)
|
|
304
|
+
file_index = frame.file_index
|
|
305
|
+
received = bytearray()
|
|
306
|
+
pending: dict[int, AudioDataFrame] = {}
|
|
307
|
+
end_offset: int | None = None
|
|
308
|
+
expected_size: int | None = None
|
|
309
|
+
recovery_attempts = 0
|
|
310
|
+
|
|
311
|
+
def add_frame(current: AudioDataFrame) -> bool:
|
|
312
|
+
nonlocal end_offset
|
|
313
|
+
|
|
314
|
+
if current.file_index != file_index:
|
|
315
|
+
raise ProtocolError(
|
|
316
|
+
f"Audio file index mismatch: expected {file_index}, "
|
|
317
|
+
f"got {current.file_index}"
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
if expected_size is not None and current.frame_offset > expected_size:
|
|
321
|
+
raise ProtocolError(
|
|
322
|
+
f"Audio frame offset {current.frame_offset} exceeds "
|
|
323
|
+
f"file size {expected_size}"
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
frame_data = current.data
|
|
327
|
+
if expected_size is not None:
|
|
328
|
+
remaining = max(0, expected_size - current.frame_offset)
|
|
329
|
+
frame_data = frame_data[:remaining]
|
|
330
|
+
|
|
331
|
+
frame_end = current.frame_offset + len(frame_data)
|
|
332
|
+
if current.is_end and expected_size is None:
|
|
333
|
+
if end_offset is not None and end_offset != frame_end:
|
|
334
|
+
raise ProtocolError(
|
|
335
|
+
"Conflicting audio end offsets: "
|
|
336
|
+
f"{end_offset} and {frame_end}"
|
|
337
|
+
)
|
|
338
|
+
end_offset = frame_end
|
|
339
|
+
|
|
340
|
+
previous_size = len(received)
|
|
341
|
+
if frame_end <= previous_size:
|
|
342
|
+
overlap_size = len(frame_data)
|
|
343
|
+
if received[current.frame_offset:frame_end] != frame_data[:overlap_size]:
|
|
344
|
+
raise ProtocolError(
|
|
345
|
+
f"Conflicting audio data at offset {current.frame_offset}"
|
|
346
|
+
)
|
|
347
|
+
return False
|
|
348
|
+
if current.frame_offset <= previous_size:
|
|
349
|
+
overlap = previous_size - current.frame_offset
|
|
350
|
+
if received[current.frame_offset:previous_size] != frame_data[:overlap]:
|
|
351
|
+
raise ProtocolError(
|
|
352
|
+
f"Conflicting audio overlap at offset {current.frame_offset}"
|
|
353
|
+
)
|
|
354
|
+
received.extend(frame_data[overlap:])
|
|
355
|
+
return len(received) > previous_size
|
|
356
|
+
|
|
357
|
+
existing = pending.get(current.frame_offset)
|
|
358
|
+
if existing is None or len(existing.data) < len(current.data):
|
|
359
|
+
pending[current.frame_offset] = current
|
|
360
|
+
return False
|
|
361
|
+
|
|
362
|
+
async def ensure_recovery_metadata() -> None:
|
|
363
|
+
nonlocal end_offset, expected_size
|
|
364
|
+
|
|
365
|
+
if expected_size is not None:
|
|
366
|
+
return
|
|
367
|
+
info = await get_audio_file_info(
|
|
368
|
+
client,
|
|
369
|
+
file_index,
|
|
370
|
+
timeout_s=timeout_s,
|
|
371
|
+
)
|
|
372
|
+
if info.file_index != file_index:
|
|
373
|
+
raise ProtocolError(
|
|
374
|
+
f"Audio metadata index mismatch: expected {file_index}, "
|
|
375
|
+
f"got {info.file_index}"
|
|
376
|
+
)
|
|
377
|
+
if info.data_size <= 0:
|
|
378
|
+
raise ProtocolError(
|
|
379
|
+
f"Audio metadata has invalid data_size={info.data_size}"
|
|
380
|
+
)
|
|
381
|
+
expected_size = info.data_size
|
|
382
|
+
end_offset = expected_size
|
|
383
|
+
if len(received) > expected_size:
|
|
384
|
+
del received[expected_size:]
|
|
385
|
+
for offset in list(pending):
|
|
386
|
+
if offset >= expected_size:
|
|
387
|
+
pending.pop(offset)
|
|
388
|
+
|
|
389
|
+
def append_pending() -> bool:
|
|
390
|
+
grew = False
|
|
391
|
+
while pending:
|
|
392
|
+
offset = min(pending)
|
|
393
|
+
if offset > len(received):
|
|
394
|
+
break
|
|
395
|
+
current = pending.pop(offset)
|
|
396
|
+
if add_frame(current):
|
|
397
|
+
grew = True
|
|
398
|
+
return grew
|
|
399
|
+
|
|
400
|
+
while True:
|
|
401
|
+
grew = add_frame(frame)
|
|
402
|
+
if append_pending():
|
|
403
|
+
grew = True
|
|
404
|
+
if grew:
|
|
405
|
+
recovery_attempts = 0
|
|
406
|
+
|
|
407
|
+
if end_offset is not None and len(received) >= end_offset:
|
|
408
|
+
return file_index, bytes(received[:end_offset])
|
|
409
|
+
|
|
410
|
+
has_gap = bool(pending) and min(pending) > len(received)
|
|
411
|
+
if has_gap:
|
|
412
|
+
recovery_attempts += 1
|
|
413
|
+
if recovery_attempts > 3:
|
|
414
|
+
raise ProtocolError(
|
|
415
|
+
"Audio frame gap: "
|
|
416
|
+
f"unable to recover offset {len(received)}"
|
|
417
|
+
)
|
|
418
|
+
await ensure_recovery_metadata()
|
|
419
|
+
if expected_size is not None and len(received) >= expected_size:
|
|
420
|
+
return file_index, bytes(received[:expected_size])
|
|
421
|
+
await _request_audio_retry(client, file_index, len(received))
|
|
422
|
+
|
|
423
|
+
while True:
|
|
424
|
+
try:
|
|
425
|
+
frame = await _wait_audio_data_frame(
|
|
426
|
+
client,
|
|
427
|
+
file_index,
|
|
428
|
+
timeout_s=timeout_s,
|
|
429
|
+
)
|
|
430
|
+
break
|
|
431
|
+
except (TimeoutError, ProtocolError) as exc:
|
|
432
|
+
recovery_attempts += 1
|
|
433
|
+
if recovery_attempts > 3:
|
|
434
|
+
raise ProtocolError(
|
|
435
|
+
"Audio stream stalled: "
|
|
436
|
+
f"unable to recover offset {len(received)}"
|
|
437
|
+
) from exc
|
|
438
|
+
await ensure_recovery_metadata()
|
|
439
|
+
if expected_size is not None and len(received) >= expected_size:
|
|
440
|
+
return file_index, bytes(received[:expected_size])
|
|
441
|
+
await _request_audio_retry(client, file_index, len(received))
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
async def _download_audio_file_quick(
|
|
445
|
+
client: OpenZiloClient,
|
|
446
|
+
file_index: int,
|
|
447
|
+
*,
|
|
448
|
+
progress: AudioProgressCallback | None = None,
|
|
449
|
+
timeout_s: float | None = None,
|
|
450
|
+
) -> tuple[AudioFileInfo, bytes]:
|
|
451
|
+
client._drain_queue(int(AudioCommand.FILE_INFO_RESP))
|
|
452
|
+
client._drain_queue(int(AudioCommand.DATA_FRAME))
|
|
453
|
+
await client.send_command(
|
|
454
|
+
AudioCommand.START_EXTRACT_QUICK,
|
|
455
|
+
BinaryWriter().u16(0).u32(file_index).build(),
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
info_packet = await client.wait_for_command(
|
|
459
|
+
AudioCommand.FILE_INFO_RESP,
|
|
460
|
+
timeout_s=timeout_s,
|
|
461
|
+
)
|
|
462
|
+
info = parse_audio_file_info(info_packet.body)
|
|
463
|
+
if info.file_index != file_index:
|
|
464
|
+
raise ProtocolError(
|
|
465
|
+
f"Audio metadata index mismatch: expected {file_index}, got {info.file_index}"
|
|
466
|
+
)
|
|
467
|
+
received = bytearray()
|
|
468
|
+
gap_retries = 0
|
|
469
|
+
|
|
470
|
+
while True:
|
|
471
|
+
try:
|
|
472
|
+
frame = await _wait_audio_data_frame(
|
|
473
|
+
client,
|
|
474
|
+
file_index,
|
|
475
|
+
timeout_s=timeout_s,
|
|
476
|
+
)
|
|
477
|
+
except TimeoutError as exc:
|
|
478
|
+
gap_retries += 1
|
|
479
|
+
if gap_retries > 3:
|
|
480
|
+
raise ProtocolError(
|
|
481
|
+
f"Audio stream stalled at offset {len(received)}"
|
|
482
|
+
) from exc
|
|
483
|
+
await _request_audio_retry(client, file_index, len(received))
|
|
484
|
+
frame = await _wait_audio_data_frame(
|
|
485
|
+
client,
|
|
486
|
+
file_index,
|
|
487
|
+
timeout_s=timeout_s,
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
if frame.frame_offset > len(received):
|
|
491
|
+
gap_retries += 1
|
|
492
|
+
if gap_retries > 3:
|
|
493
|
+
raise ProtocolError(
|
|
494
|
+
"Audio frame gap: "
|
|
495
|
+
f"expected offset {len(received)}, got {frame.frame_offset}"
|
|
496
|
+
)
|
|
497
|
+
await _request_audio_retry(client, file_index, len(received))
|
|
498
|
+
continue
|
|
499
|
+
|
|
500
|
+
overlap = len(received) - frame.frame_offset
|
|
501
|
+
overlap_size = min(overlap, len(frame.data))
|
|
502
|
+
if overlap_size > 0:
|
|
503
|
+
existing = received[
|
|
504
|
+
frame.frame_offset : frame.frame_offset + overlap_size
|
|
505
|
+
]
|
|
506
|
+
if existing != frame.data[:overlap_size]:
|
|
507
|
+
raise ProtocolError(
|
|
508
|
+
f"Conflicting audio overlap at offset {frame.frame_offset}"
|
|
509
|
+
)
|
|
510
|
+
if overlap < len(frame.data):
|
|
511
|
+
new_data = frame.data[overlap:]
|
|
512
|
+
if info.data_size > 0:
|
|
513
|
+
new_data = new_data[: max(0, info.data_size - len(received))]
|
|
514
|
+
received.extend(new_data)
|
|
515
|
+
|
|
516
|
+
if overlap < len(frame.data):
|
|
517
|
+
gap_retries = 0
|
|
518
|
+
|
|
519
|
+
if progress:
|
|
520
|
+
progress(len(received), info.data_size)
|
|
521
|
+
if info.data_size > 0 and len(received) >= info.data_size:
|
|
522
|
+
break
|
|
523
|
+
if frame.is_end:
|
|
524
|
+
gap_retries += 1
|
|
525
|
+
if gap_retries > 3:
|
|
526
|
+
raise ProtocolError(
|
|
527
|
+
f"Audio stream ended at {len(received)} of {info.data_size} bytes"
|
|
528
|
+
)
|
|
529
|
+
await _request_audio_retry(client, file_index, len(received))
|
|
530
|
+
elif not frame.data:
|
|
531
|
+
raise ProtocolError(
|
|
532
|
+
f"Empty audio frame at offset {frame.frame_offset} before end"
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
data = bytes(received[: info.data_size] if info.data_size > 0 else received)
|
|
536
|
+
return info, data
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
@_audio_operation
|
|
540
|
+
async def clear_audio_files(
|
|
541
|
+
client: OpenZiloClient,
|
|
542
|
+
*,
|
|
543
|
+
timeout_s: float | None = None,
|
|
544
|
+
) -> None:
|
|
545
|
+
packet = await client.request(
|
|
546
|
+
AudioCommand.CLEAR_ALL,
|
|
547
|
+
AudioCommand.CLEAR_ALL_RESP,
|
|
548
|
+
timeout_s=timeout_s,
|
|
549
|
+
)
|
|
550
|
+
reader = BinaryReader(packet.body)
|
|
551
|
+
ensure_success(read_error(reader))
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
@_audio_operation
|
|
555
|
+
async def download_audio_file(
|
|
556
|
+
client: OpenZiloClient,
|
|
557
|
+
file_index: int,
|
|
558
|
+
*,
|
|
559
|
+
progress: AudioProgressCallback | None = None,
|
|
560
|
+
timeout_s: float | None = None,
|
|
561
|
+
quick: bool = True,
|
|
562
|
+
) -> tuple[AudioFileInfo, bytes]:
|
|
563
|
+
if quick:
|
|
564
|
+
return await _download_audio_file_quick(
|
|
565
|
+
client,
|
|
566
|
+
file_index,
|
|
567
|
+
progress=progress,
|
|
568
|
+
timeout_s=timeout_s,
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
try:
|
|
572
|
+
info = await get_audio_file_info(
|
|
573
|
+
client,
|
|
574
|
+
file_index,
|
|
575
|
+
timeout_s=timeout_s,
|
|
576
|
+
)
|
|
577
|
+
if info.file_index != file_index:
|
|
578
|
+
raise ProtocolError(
|
|
579
|
+
f"Audio metadata index mismatch: expected {file_index}, got {info.file_index}"
|
|
580
|
+
)
|
|
581
|
+
received = bytearray()
|
|
582
|
+
|
|
583
|
+
while True:
|
|
584
|
+
frame = await read_audio_frame(
|
|
585
|
+
client,
|
|
586
|
+
file_index,
|
|
587
|
+
len(received),
|
|
588
|
+
timeout_s=timeout_s,
|
|
589
|
+
)
|
|
590
|
+
if frame.frame_offset > len(received):
|
|
591
|
+
raise ProtocolError(
|
|
592
|
+
f"Audio frame gap: expected offset {len(received)}, "
|
|
593
|
+
f"got {frame.frame_offset}"
|
|
594
|
+
)
|
|
595
|
+
overlap = len(received) - frame.frame_offset
|
|
596
|
+
overlap_size = min(overlap, len(frame.data))
|
|
597
|
+
if overlap_size > 0:
|
|
598
|
+
existing = received[
|
|
599
|
+
frame.frame_offset : frame.frame_offset + overlap_size
|
|
600
|
+
]
|
|
601
|
+
if existing != frame.data[:overlap_size]:
|
|
602
|
+
raise ProtocolError(
|
|
603
|
+
f"Conflicting audio overlap at offset {frame.frame_offset}"
|
|
604
|
+
)
|
|
605
|
+
new_data = frame.data[overlap:]
|
|
606
|
+
if info.data_size > 0:
|
|
607
|
+
new_data = new_data[: max(0, info.data_size - len(received))]
|
|
608
|
+
received.extend(new_data)
|
|
609
|
+
if progress:
|
|
610
|
+
progress(len(received), info.data_size)
|
|
611
|
+
if info.data_size > 0 and len(received) >= info.data_size:
|
|
612
|
+
break
|
|
613
|
+
if frame.is_end:
|
|
614
|
+
raise ProtocolError(
|
|
615
|
+
f"Audio stream ended at {len(received)} of {info.data_size} bytes"
|
|
616
|
+
)
|
|
617
|
+
if not new_data:
|
|
618
|
+
raise ProtocolError(
|
|
619
|
+
f"Audio transfer made no progress at offset {len(received)}"
|
|
620
|
+
)
|
|
621
|
+
except (Exception, asyncio.CancelledError):
|
|
622
|
+
if client.is_connected:
|
|
623
|
+
try:
|
|
624
|
+
await asyncio.wait_for(client.request(
|
|
625
|
+
AudioCommand.END_EXTRACT, AudioCommand.EXTRACT_DONE,
|
|
626
|
+
BinaryWriter().u16(0).u32(file_index).build(), timeout_s=2.0,
|
|
627
|
+
), timeout=2.0)
|
|
628
|
+
except (Exception, asyncio.CancelledError):
|
|
629
|
+
pass
|
|
630
|
+
raise
|
|
631
|
+
await end_audio_extract(client, file_index, timeout_s=timeout_s, ignore_timeout=False)
|
|
632
|
+
data = bytes(received[: info.data_size] if info.data_size > 0 else received)
|
|
633
|
+
return info, data
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def parse_audio_file_info(body: bytes) -> AudioFileInfo:
|
|
637
|
+
reader = BinaryReader(body)
|
|
638
|
+
ensure_success(read_error(reader))
|
|
639
|
+
info = AudioFileInfo(
|
|
640
|
+
file_index=reader.u32(),
|
|
641
|
+
record_time=reader.u32(),
|
|
642
|
+
data_size=reader.u32(),
|
|
643
|
+
)
|
|
644
|
+
if reader.remaining:
|
|
645
|
+
raise ProtocolError(
|
|
646
|
+
f"Unexpected trailing audio file info bytes: {reader.remaining}"
|
|
647
|
+
)
|
|
648
|
+
return info
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def parse_audio_data_frame(body: bytes) -> AudioDataFrame:
|
|
652
|
+
reader = BinaryReader(body)
|
|
653
|
+
ensure_success(read_error(reader))
|
|
654
|
+
file_index = reader.u32()
|
|
655
|
+
frame_offset = reader.u32()
|
|
656
|
+
frame_size = reader.u32()
|
|
657
|
+
is_end = bool(reader.u8())
|
|
658
|
+
if reader.remaining != frame_size:
|
|
659
|
+
raise ProtocolError(
|
|
660
|
+
f"Audio frame size mismatch: declared {frame_size}, "
|
|
661
|
+
f"got {reader.remaining}"
|
|
662
|
+
)
|
|
663
|
+
data = reader.bytes(frame_size)
|
|
664
|
+
return AudioDataFrame(
|
|
665
|
+
file_index=file_index,
|
|
666
|
+
frame_offset=frame_offset,
|
|
667
|
+
frame_size=frame_size,
|
|
668
|
+
is_end=is_end,
|
|
669
|
+
data=data,
|
|
670
|
+
)
|