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.
@@ -0,0 +1,422 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Live recording subscription and streaming receive."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import inspect
8
+ import logging
9
+ import math
10
+ import struct
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass
13
+ from typing import Any, Literal
14
+
15
+ from ._errors import AudioDecodeError, ProtocolError, TimeoutError
16
+ from ._protocol import AudioCommand, ensure_success
17
+ from ._client import OpenZiloClient
18
+ from ._codec import PcmConfig, _validate_opus_packet, build_opus_recording
19
+ from ._audio import _audio_operation, _PacketInbox
20
+ from ._tasks import await_before
21
+
22
+ _logger = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class LiveAudioSubscription:
27
+ enabled: bool
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class LiveAudioStart:
32
+ session_id: int
33
+ record_time: int
34
+ sample_rate: int
35
+ channels: int
36
+ codec: int
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class LiveAudioData:
41
+ session_id: int
42
+ sequence: int
43
+ byte_offset: int
44
+ data: bytes
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class LiveAudioEnd:
49
+ error_code: int
50
+ session_id: int
51
+ produced_bytes: int
52
+ sent_bytes: int
53
+ dropped_frames: int
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class LiveAudioRecording:
58
+ start: LiveAudioStart
59
+ end: LiveAudioEnd
60
+ data: bytes # Complete OP2C file, suitable for decode_audio_to_wav().
61
+
62
+
63
+ async def set_live_audio_subscription(
64
+ client: OpenZiloClient, enabled: bool, *, timeout_s: float | None = None,
65
+ ) -> LiveAudioSubscription:
66
+ """Enable BLE output for subsequent recordings.
67
+
68
+ AUTO/legacy output is live-only when subscribed. Extended firmware can be
69
+ configured as LIVE_AND_FLASH to retain a complete local backup.
70
+
71
+ Enabling requires NUS notifications and ATT MTU >= 128. Firmware is the
72
+ authority on MTU readiness. Disabling aborts an active live recording;
73
+ disconnect clears the subscription. This never presses the record button.
74
+ """
75
+ if enabled and client._audio_owner not in (None, asyncio.current_task()):
76
+ raise ProtocolError("Another audio operation is already active")
77
+ timeout = client.command_timeout_s if timeout_s is None else timeout_s
78
+ deadline = asyncio.get_running_loop().time() + max(0.0, timeout)
79
+ return await await_before(
80
+ _set_live_audio_subscription(client, enabled, timeout), deadline,
81
+ "Timed out waiting for live subscription response",
82
+ )
83
+
84
+
85
+ async def _set_live_audio_subscription(
86
+ client: OpenZiloClient, enabled: bool, timeout_s: float,
87
+ ) -> LiveAudioSubscription:
88
+ async with client._live_subscription_lock:
89
+ if not isinstance(enabled, bool):
90
+ raise ValueError("enabled must be a bool")
91
+ client._check_command_access(AudioCommand.LIVE_SUBSCRIBE)
92
+ # If an enable response is lost, conservatively require disable/reconnect
93
+ # before OTA rather than assuming the device still saves to Flash.
94
+ if enabled:
95
+ client._live_audio_subscribed = True
96
+ packet = await client.request(
97
+ AudioCommand.LIVE_SUBSCRIBE, AudioCommand.LIVE_SUBSCRIBE_RESP,
98
+ bytes([int(enabled)]), timeout_s=timeout_s,
99
+ )
100
+ if len(packet.body) != 3 or packet.body[2] not in (0, 1):
101
+ raise ProtocolError("Invalid live subscription response")
102
+ error = struct.unpack_from(">H", packet.body)[0]
103
+ client._live_audio_subscribed = bool(packet.body[2])
104
+ ensure_success(error)
105
+ if client._live_audio_subscribed != enabled:
106
+ raise ProtocolError("Live subscription response does not match request")
107
+ return LiveAudioSubscription(client._live_audio_subscribed)
108
+
109
+
110
+ def parse_live_audio_start(body: bytes) -> LiveAudioStart:
111
+ if len(body) != 20:
112
+ raise ProtocolError("Invalid live START length")
113
+ session, reserved1, timestamp, reserved2, rate, channels, codec = struct.unpack(">IIIIHBB", body)
114
+ if not session or reserved1 or reserved2 or rate != 16000 or channels not in (1, 2) or codec != 3:
115
+ raise ProtocolError("Unsupported live START format")
116
+ return LiveAudioStart(session, timestamp, rate, channels, codec)
117
+
118
+
119
+ def parse_live_audio_data(body: bytes, *, channels: int = 2) -> LiveAudioData:
120
+ if len(body) < 15:
121
+ raise ProtocolError("Truncated live DATA")
122
+ session, sequence, offset, length = struct.unpack_from(">IIIH", body)
123
+ if not session or not 1 <= length <= 100 or len(body) != 14 + length:
124
+ raise ProtocolError("Invalid live DATA length or session")
125
+ packet = body[14:]
126
+ try:
127
+ _validate_opus_packet(packet, channels=channels)
128
+ except AudioDecodeError as exc:
129
+ raise ProtocolError(str(exc)) from exc
130
+ return LiveAudioData(session, sequence, offset, packet)
131
+
132
+
133
+ def parse_live_audio_end(body: bytes) -> LiveAudioEnd:
134
+ if len(body) != 22:
135
+ raise ProtocolError("Invalid live END length")
136
+ error, session, reserved, produced, sent, dropped = struct.unpack(">HIIIII", body)
137
+ if not session or reserved or sent > produced:
138
+ raise ProtocolError("Invalid live END counters or session")
139
+ return LiveAudioEnd(error, session, produced, sent, dropped)
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class LivePcmFrame:
144
+ """20 ms of signed 16-bit little-endian mono/stereo PCM.
145
+
146
+ Offsets and counts are samples per channel, not bytes or BLE timestamps.
147
+ """
148
+
149
+ session_id: int
150
+ sample_offset: int
151
+ sample_count: int
152
+ data: bytes
153
+ pcm_config: PcmConfig = PcmConfig(16000, 2, 16)
154
+
155
+
156
+ class LiveAudioStream:
157
+ """A single recording's bounded START/DATA/END async event stream.
158
+
159
+ Use open_live_audio_stream() and async with. Iteration has one consumer.
160
+ Frames are provisional until a verified END; slow consumers fail explicitly.
161
+ """
162
+
163
+ def __init__(
164
+ self, client: OpenZiloClient, *, output: Literal["opus", "pcm"],
165
+ queue_size: int, timeout_s: float, recording_timeout_s: float,
166
+ ) -> None:
167
+ if output not in ("opus", "pcm"):
168
+ raise ValueError("output must be 'opus' or 'pcm'")
169
+ if isinstance(queue_size, bool) or not isinstance(queue_size, int) or queue_size < 1:
170
+ raise ValueError("queue_size must be a positive integer")
171
+ for value in (timeout_s, recording_timeout_s):
172
+ if not math.isfinite(value) or value <= 0:
173
+ raise ValueError("Live audio timeouts must be finite and positive")
174
+ self._client = client
175
+ self._output = output
176
+ self._timeout = timeout_s
177
+ self._recording_timeout = recording_timeout_s
178
+ self._queue: asyncio.Queue[LiveAudioStart | LiveAudioData | LivePcmFrame | LiveAudioEnd] = (
179
+ asyncio.Queue(maxsize=queue_size)
180
+ )
181
+ self._ready = asyncio.Event()
182
+ self._done = asyncio.Event()
183
+ self._task: asyncio.Task[None] | None = None
184
+ self._decoder: Any = None
185
+ self._error: Exception | None = None
186
+ self._start: LiveAudioStart | None = None
187
+ self._end: LiveAudioEnd | None = None
188
+ self._deadline = 0.0
189
+ self._sample_offset = 0
190
+ self._entered = False
191
+ self._active = False
192
+ self._iterating = False
193
+ self._ended = False
194
+
195
+ @property
196
+ def start(self) -> LiveAudioStart | None:
197
+ return self._start
198
+
199
+ @property
200
+ def end(self) -> LiveAudioEnd | None:
201
+ return self._end
202
+
203
+ @property
204
+ def complete(self) -> bool:
205
+ return self._end is not None
206
+
207
+ async def __aenter__(self) -> LiveAudioStream:
208
+ if self._entered:
209
+ raise ProtocolError("A live audio stream cannot be reused")
210
+ self._entered = True
211
+ if self._output == "pcm":
212
+ from ._pcm import _OpusPcmDecoder
213
+ # Fail before subscribing if the optional decoder is unavailable.
214
+ self._decoder = _OpusPcmDecoder()
215
+ self._active = True
216
+ self._task = asyncio.create_task(self._run(), name="openzilo-live-audio")
217
+ try:
218
+ await self._ready.wait()
219
+ if self._error is not None:
220
+ raise self._error
221
+ return self
222
+ except BaseException:
223
+ await self._close()
224
+ raise
225
+
226
+ async def _close(self) -> None:
227
+ self._active = False
228
+ if self._task is not None:
229
+ if not self._task.done() and not self.complete:
230
+ self._task.cancel()
231
+ await asyncio.gather(self._task, return_exceptions=True)
232
+ self._decoder = None
233
+ # Release queued frames on early exit; no complete recording is retained.
234
+ while not self._queue.empty():
235
+ self._queue.get_nowait()
236
+
237
+ async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
238
+ await self._close()
239
+ if exc_type is None and self._error is not None:
240
+ raise self._error
241
+
242
+ def __aiter__(self) -> LiveAudioStream:
243
+ return self
244
+
245
+ async def __anext__(self) -> LiveAudioStart | LiveAudioData | LivePcmFrame | LiveAudioEnd:
246
+ if not self._active:
247
+ raise ProtocolError("Consume live audio inside its async with block")
248
+ if self._iterating:
249
+ raise ProtocolError("A live audio stream allows only one consumer")
250
+ self._iterating = True
251
+ try:
252
+ if self._error is not None:
253
+ raise self._error
254
+ if self._ended:
255
+ raise StopAsyncIteration
256
+ if self._queue.empty():
257
+ if self._done.is_set():
258
+ raise StopAsyncIteration
259
+ item = asyncio.create_task(self._queue.get())
260
+ done = asyncio.create_task(self._done.wait())
261
+ try:
262
+ await asyncio.wait({item, done}, return_when=asyncio.FIRST_COMPLETED)
263
+ if self._error is not None:
264
+ raise self._error
265
+ if item.done():
266
+ event = item.result()
267
+ elif not self._queue.empty():
268
+ event = self._queue.get_nowait()
269
+ else:
270
+ raise StopAsyncIteration
271
+ finally:
272
+ for task in (item, done):
273
+ if not task.done():
274
+ task.cancel()
275
+ await asyncio.gather(item, done, return_exceptions=True)
276
+ else:
277
+ event = self._queue.get_nowait()
278
+ if isinstance(event, LiveAudioEnd):
279
+ self._ended = True
280
+ return event
281
+ finally:
282
+ self._iterating = False
283
+
284
+ def _emit(self, event: LiveAudioStart | LiveAudioData | LivePcmFrame | LiveAudioEnd) -> None:
285
+ try:
286
+ self._queue.put_nowait(event)
287
+ except asyncio.QueueFull as exc:
288
+ raise ProtocolError("Live audio consumer queue overflow; recording is incomplete") from exc
289
+
290
+ async def _decode(self, function: Callable[..., list[bytes]], *args: Any) -> None:
291
+ # Sequential worker calls preserve decoder state and keep BLE callbacks free.
292
+ task = asyncio.create_task(asyncio.to_thread(function, *args))
293
+ try:
294
+ blocks = await asyncio.shield(task)
295
+ except asyncio.CancelledError:
296
+ # A native decoder call cannot be cancelled. Join before releasing it.
297
+ await asyncio.gather(task, return_exceptions=True)
298
+ raise
299
+ if asyncio.get_running_loop().time() >= self._deadline:
300
+ raise TimeoutError("Live recording exceeded its time limit")
301
+ for block in blocks:
302
+ assert self._start is not None
303
+ self._emit(LivePcmFrame(self._start.session_id, self._sample_offset, 320, block,
304
+ PcmConfig(16000, self._start.channels, 16)))
305
+ self._sample_offset += 320
306
+
307
+ async def _run(self) -> None:
308
+ try:
309
+ await self._receive_owned(self._client, self)
310
+ except Exception as exc:
311
+ self._error = exc
312
+ finally:
313
+ self._ready.set()
314
+ self._done.set()
315
+
316
+ @staticmethod
317
+ @_audio_operation
318
+ async def _receive_owned(client: OpenZiloClient, stream: LiveAudioStream) -> None:
319
+ if client._live_audio_subscribed:
320
+ raise ProtocolError("Disable the existing live subscription before starting a managed recording")
321
+ commands = (AudioCommand.LIVE_START, AudioCommand.LIVE_DATA, AudioCommand.LIVE_END)
322
+ for command in commands:
323
+ client._drain_queue(int(command))
324
+ try:
325
+ with _PacketInbox(client, commands) as inbox:
326
+ await set_live_audio_subscription(client, True, timeout_s=stream._timeout)
327
+ stream._ready.set()
328
+ first = await inbox.wait(stream._timeout)
329
+ if first.command != AudioCommand.LIVE_START:
330
+ raise ProtocolError("Live recording did not begin with START")
331
+ stream._start = parse_live_audio_start(first.body)
332
+ if stream._decoder is not None and stream._start.channels == 1:
333
+ from ._pcm import _OpusPcmDecoder
334
+ stream._decoder = _OpusPcmDecoder(channels=1)
335
+ stream._deadline = asyncio.get_running_loop().time() + stream._recording_timeout
336
+ stream._emit(stream._start)
337
+ sequence = received = 0
338
+ while True:
339
+ remaining = stream._deadline - asyncio.get_running_loop().time()
340
+ if remaining <= 0:
341
+ raise TimeoutError("Live recording exceeded its time limit")
342
+ packet = await inbox.wait(min(5.0, remaining))
343
+ if packet.command == AudioCommand.LIVE_DATA:
344
+ frame = parse_live_audio_data(packet.body, channels=stream._start.channels)
345
+ if (frame.session_id != stream._start.session_id or frame.sequence != sequence
346
+ or frame.byte_offset != received):
347
+ raise ProtocolError("Live recording session, sequence or offset mismatch")
348
+ if sequence >= 3000:
349
+ raise ProtocolError("Live recording exceeds firmware's 60-second limit")
350
+ sequence += 1
351
+ received += len(frame.data)
352
+ if stream._decoder is None:
353
+ stream._emit(frame)
354
+ else:
355
+ await stream._decode(stream._decoder.decode, frame.data)
356
+ elif packet.command == AudioCommand.LIVE_END:
357
+ end = parse_live_audio_end(packet.body)
358
+ if end.session_id != stream._start.session_id:
359
+ raise ProtocolError("Live END belongs to another recording")
360
+ ensure_success(end.error_code)
361
+ if end.dropped_frames or end.produced_bytes != received or end.sent_bytes != received:
362
+ raise ProtocolError("Live recording is incomplete according to END counters")
363
+ if stream._decoder is not None and sequence:
364
+ await stream._decode(stream._decoder.flush)
365
+ stream._emit(end)
366
+ stream._end = end
367
+ return
368
+ else:
369
+ raise ProtocolError("Unexpected START during live recording")
370
+ finally:
371
+ if client.is_connected and client._live_audio_subscribed:
372
+ try:
373
+ await set_live_audio_subscription(client, False, timeout_s=2.0)
374
+ except Exception as exc:
375
+ _logger.warning("Could not unsubscribe live audio; disconnect before reuse: %s", exc)
376
+
377
+ def open_live_audio_stream(
378
+ client: OpenZiloClient, *, output: Literal["opus", "pcm"] = "pcm",
379
+ queue_size: int = 64, timeout_s: float = 60.0, recording_timeout_s: float = 70.0,
380
+ ) -> LiveAudioStream:
381
+ """Open one button-triggered recording as ordered START/frame/END events.
382
+
383
+ Entry confirms subscription, not recording start. PCM needs the ``pcm``
384
+ extra; Opus requires only the base SDK. Flash retention follows device
385
+ configuration; this iterator does not buffer the entire recording.
386
+ Context exit aborts unfinished capture and attempts bounded unsubscribe.
387
+ """
388
+ return LiveAudioStream(client, output=output, queue_size=queue_size,
389
+ timeout_s=timeout_s, recording_timeout_s=recording_timeout_s)
390
+
391
+
392
+ async def receive_live_audio_file(
393
+ client: OpenZiloClient, *, on_packet: Callable[[LiveAudioData], Any] | None = None,
394
+ on_subscribed: Callable[[], Any] | None = None,
395
+ timeout_s: float = 60.0, recording_timeout_s: float = 70.0,
396
+ ) -> LiveAudioRecording:
397
+ """Collect the verified Opus event stream into one complete OP2C recording.
398
+
399
+ Callbacks may be sync or async and must return promptly. Slow callbacks
400
+ fail with a bounded queue overflow rather than silently dropping audio.
401
+ """
402
+ packets: list[bytes] = []
403
+ async with open_live_audio_stream(
404
+ client, output="opus", queue_size=client._receive_queue_size,
405
+ timeout_s=timeout_s, recording_timeout_s=recording_timeout_s,
406
+ ) as stream:
407
+ if on_subscribed is not None:
408
+ result = on_subscribed()
409
+ if inspect.isawaitable(result):
410
+ await await_before(result, asyncio.get_running_loop().time() + timeout_s,
411
+ "on_subscribed callback timed out")
412
+ async for event in stream:
413
+ if isinstance(event, LiveAudioData):
414
+ packets.append(event.data)
415
+ if on_packet is not None:
416
+ result = on_packet(event)
417
+ if inspect.isawaitable(result):
418
+ await await_before(result, stream._deadline,
419
+ "Live recording exceeded its time limit")
420
+ assert stream.start is not None and stream.end is not None
421
+ return LiveAudioRecording(stream.start, stream.end,
422
+ build_opus_recording(packets, channels=stream.start.channels))
openzilo/_ota.py ADDED
@@ -0,0 +1,257 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Application firmware update over BLE."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import math
8
+ from collections.abc import Awaitable, Callable
9
+ from typing import Any
10
+
11
+ from ._firmware_bundle import inspect_firmware_bundle
12
+ from ._errors import ProtocolError, TimeoutError, TransportError
13
+ from ._protocol import (
14
+ _OtaCommand,
15
+ BinaryReader,
16
+ BinaryWriter,
17
+ crc16_compute,
18
+ ensure_success,
19
+ Packet,
20
+ )
21
+ from ._client import _ota_context, OpenZiloClient
22
+ from ._device import get_system_info, SystemInfo
23
+ from ._tasks import await_before
24
+
25
+
26
+ def _board_identity(board: str | None) -> tuple[str, ...] | None:
27
+ # Zephyr BOARD_QUALIFIERS may already start with '/'. Preserve signed
28
+ # metadata verbatim; ignore empty separators only for identity comparison.
29
+ if not board:
30
+ return None
31
+ parts = tuple(part for part in board.split("/") if part)
32
+ if not parts or any(part in (".", "..") for part in parts):
33
+ return None
34
+ return parts
35
+
36
+
37
+ async def _ota_timed(operation: Awaitable[Any], timeout: float, phase: str) -> Any:
38
+ deadline = asyncio.get_running_loop().time() + max(0.0, timeout)
39
+ message = f"Firmware update timed out during {phase}; installation is unconfirmed"
40
+ return await await_before(operation, deadline, message)
41
+
42
+
43
+ async def _wait_ota_packet(
44
+ client: OpenZiloClient,
45
+ queue: asyncio.Queue[Packet],
46
+ timeout: float,
47
+ ) -> Packet:
48
+ # Notifications and the reboot disconnect may arrive in the same event-loop turn.
49
+ # The local queue survives disconnect, unlike the ordinary command queues.
50
+ if not client._protocol_errors.empty():
51
+ raise client._protocol_errors.get_nowait()
52
+ if not queue.empty():
53
+ return queue.get_nowait()
54
+ packet_task = asyncio.create_task(queue.get())
55
+ error_task = asyncio.create_task(client._protocol_errors.get())
56
+ disconnect_task = asyncio.create_task(client._disconnected.wait())
57
+ tasks = {packet_task, error_task, disconnect_task}
58
+ try:
59
+ done, _ = await asyncio.wait(tasks, timeout=max(0.0, timeout),
60
+ return_when=asyncio.FIRST_COMPLETED)
61
+ if error_task in done:
62
+ raise error_task.result()
63
+ if packet_task in done:
64
+ return packet_task.result()
65
+ if disconnect_task in done:
66
+ raise TransportError("BLE disconnected before OTA transfer confirmation; installation is unconfirmed")
67
+ raise TimeoutError("Timed out waiting for OTA data request or result; installation is unconfirmed")
68
+ finally:
69
+ for task in tasks:
70
+ if not task.done():
71
+ task.cancel()
72
+ await asyncio.gather(*tasks, return_exceptions=True)
73
+
74
+
75
+ async def _verify_firmware_restart(
76
+ client: OpenZiloClient,
77
+ before: SystemInfo,
78
+ version: str,
79
+ timeout_s: float,
80
+ reboot_timeout_s: float,
81
+ ) -> SystemInfo:
82
+ loop = asyncio.get_running_loop()
83
+ deadline = loop.time() + reboot_timeout_s
84
+ await _ota_timed(client._disconnected.wait(), reboot_timeout_s, "waiting for device reboot")
85
+ last_error: Exception | None = None
86
+ while loop.time() < deadline:
87
+ remaining = min(timeout_s, deadline - loop.time())
88
+ try:
89
+ await _ota_timed(client.disconnect(), remaining, "connection cleanup")
90
+ await _ota_timed(client.connect(), min(timeout_s, deadline - loop.time()), "reconnection")
91
+ after = await _ota_timed(
92
+ get_system_info(client, timeout_s=timeout_s),
93
+ min(timeout_s, deadline - loop.time()), "version verification",
94
+ )
95
+ except (TransportError, TimeoutError, OSError) as exc:
96
+ last_error = exc
97
+ await asyncio.sleep(min(1.0, max(0.0, deadline - loop.time())))
98
+ continue
99
+ if after.model != before.model or (before.cpuid and after.cpuid != before.cpuid) or (
100
+ before.sn and after.sn != before.sn
101
+ ):
102
+ raise ProtocolError("Reconnected device identity differs; installation is unconfirmed")
103
+ if after.firmware_version != version:
104
+ raise ProtocolError(
105
+ f"Firmware version verification failed: expected {version}, "
106
+ f"device reports {after.firmware_version}"
107
+ )
108
+ return after
109
+ raise TimeoutError("Could not reconnect and verify the new firmware; installation is unconfirmed") from last_error
110
+
111
+
112
+ async def update_firmware(
113
+ client: OpenZiloClient,
114
+ firmware: bytes,
115
+ *,
116
+ trusted_public_key: bytes,
117
+ allow_test_firmware: bool = False,
118
+ progress: Callable[[int, int], None] | None = None,
119
+ timeout_s: float = 30.0,
120
+ total_timeout_s: float = 600.0,
121
+ reboot_timeout_s: float = 90.0,
122
+ ) -> SystemInfo:
123
+ """Upload an official APP package, await reboot, and verify its running version.
124
+
125
+ Use this connected client exclusively until the call finishes. Stop recording
126
+ and IMU streaming first. Signed ZIPs require an independently trusted PEM
127
+ public key; only the verified payload is transmitted. Raw BIN inputs are
128
+ rejected. Version and compatibility come only from signed metadata.
129
+ ``progress(sent, total)`` reports transfer progress, not installation success.
130
+ The return value is system information read after reboot. A timeout or
131
+ disconnect before confirmation never implies a successful installation.
132
+ """
133
+ bundle = inspect_firmware_bundle(firmware, trusted_public_key=trusted_public_key)
134
+ if bundle.profile == "test" and not allow_test_firmware:
135
+ raise ValueError("Test firmware requires allow_test_firmware=True")
136
+ version, data = bundle.version, bundle.payload
137
+ for name, value in (("timeout_s", timeout_s), ("total_timeout_s", total_timeout_s),
138
+ ("reboot_timeout_s", reboot_timeout_s)):
139
+ if not math.isfinite(value) or value <= 0:
140
+ raise ValueError(f"{name} must be finite and greater than zero")
141
+ if client._firmware_update_active:
142
+ raise ProtocolError("A firmware update is already running on this client")
143
+ if client._recording_active:
144
+ raise ProtocolError("Confirm recording completion with get_audio_recording_status before OTA")
145
+ if client._live_audio_subscribed:
146
+ raise ProtocolError("Disable live audio subscription before updating firmware")
147
+ if (client._audio_owner is not None or client._write_lock.locked()
148
+ or any(lock.locked() for lock in client._request_locks.values())):
149
+ raise ProtocolError("Finish active audio operations and requests before updating firmware")
150
+ if not client.is_connected:
151
+ raise TransportError("Connect the client before updating firmware")
152
+
153
+ commands = (_OtaCommand.NOTIFY_RESP, _OtaCommand.GET_PACKET, _OtaCommand.UPDATE_RESULT)
154
+ if any(int(command) in client._callback_only for command in commands):
155
+ raise ProtocolError("Remove callback-only OTA handlers before updating firmware")
156
+ queue: asyncio.Queue[Packet] = asyncio.Queue(maxsize=16)
157
+ queue_error: ProtocolError | None = None
158
+
159
+ def on_packet(packet: Packet) -> None:
160
+ nonlocal queue_error
161
+ # This session owns OTA responses, so do not accumulate duplicate copies.
162
+ client._drain_queue(int(packet.command))
163
+ if queue.full():
164
+ queue_error = ProtocolError("OTA response queue overflow")
165
+ else:
166
+ queue.put_nowait(packet)
167
+
168
+ had_capabilities = client.capabilities is not None
169
+ client._firmware_update_active = True
170
+ client._firmware_update_owner = object()
171
+ ota_token = _ota_context.set(client._firmware_update_owner)
172
+ for command in commands:
173
+ client._drain_queue(int(command))
174
+ client.add_packet_handler(command, on_packet)
175
+ client._drain_protocol_errors()
176
+ loop = asyncio.get_running_loop()
177
+ deadline = loop.time() + total_timeout_s
178
+
179
+ def remaining() -> float:
180
+ budget = deadline - loop.time()
181
+ if budget <= 0:
182
+ raise TimeoutError("Firmware transfer exceeded total_timeout_s; installation is unconfirmed")
183
+ return min(timeout_s, budget)
184
+
185
+ try:
186
+ budget = remaining()
187
+ before = await _ota_timed(get_system_info(client, timeout_s=timeout_s), budget, "device check")
188
+ if before.model != bundle.model:
189
+ raise ProtocolError("Device model differs from signed manifest")
190
+ from ._compatibility import get_device_capabilities
191
+ capabilities = await _ota_timed(
192
+ get_device_capabilities(client, timeout_s=timeout_s), remaining(), "board check")
193
+ if (_board_identity(capabilities.board_target) is None
194
+ or _board_identity(capabilities.board_target) != _board_identity(bundle.board)):
195
+ raise ProtocolError("Device board is unknown or differs from signed manifest")
196
+ if bundle.source_versions and before.firmware_version not in bundle.source_versions:
197
+ raise ProtocolError("Starting firmware version is not supported by signed manifest")
198
+ if before.firmware_version == version:
199
+ raise ProtocolError("Device already reports the target version; no update was started")
200
+ notify = (BinaryWriter().u32(2).string_u32(version).u32(len(data))
201
+ .u16(crc16_compute(data)).build())
202
+ while not queue.empty():
203
+ queue.get_nowait()
204
+ budget = remaining()
205
+ await _ota_timed(client.send_command(_OtaCommand.NOTIFY, notify), budget, "update request")
206
+ sent_end: int | None = None
207
+ if progress is not None:
208
+ progress(0, len(data))
209
+ while True:
210
+ if queue_error is not None:
211
+ raise queue_error
212
+ packet = await _wait_ota_packet(client, queue, remaining())
213
+ if queue_error is not None:
214
+ raise queue_error
215
+ reader = BinaryReader(packet.body)
216
+ if packet.command in (_OtaCommand.NOTIFY_RESP, _OtaCommand.UPDATE_RESULT):
217
+ if len(packet.body) != 2:
218
+ raise ProtocolError("Invalid OTA status response length")
219
+ ensure_success(reader.u16())
220
+ if packet.command == _OtaCommand.UPDATE_RESULT:
221
+ if sent_end != len(data):
222
+ raise ProtocolError("OTA success arrived before the package was transferred")
223
+ break
224
+ continue
225
+ if len(packet.body) != 12:
226
+ raise ProtocolError("Invalid OTA data request length")
227
+ ensure_success(reader.u16())
228
+ upgrade_type, offset, window = reader.u16(), reader.u32(), reader.u32()
229
+ # Subsequent requests use type 0; type 2 denotes the user application.
230
+ if upgrade_type not in (0, 2):
231
+ raise ProtocolError("Unexpected OTA upgrade type")
232
+ if not 1 <= window <= 4096 or offset >= len(data):
233
+ raise ProtocolError("Invalid OTA offset or window size")
234
+ if sent_end is not None and offset > sent_end:
235
+ raise ProtocolError("OTA request skipped bytes that were never sent")
236
+ # A nonzero first offset is the device's continuation point. Repeated
237
+ # requests are answered from the same immutable package bytes.
238
+ end = min(offset + window, len(data))
239
+ body = BinaryWriter().u16(0).u32(offset).u32(end - offset).bytes(data[offset:end]).build()
240
+ budget = remaining()
241
+ await _ota_timed(client.send_command(_OtaCommand.PACKET_RESP, body), budget, "data transfer")
242
+ previous = sent_end or 0
243
+ sent_end = max(previous, end)
244
+ if progress is not None and sent_end > previous:
245
+ progress(sent_end, len(data))
246
+ info = await _verify_firmware_restart(client, before, version, timeout_s, reboot_timeout_s)
247
+ if had_capabilities:
248
+ from ._compatibility import get_device_capabilities
249
+ await get_device_capabilities(client, timeout_s=min(timeout_s, 3.0))
250
+ return info
251
+ finally:
252
+ for command in commands:
253
+ client.remove_packet_handler(command, on_packet)
254
+ client._drain_queue(int(command))
255
+ client._firmware_update_active = False
256
+ client._firmware_update_owner = None
257
+ _ota_context.reset(ota_token)