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/_pcm.py ADDED
@@ -0,0 +1,87 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Optional, stateful Opus-to-PCM decoding without an ffmpeg subprocess."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import struct
7
+ import sys
8
+ from typing import Any
9
+
10
+ from ._errors import AudioDecodeError, OpusDecoderUnavailable
11
+
12
+
13
+ class _OpusPcmDecoder:
14
+ """One decoder/resampler per recording; output is s16le mono or stereo."""
15
+
16
+ def __init__(self, *, channels: int = 2) -> None:
17
+ if channels not in (1, 2):
18
+ raise ValueError("channels must be 1 or 2")
19
+ self._channels = channels
20
+ self._layout = "mono" if channels == 1 else "stereo"
21
+ self._block_bytes = 320 * channels * 2
22
+ try:
23
+ import av
24
+ except ImportError as exc:
25
+ raise OpusDecoderUnavailable(
26
+ "Install live PCM decoding with: uv sync --extra pcm"
27
+ ) from exc
28
+ self._av = av
29
+ try:
30
+ self._codec = av.CodecContext.create("opus", "r")
31
+ # OP2C has no pre-skip or gain metadata. Preserve all samples.
32
+ self._codec.extradata = struct.pack(
33
+ "<8sBBHIhB", b"OpusHead", 1, channels, 0, 16000, 0, 0,
34
+ )
35
+ self._codec.open()
36
+ self._resampler = av.AudioResampler(format="s16", layout=self._layout, rate=16000)
37
+ except Exception as exc:
38
+ raise OpusDecoderUnavailable("Could not initialize the live Opus decoder") from exc
39
+ self._pending = bytearray()
40
+ self._packets = 0
41
+ self._samples = 0
42
+
43
+ def _convert(self, frames: Any) -> None:
44
+ for frame in frames:
45
+ if (frame.sample_rate, frame.layout.name, frame.format.name) != (16000, self._layout, "s16"):
46
+ raise AudioDecodeError("Unexpected live PCM format")
47
+ # AV planes include alignment padding; expose only actual samples.
48
+ pcm = bytes(frame.planes[0])[:frame.samples * self._channels * 2]
49
+ if sys.byteorder != "little":
50
+ from array import array
51
+ samples = array("h", pcm)
52
+ samples.byteswap()
53
+ pcm = samples.tobytes()
54
+ self._pending.extend(pcm)
55
+
56
+ def _blocks(self) -> list[bytes]:
57
+ blocks = []
58
+ while len(self._pending) >= self._block_bytes:
59
+ blocks.append(bytes(self._pending[:self._block_bytes]))
60
+ del self._pending[:self._block_bytes]
61
+ self._samples += 320
62
+ return blocks
63
+
64
+ def decode(self, packet: bytes) -> list[bytes]:
65
+ try:
66
+ for frame in self._codec.decode(self._av.Packet(packet)):
67
+ self._convert(self._resampler.resample(frame))
68
+ self._packets += 1
69
+ return self._blocks()
70
+ except AudioDecodeError:
71
+ raise
72
+ except Exception as exc:
73
+ raise AudioDecodeError("Live Opus decoding failed") from exc
74
+
75
+ def flush(self) -> list[bytes]:
76
+ try:
77
+ for frame in self._codec.decode(None):
78
+ self._convert(self._resampler.resample(frame))
79
+ self._convert(self._resampler.resample(None))
80
+ blocks = self._blocks()
81
+ if self._pending or self._samples != self._packets * 320:
82
+ raise AudioDecodeError("Live Opus decoder returned an unexpected PCM length")
83
+ return blocks
84
+ except AudioDecodeError:
85
+ raise
86
+ except Exception as exc:
87
+ raise AudioDecodeError("Could not flush the live Opus decoder") from exc
openzilo/_protocol.py ADDED
@@ -0,0 +1,303 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Protocol v4 framing, command numbers and binary field helpers."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import struct
7
+ from dataclasses import dataclass
8
+ from enum import IntEnum
9
+
10
+ from ._errors import DeviceError, ERROR_MESSAGES, ErrorCode, ProtocolError
11
+
12
+
13
+ HEADER_MAGIC = 0x3F
14
+ PROTOCOL_VERSION = 4
15
+ SUPPORTED_PROTOCOL_VERSIONS = frozenset({4})
16
+ HEADER_SIZE = 11
17
+ MAX_BODY_LENGTH = 5120
18
+ _HEADER_STRUCT = struct.Struct(">BHHIH")
19
+
20
+
21
+ class SystemCommand(IntEnum):
22
+ GET_INFO = 0x0101
23
+ INFO_RESP = 0x0102
24
+ GET_CAPABILITIES = 0x0105
25
+ CAPABILITIES_RESP = 0x0106
26
+ GET_RSSI = 0x0107
27
+ RSSI_RESP = 0x0108
28
+ ERROR_RESP = 0x01FF
29
+
30
+
31
+ class _OtaCommand(IntEnum):
32
+ NOTIFY = 1005
33
+ NOTIFY_RESP = 1105
34
+ GET_PACKET = 2001
35
+ PACKET_RESP = 2101
36
+ UPDATE_RESULT = 2201
37
+
38
+
39
+ class LogCommand(IntEnum):
40
+ GET_STORAGE = 0x0301
41
+ STORAGE_RESP = 0x0302
42
+ GET_LOG = 0x0303
43
+ LOG_RESP = 0x0304
44
+
45
+
46
+ class TimeCommand(IntEnum):
47
+ REQUEST = 0x0401
48
+ RESPONSE = 0x0402
49
+
50
+
51
+ class AudioCommand(IntEnum):
52
+ GET_LIST = 0x0501
53
+ LIST_RESP = 0x0502
54
+ START_EXTRACT = 0x0503
55
+ FILE_INFO_RESP = 0x0504
56
+ DATA_FRAME = 0x0505
57
+ NEXT_FRAME = 0x0506
58
+ END_EXTRACT = 0x0507
59
+ EXTRACT_DONE = 0x0508
60
+ START_EXTRACT_QUICK = 0x0509
61
+ RECORD_RESULT = 0x050A
62
+ LIVE_SUBSCRIBE = 0x050D
63
+ LIVE_SUBSCRIBE_RESP = 0x050E
64
+ LIVE_START = 0x050F
65
+ LIVE_DATA = 0x0510
66
+ LIVE_END = 0x0511
67
+ CLEAR_ALL = 0x050B
68
+ CLEAR_ALL_RESP = 0x050C
69
+ GET_RECORDING_CONFIG = 0x0512
70
+ RECORDING_CONFIG = 0x0513
71
+ SET_RECORDING_CONFIG = 0x0514
72
+ RECORDING_CONFIG_SET = 0x0515
73
+ START_RECORDING = 0x0516
74
+ RECORDING_STARTED = 0x0517
75
+ STOP_RECORDING = 0x0518
76
+ RECORDING_STOPPED = 0x0519
77
+ GET_RECORDING_STATUS = 0x051A
78
+ RECORDING_STATUS = 0x051B
79
+
80
+
81
+ class SensorCommand(IntEnum):
82
+ START_REPORT = 0x0601
83
+ START_REPORT_RESP = 0x0602
84
+ STOP_REPORT = 0x0603
85
+ STOP_REPORT_RESP = 0x0604
86
+ DATA_FRAME = 0x0605
87
+ DOUBLE_TAP = 0x0701
88
+ GESTURE = 0x0702
89
+ KEY_DOUBLE_PRESS = 0x0703
90
+ KEY_SINGLE_PRESS = 0x0704
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class Packet:
95
+ command: int
96
+ body: bytes
97
+ version: int = PROTOCOL_VERSION
98
+ body_crc: int = 0
99
+
100
+
101
+ class BinaryReader:
102
+ def __init__(self, data: bytes | bytearray | memoryview) -> None:
103
+ self._data = memoryview(bytes(data))
104
+ self.offset = 0
105
+
106
+ @property
107
+ def remaining(self) -> int:
108
+ return len(self._data) - self.offset
109
+
110
+ def require(self, size: int) -> None:
111
+ if self.remaining < size:
112
+ raise ProtocolError(f"Need {size} bytes, only {self.remaining} left")
113
+
114
+ def u8(self) -> int:
115
+ self.require(1)
116
+ value = self._data[self.offset]
117
+ self.offset += 1
118
+ return int(value)
119
+
120
+ def u16(self) -> int:
121
+ self.require(2)
122
+ value = struct.unpack_from(">H", self._data, self.offset)[0]
123
+ self.offset += 2
124
+ return int(value)
125
+
126
+ def i16(self) -> int:
127
+ self.require(2)
128
+ value = struct.unpack_from(">h", self._data, self.offset)[0]
129
+ self.offset += 2
130
+ return int(value)
131
+
132
+ def u32(self) -> int:
133
+ self.require(4)
134
+ value = struct.unpack_from(">I", self._data, self.offset)[0]
135
+ self.offset += 4
136
+ return int(value)
137
+
138
+ def bytes(self, size: int) -> bytes:
139
+ self.require(size)
140
+ value = self._data[self.offset : self.offset + size].tobytes()
141
+ self.offset += size
142
+ return value
143
+
144
+ def string_u16(self, encoding: str = "utf-8") -> str:
145
+ size = self.u16()
146
+ return self.bytes(size).decode(encoding, errors="replace")
147
+
148
+
149
+ class BinaryWriter:
150
+ def __init__(self) -> None:
151
+ self._data = bytearray()
152
+
153
+ def u8(self, value: int) -> "BinaryWriter":
154
+ self._data += struct.pack(">B", value & 0xFF)
155
+ return self
156
+
157
+ def u16(self, value: int) -> "BinaryWriter":
158
+ self._data += struct.pack(">H", value & 0xFFFF)
159
+ return self
160
+
161
+ def i16(self, value: int) -> "BinaryWriter":
162
+ self._data += struct.pack(">h", value)
163
+ return self
164
+
165
+ def u32(self, value: int) -> "BinaryWriter":
166
+ self._data += struct.pack(">I", value & 0xFFFFFFFF)
167
+ return self
168
+
169
+ def bytes(self, value: bytes | bytearray | memoryview) -> "BinaryWriter":
170
+ self._data += bytes(value)
171
+ return self
172
+
173
+ def string_u32(self, value: str, encoding: str = "utf-8") -> "BinaryWriter":
174
+ raw = value.encode(encoding)
175
+ self.u32(len(raw))
176
+ self.bytes(raw)
177
+ return self
178
+
179
+ def build(self) -> bytes:
180
+ return bytes(self._data)
181
+
182
+
183
+ def crc16_compute(data: bytes | bytearray | memoryview, initial: int = 0xFFFF) -> int:
184
+ crc = initial & 0xFFFF
185
+ for byte in bytes(data):
186
+ crc = ((crc >> 8) | ((crc << 8) & 0xFFFF)) & 0xFFFF
187
+ crc ^= byte
188
+ crc &= 0xFFFF
189
+ crc ^= (crc & 0xFF) >> 4
190
+ crc &= 0xFFFF
191
+ crc ^= (crc << 8) << 4
192
+ crc &= 0xFFFF
193
+ crc ^= ((crc & 0xFF) << 4) << 1
194
+ crc &= 0xFFFF
195
+ return crc
196
+
197
+
198
+ def encode_packet(command: int, body: bytes | bytearray | memoryview = b"") -> bytes:
199
+ payload = bytes(body)
200
+ body_crc = crc16_compute(payload) if payload else 0
201
+ header = _HEADER_STRUCT.pack(
202
+ HEADER_MAGIC,
203
+ PROTOCOL_VERSION,
204
+ int(command) & 0xFFFF,
205
+ len(payload),
206
+ body_crc,
207
+ )
208
+ return header + payload
209
+
210
+
211
+ def decode_packet(data: bytes | bytearray | memoryview) -> Packet:
212
+ raw = bytes(data)
213
+ if len(raw) < HEADER_SIZE:
214
+ raise ProtocolError(f"Packet too short: {len(raw)} bytes")
215
+
216
+ magic, version, command, body_length, body_crc = _HEADER_STRUCT.unpack(
217
+ raw[:HEADER_SIZE]
218
+ )
219
+ if magic != HEADER_MAGIC:
220
+ raise ProtocolError(f"Invalid packet magic: 0x{magic:02X}")
221
+ if version not in SUPPORTED_PROTOCOL_VERSIONS:
222
+ raise ProtocolError(f"Unsupported protocol version: {version}")
223
+ if body_length > MAX_BODY_LENGTH:
224
+ raise ProtocolError(f"Body too large: {body_length} bytes")
225
+ if len(raw) < HEADER_SIZE + body_length:
226
+ raise ProtocolError(
227
+ f"Incomplete packet: need {HEADER_SIZE + body_length}, got {len(raw)}"
228
+ )
229
+
230
+ body = raw[HEADER_SIZE : HEADER_SIZE + body_length]
231
+ if body_length:
232
+ actual_crc = crc16_compute(body)
233
+ if actual_crc != body_crc:
234
+ raise ProtocolError(
235
+ f"Body CRC mismatch: expected 0x{body_crc:04X}, got 0x{actual_crc:04X}"
236
+ )
237
+
238
+ return Packet(command=command, body=body, version=version, body_crc=body_crc)
239
+
240
+
241
+ def peek_body_length(data: bytes | bytearray | memoryview) -> int:
242
+ if len(data) < HEADER_SIZE:
243
+ raise ProtocolError("Not enough bytes to read packet header")
244
+ _, _, _, body_length, _ = _HEADER_STRUCT.unpack(bytes(data[:HEADER_SIZE]))
245
+ return body_length
246
+
247
+
248
+ class PacketStream:
249
+ """Accumulates BLE chunks and emits complete protocol packets."""
250
+
251
+ def __init__(self) -> None:
252
+ self._buffer = bytearray()
253
+
254
+ def clear(self) -> None:
255
+ self._buffer.clear()
256
+
257
+ def feed(self, data: bytes | bytearray | memoryview) -> list[Packet]:
258
+ self._buffer.extend(data)
259
+ packets: list[Packet] = []
260
+
261
+ while True:
262
+ if not self._buffer:
263
+ return packets
264
+
265
+ magic_index = self._buffer.find(bytes([HEADER_MAGIC]))
266
+ if magic_index < 0:
267
+ self._buffer.clear()
268
+ return packets
269
+ if magic_index:
270
+ del self._buffer[:magic_index]
271
+
272
+ if len(self._buffer) < HEADER_SIZE:
273
+ return packets
274
+
275
+ body_length = peek_body_length(self._buffer)
276
+ if body_length > MAX_BODY_LENGTH:
277
+ self._buffer.clear()
278
+ raise ProtocolError(f"Body too large: {body_length} bytes")
279
+
280
+ packet_length = HEADER_SIZE + body_length
281
+ if len(self._buffer) < packet_length:
282
+ return packets
283
+
284
+ packet_bytes = bytes(self._buffer[:packet_length])
285
+ del self._buffer[:packet_length]
286
+ packets.append(decode_packet(packet_bytes))
287
+
288
+ def __len__(self) -> int:
289
+ return len(self._buffer)
290
+
291
+
292
+ def read_error(reader: BinaryReader) -> int:
293
+ return reader.u16()
294
+
295
+
296
+ def ensure_success(error_code: int) -> None:
297
+ if error_code == int(ErrorCode.SUCCESS):
298
+ return
299
+ try:
300
+ message = ERROR_MESSAGES[ErrorCode(error_code)]
301
+ except ValueError:
302
+ message = f"device error {error_code}"
303
+ raise DeviceError(error_code, message)
openzilo/_recording.py ADDED
@@ -0,0 +1,250 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Recording control extension; requires firmware implementing 0x0512..0x051B."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import math
8
+ import struct
9
+ from dataclasses import dataclass
10
+ from enum import IntEnum
11
+
12
+ from ._client import OpenZiloClient
13
+ from ._errors import ProtocolError, TimeoutError
14
+ from ._protocol import AudioCommand, ensure_success
15
+
16
+
17
+ class AudioOutput(IntEnum):
18
+ AUTO = 0
19
+ FLASH = 1
20
+ LIVE = 2
21
+ LIVE_AND_FLASH = 3
22
+
23
+
24
+ class AudioDisconnectPolicy(IntEnum):
25
+ STOP = 0
26
+ CONTINUE_SAVING = 1
27
+
28
+
29
+ class AudioRecordingState(IntEnum):
30
+ IDLE = 0
31
+ QUEUED = 1
32
+ CAPTURING = 2
33
+ FINALIZING = 3
34
+ COMPLETE = 4
35
+ FAILED = 5
36
+ CANCELLED = 6
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class AudioRecordingConfig:
41
+ output: AudioOutput = AudioOutput.AUTO
42
+ disconnect_policy: AudioDisconnectPolicy = AudioDisconnectPolicy.STOP
43
+ channels: int = 2
44
+ bitrate: int = 32000
45
+ gain_left_q8: int = 256
46
+ gain_right_q8: int = 256
47
+ max_duration_ms: int = 60000
48
+ sample_rate: int = 16000
49
+ frame_duration_ms: int = 20
50
+ codec: int = 3
51
+ complexity: int = 1
52
+ vbr: int = 1
53
+ constrained_vbr: int = 1
54
+ dtx: int = 0
55
+ fec: int = 0
56
+ packet_loss_percent: int = 0
57
+ signal: int = 3001
58
+ bit_depth: int = 16
59
+ max_packet_size: int = 100
60
+ application: int = 2048
61
+
62
+ def __post_init__(self) -> None:
63
+ for name in ("output", "disconnect_policy", "channels", "bitrate", "gain_left_q8",
64
+ "gain_right_q8", "max_duration_ms", "sample_rate", "frame_duration_ms",
65
+ "codec", "complexity", "vbr", "constrained_vbr", "dtx", "fec",
66
+ "packet_loss_percent", "signal", "bit_depth", "max_packet_size", "application"):
67
+ value = getattr(self, name)
68
+ if isinstance(value, bool) or not isinstance(value, int):
69
+ raise ValueError(f"{name} must be an integer")
70
+ object.__setattr__(self, "output", AudioOutput(self.output))
71
+ object.__setattr__(self, "disconnect_policy", AudioDisconnectPolicy(self.disconnect_policy))
72
+ if self.channels not in (1, 2) or not 8000 <= self.bitrate <= 32000:
73
+ raise ValueError("Supported audio is mono/stereo at 8000..32000 bits/s")
74
+ if not 0 <= self.gain_left_q8 <= 1024 or not 0 <= self.gain_right_q8 <= 1024:
75
+ raise ValueError("Digital gains must be 0..1024 (256 = unity)")
76
+ if self.max_duration_ms != 0 and (not 20 <= self.max_duration_ms <= 60000 or self.max_duration_ms % 20):
77
+ raise ValueError("max_duration_ms must be 0 or 20..60000 in 20 ms increments")
78
+ if (self.sample_rate, self.frame_duration_ms) != (16000, 20):
79
+ raise ValueError("This firmware supports 16000 Hz and 20 ms frames")
80
+ if (self.codec, self.complexity, self.vbr, self.constrained_vbr, self.dtx,
81
+ self.fec, self.packet_loss_percent, self.signal, self.bit_depth,
82
+ self.max_packet_size, self.application) != (3, 1, 1, 1, 0, 0, 0, 3001, 16, 100, 2048):
83
+ raise ValueError("This firmware's fixed Opus profile is read-only")
84
+ if (self.disconnect_policy == AudioDisconnectPolicy.CONTINUE_SAVING
85
+ and self.output not in (AudioOutput.FLASH, AudioOutput.LIVE_AND_FLASH)):
86
+ raise ValueError("CONTINUE_SAVING requires FLASH or LIVE_AND_FLASH")
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class AudioRecordingStatus:
91
+ session_id: int
92
+ state: AudioRecordingState
93
+ saved: bool
94
+ error_code: int
95
+ file_index: int | None
96
+
97
+ @property
98
+ def finished(self) -> bool:
99
+ return self.state in (AudioRecordingState.COMPLETE, AudioRecordingState.FAILED,
100
+ AudioRecordingState.CANCELLED)
101
+
102
+
103
+ _CONFIG = struct.Struct(">BBBBIHHH")
104
+
105
+
106
+ def _config_body(config: AudioRecordingConfig) -> bytes:
107
+ return _CONFIG.pack(1, config.output, config.disconnect_policy, config.channels,
108
+ config.bitrate, config.gain_left_q8, config.gain_right_q8,
109
+ config.max_duration_ms)
110
+
111
+
112
+ def _parse_config(body: bytes) -> AudioRecordingConfig:
113
+ if len(body) < 2:
114
+ raise ProtocolError("Truncated audio configuration response")
115
+ ensure_success(struct.unpack_from(">H", body)[0])
116
+ if len(body) != 34:
117
+ raise ProtocolError("Invalid audio configuration response length")
118
+ version, output, disconnect, channels, bitrate, left, right, duration = _CONFIG.unpack_from(body, 2)
119
+ if version != 1:
120
+ raise ProtocolError("Unsupported audio configuration version")
121
+ rate, frame = struct.unpack_from(">HH", body, 16)
122
+ profile = struct.unpack_from(">BBBBBBBHBHH", body, 20)
123
+ try:
124
+ return AudioRecordingConfig(output, disconnect, channels, bitrate, left, right, duration, rate, frame, *profile)
125
+ except ValueError as exc:
126
+ raise ProtocolError(str(exc)) from exc
127
+
128
+
129
+ async def get_audio_recording_config(
130
+ client: OpenZiloClient, *, timeout_s: float | None = None,
131
+ ) -> AudioRecordingConfig:
132
+ packet = await client.request(AudioCommand.GET_RECORDING_CONFIG, AudioCommand.RECORDING_CONFIG,
133
+ timeout_s=timeout_s)
134
+ return _parse_config(packet.body)
135
+
136
+
137
+ async def set_audio_recording_config(
138
+ client: OpenZiloClient, config: AudioRecordingConfig, *, timeout_s: float | None = None,
139
+ ) -> AudioRecordingConfig:
140
+ """Set volatile defaults while idle; return verified device readback.
141
+
142
+ These settings survive a BLE reconnect, but reset on device reboot. A live
143
+ output still needs live subscription before starting. Gains are digital;
144
+ mono averages the independently scaled left/right samples before saturation.
145
+ """
146
+ if not isinstance(config, AudioRecordingConfig):
147
+ raise TypeError("config must be AudioRecordingConfig")
148
+ if client.capabilities is not None and client.capabilities.recording_limits is not None:
149
+ client.capabilities.recording_limits.validate(config)
150
+ async with client._recording_control_lock:
151
+ packet = await client.request(AudioCommand.SET_RECORDING_CONFIG, AudioCommand.RECORDING_CONFIG_SET,
152
+ _config_body(config), timeout_s=timeout_s)
153
+ applied = _parse_config(packet.body)
154
+ if applied != config:
155
+ raise ProtocolError("Audio configuration readback does not match request")
156
+ return applied
157
+
158
+
159
+ def _session_ack(body: bytes) -> int:
160
+ if len(body) < 2:
161
+ raise ProtocolError("Truncated recording response")
162
+ ensure_success(struct.unpack_from(">H", body)[0])
163
+ if len(body) != 6 or not struct.unpack_from(">I", body, 2)[0]:
164
+ raise ProtocolError("Invalid recording session response")
165
+ return struct.unpack_from(">I", body, 2)[0]
166
+
167
+
168
+ async def start_audio_recording(
169
+ client: OpenZiloClient, *, timeout_s: float | None = None,
170
+ ) -> int:
171
+ """Queue a remote recording and return its session id, not completion.
172
+
173
+ Register the live receiver first when using LIVE or LIVE_AND_FLASH. A lost
174
+ ACK leaves the outcome unknown: query status instead of retrying START.
175
+ """
176
+ async with client._recording_control_lock:
177
+ client._check_command_access(AudioCommand.START_RECORDING)
178
+ client._recording_active = True # conservative if the ACK is lost
179
+ packet = await client.request(AudioCommand.START_RECORDING, AudioCommand.RECORDING_STARTED,
180
+ timeout_s=timeout_s)
181
+ return _session_ack(packet.body)
182
+
183
+
184
+ async def stop_audio_recording(
185
+ client: OpenZiloClient, session_id: int, *, cancel: bool = False,
186
+ timeout_s: float | None = None,
187
+ ) -> int:
188
+ """Request graceful stop or discard; ACK is not a saved-file confirmation.
189
+
190
+ Repeated graceful stops of the same session are safe. A stale session id
191
+ cannot stop a newer recording. Query/wait for terminal status afterwards.
192
+ """
193
+ if isinstance(session_id, bool) or not isinstance(session_id, int) or not 1 <= session_id <= 0xFFFFFFFF:
194
+ raise ValueError("session_id must be a nonzero u32")
195
+ if not isinstance(cancel, bool):
196
+ raise ValueError("cancel must be a bool")
197
+ async with client._recording_control_lock:
198
+ packet = await client.request(AudioCommand.STOP_RECORDING, AudioCommand.RECORDING_STOPPED,
199
+ struct.pack(">IB", session_id, cancel), timeout_s=timeout_s)
200
+ returned = _session_ack(packet.body)
201
+ if returned != session_id:
202
+ raise ProtocolError("Recording stop response belongs to another session")
203
+ return returned
204
+
205
+
206
+ async def get_audio_recording_status(
207
+ client: OpenZiloClient, *, timeout_s: float | None = None,
208
+ ) -> AudioRecordingStatus:
209
+ packet = await client.request(AudioCommand.GET_RECORDING_STATUS, AudioCommand.RECORDING_STATUS,
210
+ timeout_s=timeout_s)
211
+ body = packet.body
212
+ if len(body) < 2:
213
+ raise ProtocolError("Truncated recording status")
214
+ ensure_success(struct.unpack_from(">H", body)[0])
215
+ if len(body) != 14:
216
+ raise ProtocolError("Invalid recording status length")
217
+ _, session, state, saved, error, index = struct.unpack(">HIBBHI", body)
218
+ if state > 6 or saved > 1 or (state == 0) != (session == 0):
219
+ raise ProtocolError("Invalid recording status values")
220
+ if (not saved and index) or (state == 4 and error):
221
+ raise ProtocolError("Inconsistent recording status")
222
+ if (state == 5 and not error) or (state in (0, 6) and (saved or error)):
223
+ raise ProtocolError("Inconsistent terminal recording status")
224
+ status = AudioRecordingStatus(session, AudioRecordingState(state), bool(saved), error,
225
+ index if saved else None)
226
+ client._recording_active = state in (1, 2, 3)
227
+ return status
228
+
229
+
230
+ async def wait_audio_recording_finished(
231
+ client: OpenZiloClient, session_id: int, *, timeout_s: float = 75.0,
232
+ poll_interval_s: float = 0.2,
233
+ ) -> AudioRecordingStatus:
234
+ """Wait for capture and local file commit; raise on a failed or replaced session."""
235
+ if isinstance(session_id, bool) or not isinstance(session_id, int) or not 1 <= session_id <= 0xFFFFFFFF:
236
+ raise ValueError("session_id must be a nonzero u32")
237
+ if not math.isfinite(timeout_s) or timeout_s <= 0 or not math.isfinite(poll_interval_s) or poll_interval_s <= 0:
238
+ raise ValueError("Timeout and poll interval must be finite and positive")
239
+ deadline = asyncio.get_running_loop().time() + timeout_s
240
+ while True:
241
+ remaining = deadline - asyncio.get_running_loop().time()
242
+ if remaining <= 0:
243
+ raise TimeoutError("Recording completion is unconfirmed")
244
+ status = await get_audio_recording_status(client, timeout_s=min(client.command_timeout_s, remaining))
245
+ if status.session_id != session_id:
246
+ raise ProtocolError("Recording status belongs to another session")
247
+ if status.finished:
248
+ ensure_success(status.error_code)
249
+ return status
250
+ await asyncio.sleep(min(poll_interval_s, max(0.0, deadline - asyncio.get_running_loop().time())))