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/_sensor.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""IMU reports and gesture/button events."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import IntEnum
|
|
8
|
+
|
|
9
|
+
from ._errors import ProtocolError
|
|
10
|
+
from ._protocol import BinaryReader, ensure_success, read_error, SensorCommand
|
|
11
|
+
from ._client import OpenZiloClient
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SensorGestureId(IntEnum):
|
|
15
|
+
IDLE = 0
|
|
16
|
+
ROTATE_BACK = 1
|
|
17
|
+
ROTATE_FRONT = 2
|
|
18
|
+
WAVE = 3
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_SENSOR_GESTURE_NAMES: dict[int, str] = {
|
|
22
|
+
int(SensorGestureId.IDLE): "idle",
|
|
23
|
+
int(SensorGestureId.ROTATE_BACK): "rotate_back",
|
|
24
|
+
int(SensorGestureId.ROTATE_FRONT): "rotate_front",
|
|
25
|
+
int(SensorGestureId.WAVE): "wave",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class SensorStartInfo:
|
|
31
|
+
sample_rate_hz: int
|
|
32
|
+
accel_range_g: int
|
|
33
|
+
gyro_range_dps: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class SensorStopInfo:
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class SensorDataSample:
|
|
43
|
+
timestamp_ms: int
|
|
44
|
+
accel_x: int
|
|
45
|
+
accel_y: int
|
|
46
|
+
accel_z: int
|
|
47
|
+
gyro_x: int
|
|
48
|
+
gyro_y: int
|
|
49
|
+
gyro_z: int
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class SensorDataBatch:
|
|
54
|
+
sequence_start: int
|
|
55
|
+
frame_count: int
|
|
56
|
+
sample_size: int
|
|
57
|
+
samples: tuple[SensorDataSample, ...]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class SensorDoubleTapEvent:
|
|
62
|
+
timestamp_ms: int
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class SensorGestureEvent:
|
|
67
|
+
timestamp_ms: int
|
|
68
|
+
gesture_id: int
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class SensorKeyDoublePressEvent:
|
|
73
|
+
timestamp_ms: int
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class SensorKeySinglePressEvent:
|
|
78
|
+
timestamp_ms: int
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def start_sensor_report(
|
|
82
|
+
client: OpenZiloClient,
|
|
83
|
+
*,
|
|
84
|
+
timeout_s: float | None = None,
|
|
85
|
+
) -> SensorStartInfo:
|
|
86
|
+
"""Start IMU reports. single-sample IMU firmware starts capture; gesture firmware requires
|
|
87
|
+
gesture mode first. Both single-sample and batch reports are supported.
|
|
88
|
+
"""
|
|
89
|
+
packet = await client.request(
|
|
90
|
+
SensorCommand.START_REPORT,
|
|
91
|
+
SensorCommand.START_REPORT_RESP,
|
|
92
|
+
timeout_s=timeout_s,
|
|
93
|
+
)
|
|
94
|
+
reader = BinaryReader(packet.body)
|
|
95
|
+
ensure_success(read_error(reader))
|
|
96
|
+
return SensorStartInfo(
|
|
97
|
+
sample_rate_hz=reader.u16(),
|
|
98
|
+
accel_range_g=reader.u16(),
|
|
99
|
+
gyro_range_dps=reader.u16(),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
async def stop_sensor_report(
|
|
104
|
+
client: OpenZiloClient,
|
|
105
|
+
*,
|
|
106
|
+
timeout_s: float | None = None,
|
|
107
|
+
) -> SensorStopInfo:
|
|
108
|
+
"""Stop reports; single-sample IMU firmware also stops capture, gesture firmware may retain it."""
|
|
109
|
+
packet = await client.request(
|
|
110
|
+
SensorCommand.STOP_REPORT,
|
|
111
|
+
SensorCommand.STOP_REPORT_RESP,
|
|
112
|
+
timeout_s=timeout_s,
|
|
113
|
+
)
|
|
114
|
+
reader = BinaryReader(packet.body)
|
|
115
|
+
ensure_success(read_error(reader))
|
|
116
|
+
return SensorStopInfo()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def wait_sensor_data(
|
|
120
|
+
client: OpenZiloClient,
|
|
121
|
+
*,
|
|
122
|
+
timeout_s: float | None = None,
|
|
123
|
+
) -> SensorDataBatch:
|
|
124
|
+
"""Wait for one 0x0605 batch after start_sensor_report() succeeds."""
|
|
125
|
+
packet = await client.wait_for_command(SensorCommand.DATA_FRAME, timeout_s=timeout_s)
|
|
126
|
+
return parse_sensor_data_batch(packet.body)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _read_sensor_sample(reader: BinaryReader) -> SensorDataSample:
|
|
130
|
+
return SensorDataSample(
|
|
131
|
+
timestamp_ms=reader.u32(),
|
|
132
|
+
accel_x=reader.i16(),
|
|
133
|
+
accel_y=reader.i16(),
|
|
134
|
+
accel_z=reader.i16(),
|
|
135
|
+
gyro_x=reader.i16(),
|
|
136
|
+
gyro_y=reader.i16(),
|
|
137
|
+
gyro_z=reader.i16(),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def parse_sensor_data_batch(body: bytes) -> SensorDataBatch:
|
|
142
|
+
reader = BinaryReader(body)
|
|
143
|
+
ensure_success(read_error(reader))
|
|
144
|
+
sequence_start = reader.u32()
|
|
145
|
+
# The original single-sample IMU format is exactly 22 bytes; a valid batch is
|
|
146
|
+
# 10 + N * 16 bytes, so the two wire formats cannot overlap.
|
|
147
|
+
if len(body) == 22:
|
|
148
|
+
return SensorDataBatch(
|
|
149
|
+
sequence_start=sequence_start, frame_count=1, sample_size=16,
|
|
150
|
+
samples=(_read_sensor_sample(reader),),
|
|
151
|
+
)
|
|
152
|
+
frame_count = reader.u16()
|
|
153
|
+
sample_size = reader.u16()
|
|
154
|
+
if sample_size != 16:
|
|
155
|
+
raise ProtocolError(f"Unsupported sensor sample size: {sample_size}")
|
|
156
|
+
expected_remaining = frame_count * sample_size
|
|
157
|
+
if reader.remaining != expected_remaining:
|
|
158
|
+
raise ProtocolError(
|
|
159
|
+
f"Sensor batch length mismatch: expected {expected_remaining} sample bytes, "
|
|
160
|
+
f"got {reader.remaining}"
|
|
161
|
+
)
|
|
162
|
+
samples = tuple(_read_sensor_sample(reader) for _ in range(frame_count))
|
|
163
|
+
return SensorDataBatch(
|
|
164
|
+
sequence_start=sequence_start,
|
|
165
|
+
frame_count=frame_count,
|
|
166
|
+
sample_size=sample_size,
|
|
167
|
+
samples=samples,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def parse_sensor_double_tap_event(body: bytes) -> SensorDoubleTapEvent:
|
|
172
|
+
reader = BinaryReader(body)
|
|
173
|
+
event = SensorDoubleTapEvent(timestamp_ms=reader.u32())
|
|
174
|
+
if reader.remaining:
|
|
175
|
+
raise ProtocolError(f"Unexpected trailing double-tap event bytes: {reader.remaining}")
|
|
176
|
+
return event
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def parse_sensor_gesture_event(body: bytes) -> SensorGestureEvent:
|
|
180
|
+
reader = BinaryReader(body)
|
|
181
|
+
event = SensorGestureEvent(timestamp_ms=reader.u32(), gesture_id=reader.u8())
|
|
182
|
+
if reader.remaining:
|
|
183
|
+
raise ProtocolError(f"Unexpected trailing gesture event bytes: {reader.remaining}")
|
|
184
|
+
return event
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def sensor_gesture_name(gesture_id: int | SensorGestureId) -> str:
|
|
188
|
+
value = int(gesture_id)
|
|
189
|
+
return _SENSOR_GESTURE_NAMES.get(value, f"unknown({value})")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def parse_sensor_key_double_press_event(body: bytes) -> SensorKeyDoublePressEvent:
|
|
193
|
+
reader = BinaryReader(body)
|
|
194
|
+
event = SensorKeyDoublePressEvent(timestamp_ms=reader.u32())
|
|
195
|
+
if reader.remaining:
|
|
196
|
+
raise ProtocolError(
|
|
197
|
+
f"Unexpected trailing key double-press event bytes: {reader.remaining}"
|
|
198
|
+
)
|
|
199
|
+
return event
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def parse_sensor_key_single_press_event(body: bytes) -> SensorKeySinglePressEvent:
|
|
203
|
+
reader = BinaryReader(body)
|
|
204
|
+
event = SensorKeySinglePressEvent(timestamp_ms=reader.u32())
|
|
205
|
+
if reader.remaining:
|
|
206
|
+
raise ProtocolError(
|
|
207
|
+
f"Unexpected trailing key single-press event bytes: {reader.remaining}"
|
|
208
|
+
)
|
|
209
|
+
return event
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def wait_sensor_double_tap_event(
|
|
213
|
+
client: OpenZiloClient,
|
|
214
|
+
*,
|
|
215
|
+
timeout_s: float | None = None,
|
|
216
|
+
) -> SensorDoubleTapEvent:
|
|
217
|
+
packet = await client.wait_for_command(SensorCommand.DOUBLE_TAP, timeout_s=timeout_s)
|
|
218
|
+
return parse_sensor_double_tap_event(packet.body)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
async def wait_sensor_gesture_event(
|
|
222
|
+
client: OpenZiloClient,
|
|
223
|
+
*,
|
|
224
|
+
timeout_s: float | None = None,
|
|
225
|
+
) -> SensorGestureEvent:
|
|
226
|
+
packet = await client.wait_for_command(SensorCommand.GESTURE, timeout_s=timeout_s)
|
|
227
|
+
return parse_sensor_gesture_event(packet.body)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
async def wait_sensor_key_double_press_event(
|
|
231
|
+
client: OpenZiloClient,
|
|
232
|
+
*,
|
|
233
|
+
timeout_s: float | None = None,
|
|
234
|
+
) -> SensorKeyDoublePressEvent:
|
|
235
|
+
packet = await client.wait_for_command(
|
|
236
|
+
SensorCommand.KEY_DOUBLE_PRESS,
|
|
237
|
+
timeout_s=timeout_s,
|
|
238
|
+
)
|
|
239
|
+
return parse_sensor_key_double_press_event(packet.body)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
async def wait_sensor_key_single_press_event(
|
|
243
|
+
client: OpenZiloClient,
|
|
244
|
+
*,
|
|
245
|
+
timeout_s: float | None = None,
|
|
246
|
+
) -> SensorKeySinglePressEvent:
|
|
247
|
+
packet = await client.wait_for_command(
|
|
248
|
+
SensorCommand.KEY_SINGLE_PRESS,
|
|
249
|
+
timeout_s=timeout_s,
|
|
250
|
+
)
|
|
251
|
+
return parse_sensor_key_single_press_event(packet.body)
|
openzilo/_tasks.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Small asyncio helpers for deadlines and owned background tasks."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Awaitable
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from ._errors import TimeoutError
|
|
12
|
+
|
|
13
|
+
_logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def start_background_task(tasks: set[asyncio.Task[Any]], awaitable: Awaitable[Any], label: str) -> None:
|
|
17
|
+
"""Keep callback tasks alive and report their failures instead of dropping them."""
|
|
18
|
+
task = asyncio.ensure_future(awaitable)
|
|
19
|
+
tasks.add(task)
|
|
20
|
+
|
|
21
|
+
def finished(done: asyncio.Task[Any]) -> None:
|
|
22
|
+
tasks.discard(done)
|
|
23
|
+
if not done.cancelled() and done.exception() is not None:
|
|
24
|
+
_logger.error("%s failed", label, exc_info=done.exception())
|
|
25
|
+
|
|
26
|
+
task.add_done_callback(finished)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def await_before(awaitable: Awaitable[Any], deadline: float, message: str) -> Any:
|
|
30
|
+
# Unlike asyncio.wait_for on Python 3.10/3.11, this never swallows a cancellation
|
|
31
|
+
# that arrives just as the awaited operation finishes.
|
|
32
|
+
task = asyncio.ensure_future(awaitable)
|
|
33
|
+
try:
|
|
34
|
+
done, _pending = await asyncio.wait(
|
|
35
|
+
{task}, timeout=max(0.0, deadline - asyncio.get_running_loop().time()),
|
|
36
|
+
)
|
|
37
|
+
except BaseException:
|
|
38
|
+
task.cancel()
|
|
39
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
40
|
+
raise
|
|
41
|
+
if not done:
|
|
42
|
+
task.cancel()
|
|
43
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
44
|
+
raise TimeoutError(message)
|
|
45
|
+
return task.result()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def acquire_before(lock: asyncio.Lock, deadline: float, message: str) -> None:
|
|
49
|
+
task = asyncio.ensure_future(lock.acquire())
|
|
50
|
+
|
|
51
|
+
async def abandon() -> None:
|
|
52
|
+
task.cancel()
|
|
53
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
54
|
+
if not task.cancelled() and task.exception() is None:
|
|
55
|
+
lock.release()
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
done, _pending = await asyncio.wait(
|
|
59
|
+
{task}, timeout=max(0.0, deadline - asyncio.get_running_loop().time()),
|
|
60
|
+
)
|
|
61
|
+
except BaseException:
|
|
62
|
+
await abandon()
|
|
63
|
+
raise
|
|
64
|
+
if not done:
|
|
65
|
+
await abandon()
|
|
66
|
+
raise TimeoutError(message)
|
|
67
|
+
task.result()
|
openzilo/_transport.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""BLE Nordic UART Service transport built on bleak."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import inspect
|
|
8
|
+
import logging
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
import weakref
|
|
12
|
+
from collections.abc import Awaitable, Callable
|
|
13
|
+
from dataclasses import InitVar, dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from ._errors import TransportError
|
|
17
|
+
from ._tasks import start_background_task
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
NUS_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
|
|
21
|
+
NUS_TX_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
|
|
22
|
+
NUS_RX_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
|
|
23
|
+
DEFAULT_SCAN_TIMEOUT_S = 30.0
|
|
24
|
+
DEFAULT_CONNECTION_STABILIZATION_S = 3.0
|
|
25
|
+
_logger = logging.getLogger(__name__)
|
|
26
|
+
_scan_sessions: weakref.WeakKeyDictionary[Any, object] = weakref.WeakKeyDictionary()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _positive_timeout(value: float) -> None:
|
|
30
|
+
if not math.isfinite(value) or value <= 0:
|
|
31
|
+
raise ValueError("Timeout must be a finite positive number")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _compatible_name(name: str | None) -> bool:
|
|
35
|
+
name = (name or "").strip().casefold()
|
|
36
|
+
return name in {"ring", "open zilo"} or bool(re.search(r"open zilo-\S+", name))
|
|
37
|
+
_NUS_WRITE_CHUNK_SIZE = 20
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class BleDeviceInfo:
|
|
42
|
+
name: str | None
|
|
43
|
+
address: str
|
|
44
|
+
rssi: int | None = None
|
|
45
|
+
service_uuids: tuple[str, ...] = ()
|
|
46
|
+
matched_service: bool = False
|
|
47
|
+
matched_name: bool = False
|
|
48
|
+
# InitVar keeps native backend objects out of repr, equality and asdict().
|
|
49
|
+
_native_device: InitVar[Any] = None
|
|
50
|
+
|
|
51
|
+
def __post_init__(self, _native_device: Any) -> None:
|
|
52
|
+
object.__setattr__(self, "_native_device", _native_device)
|
|
53
|
+
try:
|
|
54
|
+
loop = asyncio.get_running_loop()
|
|
55
|
+
except RuntimeError:
|
|
56
|
+
loop = None
|
|
57
|
+
object.__setattr__(self, "_native_loop", loop)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
RxCallback = Callable[[bytes], None | Awaitable[None]]
|
|
61
|
+
DisconnectCallback = Callable[[], None | Awaitable[None]]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _normalize_ble_address(address: str | None) -> str:
|
|
65
|
+
return "".join(ch for ch in str(address or "") if ch.isalnum()).lower()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _address_matches(candidate: object, expected: str | None) -> bool:
|
|
69
|
+
expected_norm = _normalize_ble_address(expected)
|
|
70
|
+
if not expected_norm:
|
|
71
|
+
return True
|
|
72
|
+
return _normalize_ble_address(str(candidate or "")) == expected_norm
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class NusClient:
|
|
76
|
+
"""Cross-platform BLE/NUS client using bleak."""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
*,
|
|
81
|
+
address: str | None = None,
|
|
82
|
+
device: BleDeviceInfo | None = None,
|
|
83
|
+
connect_timeout_s: float = 30.0,
|
|
84
|
+
service_uuid: str = NUS_SERVICE_UUID,
|
|
85
|
+
tx_uuid: str = NUS_TX_UUID,
|
|
86
|
+
rx_uuid: str = NUS_RX_UUID,
|
|
87
|
+
scan_timeout_s: float = DEFAULT_SCAN_TIMEOUT_S,
|
|
88
|
+
write_with_response: bool = False,
|
|
89
|
+
) -> None:
|
|
90
|
+
if device is not None and address is not None and not _address_matches(device.address, address):
|
|
91
|
+
raise ValueError("address and device must identify the same device")
|
|
92
|
+
_positive_timeout(scan_timeout_s)
|
|
93
|
+
_positive_timeout(connect_timeout_s)
|
|
94
|
+
self.address = address if address is not None else (device.address if device else None)
|
|
95
|
+
self.device = device
|
|
96
|
+
self.connect_timeout_s = connect_timeout_s
|
|
97
|
+
self._ready = False
|
|
98
|
+
self._connecting = False
|
|
99
|
+
self.service_uuid = service_uuid
|
|
100
|
+
self.tx_uuid = tx_uuid
|
|
101
|
+
self.rx_uuid = rx_uuid
|
|
102
|
+
self.scan_timeout_s = scan_timeout_s
|
|
103
|
+
self.write_with_response = write_with_response
|
|
104
|
+
self._client: Any | None = None
|
|
105
|
+
self._rx_callback: RxCallback | None = None
|
|
106
|
+
self._disconnect_callback: DisconnectCallback | None = None
|
|
107
|
+
self._notify_started = False
|
|
108
|
+
self._callback_tasks: set[asyncio.Task[Any]] = set()
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
async def discover(
|
|
112
|
+
*,
|
|
113
|
+
address: str | None = None,
|
|
114
|
+
timeout_s: float = DEFAULT_SCAN_TIMEOUT_S,
|
|
115
|
+
on_devices_changed: Callable[[list[BleDeviceInfo]], None] | None = None,
|
|
116
|
+
_scan_stats: dict[str, Any] | None = None,
|
|
117
|
+
) -> list[BleDeviceInfo]:
|
|
118
|
+
"""Report ring candidates immediately; an explicit address bypasses candidate filtering.
|
|
119
|
+
|
|
120
|
+
Cancellation propagates after cleanup and a final callback snapshot.
|
|
121
|
+
Only one SDK scan may run in an event loop at a time.
|
|
122
|
+
"""
|
|
123
|
+
_positive_timeout(timeout_s)
|
|
124
|
+
if address is not None and not _normalize_ble_address(address):
|
|
125
|
+
raise ValueError("address must be a nonempty device identifier")
|
|
126
|
+
try:
|
|
127
|
+
from bleak import BleakScanner
|
|
128
|
+
except ImportError as exc:
|
|
129
|
+
raise TransportError("Install bleak to use BLE transport") from exc
|
|
130
|
+
loop = asyncio.get_running_loop()
|
|
131
|
+
if loop in _scan_sessions:
|
|
132
|
+
raise TransportError("SCANNING: another SDK scan is active; cancel and await it first")
|
|
133
|
+
session = object()
|
|
134
|
+
_scan_sessions[loop] = session
|
|
135
|
+
active = True
|
|
136
|
+
found = asyncio.Event()
|
|
137
|
+
results: dict[str, BleDeviceInfo] = {}
|
|
138
|
+
counts = dict(broadcasts=0, service=0, name=0, filtered=0)
|
|
139
|
+
started = loop.time()
|
|
140
|
+
first_found: float | None = None
|
|
141
|
+
last_report = -float("inf")
|
|
142
|
+
timer: asyncio.TimerHandle | None = None
|
|
143
|
+
|
|
144
|
+
def snapshot() -> list[BleDeviceInfo]:
|
|
145
|
+
return sorted(results.values(), key=lambda d: (
|
|
146
|
+
not d.matched_service, -(d.rssi if d.rssi is not None else -1000), d.address,
|
|
147
|
+
))
|
|
148
|
+
|
|
149
|
+
def report() -> None:
|
|
150
|
+
nonlocal last_report, timer
|
|
151
|
+
if timer is not None:
|
|
152
|
+
timer.cancel()
|
|
153
|
+
timer = None
|
|
154
|
+
last_report = loop.time()
|
|
155
|
+
if on_devices_changed is not None:
|
|
156
|
+
try:
|
|
157
|
+
on_devices_changed(snapshot())
|
|
158
|
+
except Exception:
|
|
159
|
+
_logger.exception("Scan result callback failed")
|
|
160
|
+
|
|
161
|
+
def detected(dev: Any, adv: Any) -> None:
|
|
162
|
+
nonlocal first_found, timer
|
|
163
|
+
if not active or _scan_sessions.get(loop) is not session:
|
|
164
|
+
return
|
|
165
|
+
counts["broadcasts"] += 1
|
|
166
|
+
device_address = str(dev.address)
|
|
167
|
+
key = _normalize_ble_address(device_address)
|
|
168
|
+
previous = results.get(key)
|
|
169
|
+
name = (getattr(adv, "local_name", None)
|
|
170
|
+
or (previous.name if previous else None) or getattr(dev, "name", None))
|
|
171
|
+
uuids = tuple(sorted(set(
|
|
172
|
+
(previous.service_uuids if previous else ())
|
|
173
|
+
+ tuple(str(u).lower() for u in getattr(adv, "service_uuids", ()))
|
|
174
|
+
+ tuple(str(u).lower() for u in getattr(adv, "service_data", {}))
|
|
175
|
+
)))
|
|
176
|
+
service_match = NUS_SERVICE_UUID.lower() in uuids
|
|
177
|
+
name_match = _compatible_name(name) or bool(previous and previous.matched_name)
|
|
178
|
+
counts["service"] += int(service_match)
|
|
179
|
+
counts["name"] += int(name_match)
|
|
180
|
+
accepted = (_address_matches(device_address, address) if address is not None
|
|
181
|
+
else service_match or name_match)
|
|
182
|
+
if not accepted:
|
|
183
|
+
counts["filtered"] += 1
|
|
184
|
+
return
|
|
185
|
+
if first_found is None:
|
|
186
|
+
first_found = loop.time() - started
|
|
187
|
+
info = BleDeviceInfo(name, device_address, getattr(adv, "rssi", None),
|
|
188
|
+
uuids, service_match, name_match, dev)
|
|
189
|
+
results[key] = info
|
|
190
|
+
if previous is None:
|
|
191
|
+
report()
|
|
192
|
+
elif info != previous:
|
|
193
|
+
remaining = 0.2 - (loop.time() - last_report)
|
|
194
|
+
if remaining <= 0:
|
|
195
|
+
report()
|
|
196
|
+
elif timer is None:
|
|
197
|
+
timer = loop.call_later(remaining, report)
|
|
198
|
+
if address is not None:
|
|
199
|
+
found.set()
|
|
200
|
+
|
|
201
|
+
scanner = None
|
|
202
|
+
entered = False
|
|
203
|
+
_logger.info("SCANNING")
|
|
204
|
+
try:
|
|
205
|
+
scanner = BleakScanner(detection_callback=detected, scanning_mode="active")
|
|
206
|
+
async with scanner:
|
|
207
|
+
entered = True
|
|
208
|
+
try:
|
|
209
|
+
await asyncio.wait_for(found.wait(), timeout_s)
|
|
210
|
+
except asyncio.TimeoutError:
|
|
211
|
+
pass
|
|
212
|
+
except Exception as exc:
|
|
213
|
+
raise TransportError(f"SCANNING failed: {exc}; stats={counts}") from exc
|
|
214
|
+
finally:
|
|
215
|
+
active = False
|
|
216
|
+
if timer is not None:
|
|
217
|
+
timer.cancel()
|
|
218
|
+
try:
|
|
219
|
+
# __aexit__ handles normal exits, failures and cancellation after start.
|
|
220
|
+
if scanner is not None and not entered:
|
|
221
|
+
try:
|
|
222
|
+
await asyncio.wait_for(scanner.stop(), 2.0)
|
|
223
|
+
except Exception:
|
|
224
|
+
_logger.exception("Scanner cleanup after start failure failed")
|
|
225
|
+
finally:
|
|
226
|
+
report()
|
|
227
|
+
_scan_sessions.pop(loop, None)
|
|
228
|
+
if _scan_stats is not None:
|
|
229
|
+
_scan_stats.update(counts, first_found_s=first_found)
|
|
230
|
+
_logger.info("Scan stats=%s first_found_s=%s", counts, first_found)
|
|
231
|
+
if address is not None and not results:
|
|
232
|
+
_logger.warning("SCANNING timeout: target not found; stats=%s", counts)
|
|
233
|
+
return snapshot()
|
|
234
|
+
|
|
235
|
+
def set_rx_callback(self, callback: RxCallback | None) -> None:
|
|
236
|
+
self._rx_callback = callback
|
|
237
|
+
|
|
238
|
+
def _set_disconnect_callback(self, callback: DisconnectCallback | None) -> None:
|
|
239
|
+
self._disconnect_callback = callback
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def is_connected(self) -> bool:
|
|
243
|
+
return bool(self._client and self._client.is_connected)
|
|
244
|
+
|
|
245
|
+
async def connect(self) -> None:
|
|
246
|
+
if self._connecting or self._client is not None:
|
|
247
|
+
raise TransportError("A connection is already active; disconnect first")
|
|
248
|
+
if not _normalize_ble_address(self.address):
|
|
249
|
+
raise TransportError("A device address/identifier or scanned device is required")
|
|
250
|
+
if asyncio.get_running_loop() in _scan_sessions:
|
|
251
|
+
raise TransportError("SCANNING: cancel and await the active scan before connecting")
|
|
252
|
+
self._connecting = True
|
|
253
|
+
stage = "SCANNING"
|
|
254
|
+
client = None
|
|
255
|
+
try:
|
|
256
|
+
from bleak import BleakClient
|
|
257
|
+
selected = self.device
|
|
258
|
+
# Native objects are only reused for this immediate connection in their loop.
|
|
259
|
+
self.device = None
|
|
260
|
+
if (selected is None or selected._native_device is None
|
|
261
|
+
or selected._native_loop is not asyncio.get_running_loop()):
|
|
262
|
+
stats: dict[str, Any] = {}
|
|
263
|
+
devices = await self.discover(address=self.address, timeout_s=self.scan_timeout_s,
|
|
264
|
+
_scan_stats=stats)
|
|
265
|
+
if not devices:
|
|
266
|
+
raise TransportError(f"SCANNING timeout: target address not found; stats={stats}")
|
|
267
|
+
selected = devices[0]
|
|
268
|
+
stage = "CONNECTING"
|
|
269
|
+
_logger.info(stage)
|
|
270
|
+
client = BleakClient(selected._native_device,
|
|
271
|
+
disconnected_callback=self._handle_disconnect,
|
|
272
|
+
timeout=self.connect_timeout_s)
|
|
273
|
+
self._client = client
|
|
274
|
+
await asyncio.wait_for(client.connect(), self.connect_timeout_s)
|
|
275
|
+
service = client.services.get_service(self.service_uuid)
|
|
276
|
+
if service is None:
|
|
277
|
+
raise TransportError("NUS service is missing")
|
|
278
|
+
rx = service.get_characteristic(self.rx_uuid)
|
|
279
|
+
tx = service.get_characteristic(self.tx_uuid)
|
|
280
|
+
write_property = "write" if self.write_with_response else "write-without-response"
|
|
281
|
+
if rx is None or write_property not in rx.properties:
|
|
282
|
+
raise TransportError(f"NUS RX must support {write_property}")
|
|
283
|
+
if tx is None or "notify" not in tx.properties:
|
|
284
|
+
raise TransportError("NUS TX must support notify")
|
|
285
|
+
stage = "SUBSCRIBING"
|
|
286
|
+
_logger.info(stage)
|
|
287
|
+
def notified(sender: Any, data: bytearray) -> None:
|
|
288
|
+
if self._client is client:
|
|
289
|
+
self._handle_notify(sender, data)
|
|
290
|
+
|
|
291
|
+
await asyncio.wait_for(client.start_notify(self.tx_uuid, notified),
|
|
292
|
+
self.connect_timeout_s)
|
|
293
|
+
self._notify_started = True
|
|
294
|
+
stage = "STABILIZING"
|
|
295
|
+
_logger.info(stage)
|
|
296
|
+
await asyncio.sleep(DEFAULT_CONNECTION_STABILIZATION_S)
|
|
297
|
+
if not client.is_connected:
|
|
298
|
+
raise TransportError("Link disconnected during stabilization")
|
|
299
|
+
self._ready = True
|
|
300
|
+
_logger.info("READY")
|
|
301
|
+
except BaseException as exc:
|
|
302
|
+
self._ready = False
|
|
303
|
+
try:
|
|
304
|
+
if client is not None:
|
|
305
|
+
await asyncio.wait_for(self.disconnect(), 2.0)
|
|
306
|
+
except Exception:
|
|
307
|
+
_logger.exception("BLE cleanup failed")
|
|
308
|
+
finally:
|
|
309
|
+
self._client = None
|
|
310
|
+
self._notify_started = False
|
|
311
|
+
if not isinstance(exc, Exception):
|
|
312
|
+
raise
|
|
313
|
+
raise TransportError(f"{stage} failed: {exc}") from exc
|
|
314
|
+
finally:
|
|
315
|
+
self._connecting = False
|
|
316
|
+
|
|
317
|
+
async def disconnect(self) -> None:
|
|
318
|
+
self._ready = False
|
|
319
|
+
if self._client is None:
|
|
320
|
+
return
|
|
321
|
+
try:
|
|
322
|
+
if self._notify_started and self._client.is_connected:
|
|
323
|
+
await self._client.stop_notify(self.tx_uuid)
|
|
324
|
+
finally:
|
|
325
|
+
self._notify_started = False
|
|
326
|
+
if self._client.is_connected:
|
|
327
|
+
await self._client.disconnect()
|
|
328
|
+
self._client = None
|
|
329
|
+
|
|
330
|
+
async def write(self, data: bytes | bytearray | memoryview) -> None:
|
|
331
|
+
if not self._ready or self._client is None or not self._client.is_connected:
|
|
332
|
+
raise TransportError("BLE client is not ready")
|
|
333
|
+
|
|
334
|
+
payload = bytes(data)
|
|
335
|
+
for offset in range(0, len(payload), _NUS_WRITE_CHUNK_SIZE):
|
|
336
|
+
chunk = payload[offset : offset + _NUS_WRITE_CHUNK_SIZE]
|
|
337
|
+
await self._client.write_gatt_char(
|
|
338
|
+
self.rx_uuid,
|
|
339
|
+
chunk,
|
|
340
|
+
response=self.write_with_response,
|
|
341
|
+
)
|
|
342
|
+
await asyncio.sleep(0)
|
|
343
|
+
|
|
344
|
+
async def __aenter__(self) -> "NusClient":
|
|
345
|
+
await self.connect()
|
|
346
|
+
return self
|
|
347
|
+
|
|
348
|
+
async def __aexit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
349
|
+
await self.disconnect()
|
|
350
|
+
|
|
351
|
+
def _handle_notify(self, _sender: Any, data: bytearray) -> None:
|
|
352
|
+
callback = self._rx_callback
|
|
353
|
+
if callback is None:
|
|
354
|
+
return
|
|
355
|
+
|
|
356
|
+
result = callback(bytes(data))
|
|
357
|
+
if inspect.isawaitable(result):
|
|
358
|
+
start_background_task(self._callback_tasks, result, "BLE receive callback")
|
|
359
|
+
|
|
360
|
+
def _handle_disconnect(self, _client: Any) -> None:
|
|
361
|
+
if _client is not self._client:
|
|
362
|
+
return
|
|
363
|
+
self._ready = False
|
|
364
|
+
self._notify_started = False
|
|
365
|
+
callback = self._disconnect_callback
|
|
366
|
+
if callback is None:
|
|
367
|
+
return
|
|
368
|
+
|
|
369
|
+
result = callback()
|
|
370
|
+
if inspect.isawaitable(result):
|
|
371
|
+
start_background_task(self._callback_tasks, result, "BLE disconnect callback")
|
openzilo/_version.py
ADDED