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,224 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Interactive charging-case calibration; candidates are saved only after validation."""
3
+ import asyncio
4
+ from dataclasses import asdict, replace
5
+ import json
6
+ import sys
7
+
8
+ from contextlib import suppress
9
+
10
+ from ._client import OpenZiloClient
11
+ from ._sensor import start_sensor_report, stop_sensor_report
12
+ from ._device import get_system_info, enable_time_sync
13
+ from ._imu_calibration import (
14
+ ImuCalibration, ImuStaticWindow, collect_imu_static_window, fit_imu_gyro_bias,
15
+ fit_imu_six_face_calibration, validate_imu_calibration,
16
+ )
17
+ from ._imu_profiles import (
18
+ ImuCalibrationProfile, imu_calibration_path, imu_device_key,
19
+ load_imu_calibration_profile, save_imu_calibration_profile, require_software_imu_source,
20
+ )
21
+
22
+
23
+
24
+ async def _prompt(message, *, client=None):
25
+ print(message, end='', flush=True)
26
+ loop = asyncio.get_running_loop()
27
+ future = loop.create_future()
28
+ def read():
29
+ line = sys.stdin.readline()
30
+ if not future.done():
31
+ if not line:
32
+ future.set_exception(EOFError('Calibration cancelled; no new parameters were saved'))
33
+ else:
34
+ future.set_result(line)
35
+ async def discard_idle_samples():
36
+ while True:
37
+ await asyncio.sleep(0.1)
38
+ client._drain_queue(0x0605)
39
+ discarder = asyncio.create_task(discard_idle_samples()) if client else None
40
+ try:
41
+ loop.add_reader(sys.stdin.fileno(), read)
42
+ except (NotImplementedError, PermissionError):
43
+ try:
44
+ return await asyncio.to_thread(input)
45
+ finally:
46
+ if discarder:
47
+ discarder.cancel()
48
+ with suppress(asyncio.CancelledError): await discarder
49
+ try:
50
+ return await future
51
+ finally:
52
+ loop.remove_reader(sys.stdin.fileno())
53
+ if discarder:
54
+ discarder.cancel()
55
+ with suppress(asyncio.CancelledError): await discarder
56
+
57
+
58
+ def _correct_window(window, calibration, *, accel=False, gyro=False):
59
+ """Validation uses NEW raw windows, transformed in software like the stream."""
60
+ return ImuStaticWindow(
61
+ tuple((v-calibration.accel_bias_ug[i]/1e6)*calibration.accel_scale_ppm[i]/1e6
62
+ if accel else v for i, v in enumerate(window.accel_g)),
63
+ tuple(v-calibration.gyro_bias_udps[i]/1e6 if gyro else v
64
+ for i, v in enumerate(window.gyro_dps)),
65
+ window.accel_std_g, window.gyro_std_dps, window.samples,
66
+ )
67
+
68
+
69
+ async def cmd_imu_calibration(args):
70
+ path = args.profile or imu_calibration_path(args.address)
71
+ if args.action == 'show':
72
+ profile = load_imu_calibration_profile(path)
73
+ if profile.device_key != imu_device_key(args.address):
74
+ raise ValueError('Profile belongs to another device')
75
+ print(json.dumps({'path': str(path), 'application': 'software', **asdict(profile)}, indent=2))
76
+ return
77
+ if args.action == 'reset':
78
+ if path.exists() and load_imu_calibration_profile(path).device_key != imu_device_key(args.address):
79
+ raise ValueError('Profile belongs to another device')
80
+ path.unlink(missing_ok=True)
81
+ print('Local software calibration profile removed.')
82
+ return
83
+ if not 2 <= args.seconds <= 120:
84
+ raise ValueError('--seconds must be between 2 and 120')
85
+ async with OpenZiloClient(address=args.address, scan_timeout_s=args.scan_timeout,
86
+ connect_timeout_s=args.connect_timeout) as client:
87
+ await require_software_imu_source(client)
88
+ info = await get_system_info(client)
89
+ enable_time_sync(client)
90
+ previous = load_imu_calibration_profile(path) if path.exists() else None
91
+ if previous:
92
+ previous.check_device(args.address, info.firmware_version, info.model)
93
+ accel_stage = args.action in ('accel', 'full')
94
+ gyro_stage = args.action in ('quick', 'full')
95
+ streaming = False
96
+ candidate = None
97
+ accel_validated = previous.accel_validated if previous else False
98
+ gyro_validated = previous.gyro_validated if previous else False
99
+ accel_report = gyro_report = None
100
+
101
+ async def prompt(message):
102
+ return await _prompt(message, client=client)
103
+
104
+ async def stop():
105
+ nonlocal streaming
106
+ if streaming:
107
+ await stop_sensor_report(client)
108
+ streaming = False
109
+
110
+ async def start():
111
+ nonlocal streaming, candidate
112
+ streaming = True # A timed-out start may still have enabled capture.
113
+ config = await start_sensor_report(client)
114
+ client._drain_queue(0x0605)
115
+ if candidate is None:
116
+ candidate = previous.calibration if previous else ImuCalibration.identity(config)
117
+ if (config.accel_range_g != candidate.accel_range_g or
118
+ config.gyro_range_dps != candidate.gyro_range_dps):
119
+ raise ValueError('IMU ranges differ from the local profile; reset the profile and recalibrate')
120
+ return config
121
+
122
+ async def window(config, seconds, *, gyro=True):
123
+ try:
124
+ return await collect_imu_static_window(client, config, seconds=seconds,
125
+ settle_seconds=2, check_gyro=gyro)
126
+ except ValueError as exc:
127
+ print(str(exc), flush=True)
128
+ return None
129
+
130
+ async def stable_gyro(config):
131
+ print('Keep the ring still. Waiting for consecutive stable windows (up to 3 minutes).')
132
+ history = []
133
+ deadline = asyncio.get_running_loop().time() + 180
134
+ while asyncio.get_running_loop().time() < deadline:
135
+ w = await window(config, 5)
136
+ if w is None:
137
+ history.clear()
138
+ continue
139
+ history = (history + [w])[-3:]
140
+ print('Current stationary angular velocity (deg/s): ' + ', '.join(f'{v:.3f}' for v in w.gyro_dps), flush=True)
141
+ if len(history) == 3 and all(
142
+ max(v.gyro_dps[i] for v in history)-min(v.gyro_dps[i] for v in history) <= 0.08
143
+ for i in range(3)):
144
+ return
145
+ raise ValueError('Readings did not stabilize; the local profile was not updated. Wait for a stable temperature and retry')
146
+
147
+ try:
148
+ print('Calibration is computed, saved and applied locally by OpenZilo.')
149
+ if accel_stage:
150
+ print('Secure the ring in the charging case. Keep it attached throughout all six faces.')
151
+ config = await start()
152
+ faces = {}
153
+ while len(faces) < 6:
154
+ await prompt(f'Collected {list(faces)}. Place the case on an unused face, release it, then press Enter: ')
155
+ w = await window(config, args.seconds, gyro=False)
156
+ if w is None:
157
+ continue
158
+ try:
159
+ face = w.face
160
+ except ValueError as exc:
161
+ print(str(exc)); continue
162
+ if face in faces:
163
+ print(f'{face} is already collected. Choose another face.'); continue
164
+ faces[face] = w
165
+ print(f'Accepted {face}.')
166
+ candidate = fit_imu_six_face_calibration(candidate, list(faces.values()))
167
+ validations = []
168
+ print('Candidate parameters are ready. Collecting fresh data for software validation.')
169
+ while len(validations) < 3:
170
+ await prompt(f'Accelerometer validation {len(validations)+1}: choose a face on another axis, release the case, then press Enter: ')
171
+ w = await window(config, max(5, args.seconds), gyro=False)
172
+ if w is None:
173
+ continue
174
+ corrected = _correct_window(w, candidate, accel=True)
175
+ try:
176
+ if corrected.face[0] in {v.face[0] for v in validations}:
177
+ print('This axis is already validated. Choose another axis.'); continue
178
+ except ValueError as exc:
179
+ print(str(exc)); continue
180
+ validations.append(corrected)
181
+ accel_report = validate_imu_calibration(validations, full=True, component='accel')
182
+ accel_validated = True
183
+ await stop()
184
+ print('Accelerometer independent validation passed.')
185
+
186
+ if gyro_stage and args.action == 'full' and candidate.gyro_range_dps == 0:
187
+ gyro_stage = False
188
+ if gyro_stage:
189
+ print('Remove the ring from the case and keep it away from magnets. Lay it flat; use paper support to prevent rolling if needed.')
190
+ await prompt('Place the ring still, release it, then press Enter to start gyroscope calibration: ')
191
+ config = await start()
192
+ if not config.gyro_range_dps:
193
+ raise ValueError('This sensor has no gyroscope; use accel to calibrate its accelerometer')
194
+ await stable_gyro(config)
195
+ gyro_window = None
196
+ for _ in range(3):
197
+ gyro_window = await window(config, max(20, args.seconds))
198
+ if gyro_window is not None:
199
+ break
200
+ if gyro_window is None:
201
+ raise ValueError('Could not collect stable gyroscope data; the local profile was not updated')
202
+ candidate = fit_imu_gyro_bias(candidate, gyro_window)
203
+ await prompt('Keep the ring flat and still. Press Enter to collect fresh validation data: ')
204
+ verification = None
205
+ for _ in range(3):
206
+ verification = await window(config, max(5, args.seconds))
207
+ if verification is not None:
208
+ break
209
+ if verification is None:
210
+ raise ValueError('Could not collect stable validation data; the local profile was not updated')
211
+ gyro_report = validate_imu_calibration(
212
+ [_correct_window(verification, candidate, gyro=True)], full=False, component='gyro')
213
+ gyro_validated = True
214
+ await stop()
215
+
216
+ profile = ImuCalibrationProfile(imu_device_key(args.address), info.firmware_version, info.model,
217
+ candidate, accel_validated, gyro_validated)
218
+ save_imu_calibration_profile(profile, path)
219
+ print(f'Validation passed. Local software calibration profile saved: {path}')
220
+ print(json.dumps({'calibration': asdict(candidate), 'accel_validated': accel_validated,
221
+ 'gyro_validated': gyro_validated, 'accel_validation': accel_report,
222
+ 'gyro_validation': gyro_report}, indent=2))
223
+ finally:
224
+ await stop()
@@ -0,0 +1,46 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Local CLI preferences; device identifiers never belong in the repository."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+
12
+ def config_path() -> Path:
13
+ if os.environ.get("OPENZILO_CONFIG"):
14
+ return Path(os.environ["OPENZILO_CONFIG"]).expanduser()
15
+ root = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
16
+ return root / "openzilo" / "config.json"
17
+
18
+
19
+ def load_address() -> str | None:
20
+ path = config_path()
21
+ try:
22
+ data = json.loads(path.read_text(encoding="utf-8"))
23
+ except FileNotFoundError:
24
+ return None
25
+ except (ValueError, UnicodeError) as exc:
26
+ raise ValueError(f"Invalid CLI config at {path}; use 'device forget' to reset it") from exc
27
+ if not isinstance(data, dict) or not isinstance(data.get("address"), str) or not data["address"].strip():
28
+ raise ValueError(f"Invalid CLI config at {path}; use 'device forget' to reset it")
29
+ return data["address"].strip()
30
+
31
+
32
+ def save_address(address: str) -> None:
33
+ address = address.strip()
34
+ if not address:
35
+ raise ValueError("Device address must not be empty")
36
+ path = config_path()
37
+ path.parent.mkdir(parents=True, exist_ok=True)
38
+ # Atomic replacement avoids leaving a truncated config on interruption.
39
+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".openzilo-")
40
+ try:
41
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
42
+ json.dump({"address": address}, stream)
43
+ stream.write("\n")
44
+ os.replace(temporary, path)
45
+ finally:
46
+ Path(temporary).unlink(missing_ok=True)
openzilo/_client.py ADDED
@@ -0,0 +1,364 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Protocol session: request/response matching and packet dispatch."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import inspect
8
+ import logging
9
+ from collections import defaultdict
10
+ from collections.abc import Awaitable, Callable
11
+ from contextvars import ContextVar
12
+ from enum import IntEnum
13
+ from typing import Any, DefaultDict
14
+
15
+ from ._errors import CompatibilityError, DeviceError, ProtocolError, TimeoutError, TransportError
16
+ from ._tasks import acquire_before, await_before, start_background_task
17
+ from ._protocol import BinaryReader, encode_packet, Packet, PacketStream, SystemCommand, TimeCommand
18
+ from ._compatibility import COMMAND_FEATURES, DeviceCapabilities
19
+ from ._transport import BleDeviceInfo, DEFAULT_SCAN_TIMEOUT_S, NusClient
20
+
21
+ _logger = logging.getLogger(__name__)
22
+ DEFAULT_COMMAND_TIMEOUT_S = 10.0
23
+ _ota_context: ContextVar[object | None] = ContextVar("openzilo_ota", default=None)
24
+ PacketHandler = Callable[[Packet], None | Awaitable[None]]
25
+
26
+
27
+ class OpenZiloClient:
28
+ """High-level BLE protocol client."""
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ address: str | None = None,
34
+ device: BleDeviceInfo | None = None,
35
+ scan_timeout_s: float = DEFAULT_SCAN_TIMEOUT_S,
36
+ connect_timeout_s: float = 30.0,
37
+ command_timeout_s: float = DEFAULT_COMMAND_TIMEOUT_S,
38
+ transport: NusClient | None = None,
39
+ receive_queue_size: int = 256,
40
+ allow_unverified_features: bool = False,
41
+ ) -> None:
42
+ if not isinstance(receive_queue_size, int) or receive_queue_size < 1:
43
+ raise ValueError("receive_queue_size must be a positive integer")
44
+ self._capability_check_required = False
45
+ self.capabilities: DeviceCapabilities | None = None
46
+ self.allow_unverified_features = allow_unverified_features
47
+ self._capability_lock = asyncio.Lock()
48
+ self._request_errors: dict[int, asyncio.Future[DeviceError]] = {}
49
+ self.command_timeout_s = command_timeout_s
50
+ self.transport = transport if transport is not None else NusClient(
51
+ address=address, device=device, scan_timeout_s=scan_timeout_s,
52
+ connect_timeout_s=connect_timeout_s,
53
+ )
54
+ self._stream = PacketStream()
55
+ self._queues: DefaultDict[int, asyncio.Queue[Packet]] = defaultdict(
56
+ lambda: asyncio.Queue(maxsize=receive_queue_size)
57
+ )
58
+ self._handlers: DefaultDict[int, list[PacketHandler]] = defaultdict(list)
59
+ self._protocol_errors: asyncio.Queue[ProtocolError] = asyncio.Queue(maxsize=1)
60
+ self._request_locks: DefaultDict[int, asyncio.Lock] = defaultdict(asyncio.Lock)
61
+ self._callback_only: set[int] = set()
62
+ self._audio_owner: asyncio.Task[Any] | None = None
63
+ self._firmware_update_owner: object | None = None
64
+ self._live_audio_subscribed = False
65
+ self._recording_active = False
66
+ self._recording_control_lock = asyncio.Lock()
67
+ self._live_subscription_lock = asyncio.Lock()
68
+ self._receive_queue_size = receive_queue_size
69
+ self._disconnected = asyncio.Event()
70
+ self._disconnected.set()
71
+ self._connection_ready = asyncio.Event()
72
+ self._connection_token: object | None = None
73
+ self._rssi_lock = asyncio.Lock()
74
+ self._rssi_failed_connection: object | None = None
75
+ self._time_sync_enabled = False
76
+ self._write_lock = asyncio.Lock()
77
+ self._write_interrupted = False
78
+ self._callback_tasks: set[asyncio.Task[Any]] = set()
79
+ self._firmware_update_active = False
80
+
81
+ @staticmethod
82
+ async def discover(*args: Any, **kwargs: Any) -> list[BleDeviceInfo]:
83
+ return await NusClient.discover(*args, **kwargs)
84
+
85
+ @property
86
+ def is_connected(self) -> bool:
87
+ return self.transport.is_connected
88
+
89
+ async def connect(self) -> None:
90
+ self._capability_check_required = False
91
+ self.capabilities = None
92
+ self._clear_receive_state()
93
+ self._connection_token = object()
94
+ self._connection_ready = asyncio.Event()
95
+ self._write_interrupted = False
96
+ self._disconnected.clear()
97
+ self.transport.set_rx_callback(self._on_rx)
98
+ set_disconnect_callback = getattr(
99
+ self.transport,
100
+ "_set_disconnect_callback",
101
+ None,
102
+ )
103
+ if callable(set_disconnect_callback):
104
+ set_disconnect_callback(self._on_disconnect)
105
+ try:
106
+ await self.transport.connect()
107
+ if self._disconnected.is_set() or not self.is_connected:
108
+ raise TransportError("BLE disconnected before the connection became ready")
109
+ self._connection_ready.set()
110
+ except BaseException:
111
+ self._on_disconnect()
112
+ raise
113
+
114
+ async def disconnect(self) -> None:
115
+ # Stop automatic replies before stop_notify/disconnect starts closing BLE.
116
+ self._on_disconnect()
117
+ try:
118
+ await self.transport.disconnect()
119
+ finally:
120
+ self._on_disconnect()
121
+
122
+ def _check_command_access(self, command: int | IntEnum) -> None:
123
+ feature = COMMAND_FEATURES.get(int(command))
124
+ if feature and self._capability_lock.locked():
125
+ raise ProtocolError("Wait for capability discovery before enhanced commands")
126
+ if feature and self._capability_check_required and self.capabilities is None:
127
+ raise CompatibilityError("Capability discovery failed; rediscover before enhanced commands")
128
+ if feature and self.capabilities is not None and not (
129
+ self.allow_unverified_features and self.capabilities.source == "unknown"
130
+ ):
131
+ self.capabilities.require(feature)
132
+ if (self._firmware_update_active
133
+ and _ota_context.get() is not self._firmware_update_owner
134
+ and int(command) != int(TimeCommand.RESPONSE)):
135
+ raise ProtocolError("Firmware update owns this connection")
136
+
137
+ async def send_command(self, command: int | IntEnum, body: bytes = b"") -> None:
138
+ await self._send_command(command, lambda: body)
139
+
140
+ async def _send_when_ready(
141
+ self, command: int | IntEnum, body: Callable[[], bytes], connection: object | None,
142
+ ) -> None:
143
+ """Defer an automatic reply, keeping it scoped to its originating connection."""
144
+ if connection is None or connection is not self._connection_token:
145
+ return
146
+ await self._connection_ready.wait()
147
+ await self._send_command(command, body, connection=connection)
148
+
149
+ async def _send_command(
150
+ self, command: int | IntEnum, body: Callable[[], bytes], *, connection: object | None = None,
151
+ ) -> None:
152
+ self._check_command_access(command)
153
+ # Keep fragmented writes (including automatic time replies) contiguous.
154
+ async with self._write_lock:
155
+ if connection is not None and (
156
+ connection is not self._connection_token or self._disconnected.is_set()
157
+ ):
158
+ return
159
+ self._check_command_access(command)
160
+ if self._write_interrupted:
161
+ raise TransportError("A previous BLE write was interrupted; reconnect before sending")
162
+ write_connection = self._connection_token
163
+ try:
164
+ # Build time-sensitive bodies only after acquiring the write lock.
165
+ await self.transport.write(encode_packet(int(command), body()))
166
+ except asyncio.CancelledError:
167
+ # A fragmented packet may be half-sent; another packet would desynchronize the device.
168
+ if write_connection is self._connection_token:
169
+ self._write_interrupted = True
170
+ raise
171
+
172
+ async def request(
173
+ self,
174
+ command: int | IntEnum,
175
+ response_command: int | IntEnum,
176
+ body: bytes = b"",
177
+ *,
178
+ timeout_s: float | None = None,
179
+ ) -> Packet:
180
+ self._check_command_access(command)
181
+ response_id = int(response_command)
182
+ if response_id in self._callback_only:
183
+ raise ProtocolError("Response command is owned by a callback-only handler")
184
+ timeout = self.command_timeout_s if timeout_s is None else timeout_s
185
+ deadline = asyncio.get_running_loop().time() + max(0.0, timeout)
186
+ message = f"Timed out waiting for command 0x{response_id:04X}"
187
+ lock = self._request_locks[response_id]
188
+ await acquire_before(lock, deadline, message)
189
+ error_future: asyncio.Future[DeviceError] | None = None
190
+ try:
191
+ self._check_command_access(command)
192
+ if int(command) in self._request_errors:
193
+ raise ProtocolError("Concurrent requests for the same command are ambiguous")
194
+ error_future = asyncio.get_running_loop().create_future()
195
+ self._request_errors[int(command)] = error_future
196
+ self._drain_queue(response_id)
197
+ self._drain_protocol_errors()
198
+ await await_before(self.send_command(command, body), deadline, message)
199
+ return await self._wait_for_command(
200
+ response_id, timeout_s=deadline - asyncio.get_running_loop().time(),
201
+ request_error=error_future,
202
+ )
203
+ finally:
204
+ if error_future is not None:
205
+ self._request_errors.pop(int(command), None)
206
+ error_future.cancel()
207
+ lock.release()
208
+
209
+ async def wait_for_command(
210
+ self,
211
+ command: int | IntEnum,
212
+ *,
213
+ timeout_s: float | None = None,
214
+ ) -> Packet:
215
+ return await self._wait_for_command(command, timeout_s=timeout_s)
216
+
217
+ async def _wait_for_command(
218
+ self, command: int | IntEnum, *, timeout_s: float | None = None,
219
+ request_error: asyncio.Future[DeviceError] | None = None,
220
+ ) -> Packet:
221
+ self._check_command_access(command)
222
+ command_id = int(command)
223
+ if command_id in self._callback_only:
224
+ raise ProtocolError("Command is owned by a callback-only handler")
225
+ timeout = self.command_timeout_s if timeout_s is None else timeout_s
226
+ if self._disconnected.is_set():
227
+ raise TransportError(
228
+ f"BLE disconnected while waiting for command 0x{command_id:04X}"
229
+ )
230
+
231
+ packet_task = asyncio.create_task(self._queues[command_id].get())
232
+ error_task = asyncio.create_task(self._protocol_errors.get())
233
+ disconnect_task = asyncio.create_task(self._disconnected.wait())
234
+ tasks = {packet_task, error_task, disconnect_task}
235
+ if request_error is not None:
236
+ tasks.add(request_error)
237
+ try:
238
+ done, _pending = await asyncio.wait(
239
+ tasks,
240
+ timeout=max(0.0, timeout),
241
+ return_when=asyncio.FIRST_COMPLETED,
242
+ )
243
+ if not done:
244
+ raise TimeoutError(
245
+ f"Timed out waiting for command 0x{command_id:04X}"
246
+ )
247
+ if request_error is not None and request_error in done:
248
+ raise request_error.result()
249
+ if error_task in done:
250
+ raise error_task.result()
251
+ if disconnect_task in done:
252
+ raise TransportError(
253
+ f"BLE disconnected while waiting for command 0x{command_id:04X}"
254
+ )
255
+ return packet_task.result()
256
+ finally:
257
+ for task in tasks:
258
+ if not task.done():
259
+ task.cancel()
260
+ await asyncio.gather(*tasks, return_exceptions=True)
261
+
262
+ def add_packet_handler(
263
+ self, command: int | IntEnum, handler: PacketHandler, *, queue_packets: bool = True,
264
+ ) -> None:
265
+ """Register a handler; queue_packets=False gives it exclusive packet delivery."""
266
+ command_id = int(command)
267
+ if command_id in self._callback_only or (not queue_packets and self._handlers[command_id]):
268
+ raise ProtocolError("Callback-only delivery requires an exclusive handler")
269
+ if not queue_packets:
270
+ self._callback_only.add(command_id)
271
+ self._drain_queue(command_id)
272
+ self._handlers[command_id].append(handler)
273
+
274
+ def remove_packet_handler(
275
+ self,
276
+ command: int | IntEnum,
277
+ handler: PacketHandler,
278
+ ) -> None:
279
+ self._handlers[int(command)].remove(handler)
280
+ self._callback_only.discard(int(command))
281
+
282
+ async def __aenter__(self) -> "OpenZiloClient":
283
+ await self.connect()
284
+ return self
285
+
286
+ async def __aexit__(self, exc_type: object, exc: object, tb: object) -> None:
287
+ await self.disconnect()
288
+
289
+ def _on_rx(self, data: bytes) -> None:
290
+ try:
291
+ packets = self._stream.feed(data)
292
+ except ProtocolError as exc:
293
+ self._stream.clear()
294
+ self._report_protocol_error(exc)
295
+ return
296
+
297
+ for packet in packets:
298
+ if packet.command == SystemCommand.ERROR_RESP:
299
+ try:
300
+ reader = BinaryReader(packet.body)
301
+ failed_command, code = reader.u16(), reader.u16()
302
+ if reader.remaining or not code:
303
+ raise ProtocolError("Invalid standard error response")
304
+ except ProtocolError as exc:
305
+ self._report_protocol_error(exc)
306
+ continue
307
+ pending = self._request_errors.get(failed_command)
308
+ if pending is not None and not pending.done():
309
+ pending.set_result(DeviceError(code,
310
+ f"Command 0x{failed_command:04X} rejected with error {code}"))
311
+ continue
312
+ if packet.command not in self._callback_only:
313
+ queue = self._queues[packet.command]
314
+ if queue.full():
315
+ self._drain_queue(packet.command)
316
+ self._report_protocol_error(ProtocolError(
317
+ f"Receive queue overflow for command 0x{packet.command:04X}; data was lost"
318
+ ))
319
+ queue.put_nowait(packet)
320
+ for handler in list(self._handlers.get(packet.command, [])):
321
+ try:
322
+ result = handler(packet)
323
+ except Exception:
324
+ _logger.exception("Packet handler for 0x%04X failed", packet.command)
325
+ continue
326
+ if inspect.isawaitable(result):
327
+ start_background_task(
328
+ self._callback_tasks, result, f"Packet handler for 0x{packet.command:04X}",
329
+ )
330
+
331
+ def _report_protocol_error(self, error: ProtocolError) -> None:
332
+ if not self._protocol_errors.full():
333
+ self._protocol_errors.put_nowait(error)
334
+
335
+ def _on_disconnect(self) -> None:
336
+ self.capabilities = None
337
+ self._connection_token = None
338
+ self._connection_ready.clear()
339
+ self._disconnected.set()
340
+ self._clear_receive_state()
341
+ for task in list(self._callback_tasks):
342
+ task.cancel()
343
+
344
+ def _drain_queue(self, command: int) -> None:
345
+ queue = self._queues[command]
346
+ while True:
347
+ try:
348
+ queue.get_nowait()
349
+ except asyncio.QueueEmpty:
350
+ return
351
+
352
+ def _drain_protocol_errors(self) -> None:
353
+ while True:
354
+ try:
355
+ self._protocol_errors.get_nowait()
356
+ except asyncio.QueueEmpty:
357
+ return
358
+
359
+ def _clear_receive_state(self) -> None:
360
+ self._live_audio_subscribed = False
361
+ self._stream.clear()
362
+ for command in list(self._queues):
363
+ self._drain_queue(command)
364
+ self._drain_protocol_errors()