led-controller-version-3-device-simulated-respeaker 3.0.2__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.
- led_controller_version_3_device_simulated_respeaker-3.0.2.dist-info/METADATA +86 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2.dist-info/RECORD +15 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2.dist-info/WHEEL +4 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2.dist-info/entry_points.txt +8 -0
- lefx/device/simulated_respeaker/__init__.py +31 -0
- lefx/device/simulated_respeaker/__main__.py +15 -0
- lefx/device/simulated_respeaker/app.py +69 -0
- lefx/device/simulated_respeaker/client.py +203 -0
- lefx/device/simulated_respeaker/link.py +337 -0
- lefx/device/simulated_respeaker/protocol.py +164 -0
- lefx/device/simulated_respeaker/provider.py +159 -0
- lefx/device/simulated_respeaker/registration.py +113 -0
- lefx/device/simulated_respeaker/ring.py +105 -0
- lefx/device/simulated_respeaker/sink.py +69 -0
- lefx/device/simulated_respeaker/window.py +168 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""The service-side transport: a loopback socket the ring window connects to.
|
|
2
|
+
|
|
3
|
+
The service listens and the window dials in, not the other way round. That
|
|
4
|
+
matches how the hardware behaves — the controller runs whether or not anything
|
|
5
|
+
is plugged in, and a device appearing later is an ordinary event rather than a
|
|
6
|
+
restart. A window can be opened, closed and reopened as often as you like.
|
|
7
|
+
|
|
8
|
+
One link carries both directions, the same way one USB cable does: frames go out
|
|
9
|
+
to the window, slider values come back. The sink and the provider stay separate
|
|
10
|
+
objects over it, so a window that stops reporting inputs does not stop the
|
|
11
|
+
display.
|
|
12
|
+
|
|
13
|
+
No Qt here, and none reachable from here. Installing the simulator must not pull
|
|
14
|
+
a GUI toolkit into the service process.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import socket
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from . import protocol
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger("lefx.device.simulated_respeaker.link")
|
|
29
|
+
|
|
30
|
+
SEND_TIMEOUT_S = 2.0
|
|
31
|
+
"""A window that cannot absorb a few hundred bytes in this long is gone,
|
|
32
|
+
whatever its socket still claims."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def default_port() -> int:
|
|
36
|
+
"""The port both halves use unless told otherwise."""
|
|
37
|
+
raw = os.environ.get(protocol.PORT_ENV_VAR)
|
|
38
|
+
if not raw:
|
|
39
|
+
return protocol.DEFAULT_PORT
|
|
40
|
+
try:
|
|
41
|
+
return int(raw)
|
|
42
|
+
except ValueError:
|
|
43
|
+
logger.warning("ignoring %s=%r: not a port number", protocol.PORT_ENV_VAR, raw)
|
|
44
|
+
return protocol.DEFAULT_PORT
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _Window:
|
|
48
|
+
"""One connected ring window, with its own writer thread.
|
|
49
|
+
|
|
50
|
+
Frames are dropped rather than queued when a window falls behind: a frame is
|
|
51
|
+
a snapshot of *now*, and delivering a backlog of stale rings late is worse
|
|
52
|
+
than skipping to the current one. Control messages are queued, because
|
|
53
|
+
missing one loses meaning rather than a redraw.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, sock: socket.socket, address: Any) -> None:
|
|
57
|
+
self.sock = sock
|
|
58
|
+
self.address = address
|
|
59
|
+
self.alive = True
|
|
60
|
+
self._lock = threading.Lock()
|
|
61
|
+
self._wakeup = threading.Condition(self._lock)
|
|
62
|
+
self._pending_frame: bytes | None = None
|
|
63
|
+
self._control: list[bytes] = []
|
|
64
|
+
self._writer = threading.Thread(
|
|
65
|
+
target=self._write_loop, name="lefx-simulator-writer", daemon=True
|
|
66
|
+
)
|
|
67
|
+
self._writer.start()
|
|
68
|
+
|
|
69
|
+
def send_frame(self, message: bytes) -> None:
|
|
70
|
+
with self._wakeup:
|
|
71
|
+
self._pending_frame = message
|
|
72
|
+
self._wakeup.notify()
|
|
73
|
+
|
|
74
|
+
def send_control(self, message: bytes) -> None:
|
|
75
|
+
with self._wakeup:
|
|
76
|
+
self._control.append(message)
|
|
77
|
+
self._wakeup.notify()
|
|
78
|
+
|
|
79
|
+
def _write_loop(self) -> None:
|
|
80
|
+
while True:
|
|
81
|
+
with self._wakeup:
|
|
82
|
+
while self.alive and self._pending_frame is None and not self._control:
|
|
83
|
+
self._wakeup.wait()
|
|
84
|
+
if not self.alive:
|
|
85
|
+
return
|
|
86
|
+
control, self._control = self._control, []
|
|
87
|
+
frame, self._pending_frame = self._pending_frame, None
|
|
88
|
+
try:
|
|
89
|
+
for message in control:
|
|
90
|
+
self.sock.sendall(message)
|
|
91
|
+
if frame is not None:
|
|
92
|
+
self.sock.sendall(frame)
|
|
93
|
+
except OSError as exc:
|
|
94
|
+
logger.debug("window %s went away while writing: %s", self.address, exc)
|
|
95
|
+
self.close()
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
def close(self) -> None:
|
|
99
|
+
with self._wakeup:
|
|
100
|
+
if not self.alive:
|
|
101
|
+
return
|
|
102
|
+
self.alive = False
|
|
103
|
+
self._wakeup.notify_all()
|
|
104
|
+
try:
|
|
105
|
+
self.sock.shutdown(socket.SHUT_RDWR)
|
|
106
|
+
except OSError:
|
|
107
|
+
pass
|
|
108
|
+
try:
|
|
109
|
+
self.sock.close()
|
|
110
|
+
except OSError:
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class SimulatorLink:
|
|
115
|
+
"""Accepts ring windows, sends them frames and collects their inputs."""
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
*,
|
|
120
|
+
host: str = protocol.DEFAULT_HOST,
|
|
121
|
+
port: int | None = None,
|
|
122
|
+
led_count: int = 12,
|
|
123
|
+
) -> None:
|
|
124
|
+
self.host = host
|
|
125
|
+
self.requested_port = default_port() if port is None else int(port)
|
|
126
|
+
self.led_count = int(led_count)
|
|
127
|
+
|
|
128
|
+
self._lock = threading.RLock()
|
|
129
|
+
self._server: socket.socket | None = None
|
|
130
|
+
self._accepting: threading.Thread | None = None
|
|
131
|
+
self._windows: list[_Window] = []
|
|
132
|
+
self._latest_inputs: dict[str, Any] | None = None
|
|
133
|
+
self._last_input_at: float | None = None
|
|
134
|
+
self._closed = False
|
|
135
|
+
self._last_error: str | None = None
|
|
136
|
+
self._frames_sent = 0
|
|
137
|
+
self.port: int | None = None
|
|
138
|
+
|
|
139
|
+
# -- lifecycle ----------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
def start(self) -> None:
|
|
142
|
+
"""Bind and listen. Failing to bind leaves the link simply unavailable.
|
|
143
|
+
|
|
144
|
+
The service must run without a display, exactly as it runs without a
|
|
145
|
+
cable; a taken port is a reason for ``status`` to say so, not to refuse
|
|
146
|
+
to start.
|
|
147
|
+
|
|
148
|
+
Starting a link that was closed brings it back, the way starting a
|
|
149
|
+
stopped USB transport does. Both devices are reached through one shared
|
|
150
|
+
instance per process, and a shut-down service leaves that instance
|
|
151
|
+
behind; a link that stayed dead would make the next service in the same
|
|
152
|
+
process report a display that can never appear, while the hardware in
|
|
153
|
+
the same situation simply reconnects.
|
|
154
|
+
"""
|
|
155
|
+
with self._lock:
|
|
156
|
+
if self._server is not None:
|
|
157
|
+
return
|
|
158
|
+
self._closed = False
|
|
159
|
+
try:
|
|
160
|
+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
161
|
+
if not sys.platform.startswith("win"):
|
|
162
|
+
# On POSIX this only skips the TIME_WAIT delay after a
|
|
163
|
+
# restart. On Windows it means something else entirely —
|
|
164
|
+
# permission to take a port another socket already holds —
|
|
165
|
+
# and it turns a plain "in use" into WSAEACCES, which reads
|
|
166
|
+
# like a privilege problem and sends you looking in the
|
|
167
|
+
# wrong place. The platform default is what we want there.
|
|
168
|
+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
169
|
+
server.bind((self.host, self.requested_port))
|
|
170
|
+
server.listen(4)
|
|
171
|
+
except OSError as exc:
|
|
172
|
+
self._last_error = f"cannot listen on {self.host}:{self.requested_port}: {exc}"
|
|
173
|
+
logger.warning("%s", self._last_error)
|
|
174
|
+
return
|
|
175
|
+
self._server = server
|
|
176
|
+
# Port 0 means "any free port"; ask the socket which one it got.
|
|
177
|
+
self.port = server.getsockname()[1]
|
|
178
|
+
self._last_error = None
|
|
179
|
+
self._accepting = threading.Thread(
|
|
180
|
+
target=self._accept_loop, name="lefx-simulator-accept", daemon=True
|
|
181
|
+
)
|
|
182
|
+
self._accepting.start()
|
|
183
|
+
logger.info("simulator link listening on %s:%s", self.host, self.port)
|
|
184
|
+
|
|
185
|
+
def close(self) -> None:
|
|
186
|
+
"""Idempotent."""
|
|
187
|
+
with self._lock:
|
|
188
|
+
if self._closed:
|
|
189
|
+
return
|
|
190
|
+
self._closed = True
|
|
191
|
+
server, self._server = self._server, None
|
|
192
|
+
windows, self._windows = self._windows, []
|
|
193
|
+
if server is not None:
|
|
194
|
+
try:
|
|
195
|
+
server.close()
|
|
196
|
+
except OSError:
|
|
197
|
+
pass
|
|
198
|
+
for window in windows:
|
|
199
|
+
window.close()
|
|
200
|
+
|
|
201
|
+
# -- state --------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def connected(self) -> bool:
|
|
205
|
+
with self._lock:
|
|
206
|
+
return any(window.alive for window in self._windows)
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def window_count(self) -> int:
|
|
210
|
+
with self._lock:
|
|
211
|
+
return sum(1 for window in self._windows if window.alive)
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def last_error(self) -> str | None:
|
|
215
|
+
with self._lock:
|
|
216
|
+
return self._last_error
|
|
217
|
+
|
|
218
|
+
def detail(self) -> str | None:
|
|
219
|
+
"""Why there is no display, in words, or ``None`` when there is one."""
|
|
220
|
+
with self._lock:
|
|
221
|
+
if self._closed:
|
|
222
|
+
return "simulator link closed"
|
|
223
|
+
if self._last_error is not None:
|
|
224
|
+
return self._last_error
|
|
225
|
+
if self._server is None:
|
|
226
|
+
return "simulator link not started"
|
|
227
|
+
if not any(window.alive for window in self._windows):
|
|
228
|
+
return f"no ring window connected on {self.host}:{self.port}"
|
|
229
|
+
return None
|
|
230
|
+
|
|
231
|
+
def stats(self) -> dict[str, Any]:
|
|
232
|
+
with self._lock:
|
|
233
|
+
return {
|
|
234
|
+
"host": self.host,
|
|
235
|
+
"port": self.port,
|
|
236
|
+
"windows": sum(1 for window in self._windows if window.alive),
|
|
237
|
+
"frames_sent": self._frames_sent,
|
|
238
|
+
"last_error": self._last_error,
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
# -- output -------------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
def send_frame(self, leds: tuple[int, ...] | list[int], timestamp: float) -> bool:
|
|
244
|
+
"""Hand the frame to every connected window. False when there is none."""
|
|
245
|
+
message = protocol.encode(protocol.frame(leds, timestamp))
|
|
246
|
+
with self._lock:
|
|
247
|
+
windows = [window for window in self._windows if window.alive]
|
|
248
|
+
if windows:
|
|
249
|
+
self._frames_sent += 1
|
|
250
|
+
for window in windows:
|
|
251
|
+
window.send_frame(message)
|
|
252
|
+
return bool(windows)
|
|
253
|
+
|
|
254
|
+
# -- input --------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
def latest_inputs(self) -> dict[str, Any] | None:
|
|
257
|
+
"""The most recent slider reading, or ``None`` when nothing reported.
|
|
258
|
+
|
|
259
|
+
A reading is *what a connected window says*, so no window means no
|
|
260
|
+
reading — decided here rather than left to the reader thread's cleanup.
|
|
261
|
+
A window's socket closing and its bookkeeping being tidied up are two
|
|
262
|
+
moments, and in between, a caller could otherwise see a reading from a
|
|
263
|
+
window that is already gone. Making it definitional removes the window
|
|
264
|
+
in which that is possible instead of narrowing it.
|
|
265
|
+
"""
|
|
266
|
+
with self._lock:
|
|
267
|
+
if not any(window.alive for window in self._windows):
|
|
268
|
+
return None
|
|
269
|
+
return None if self._latest_inputs is None else dict(self._latest_inputs)
|
|
270
|
+
|
|
271
|
+
# -- accepting and reading ----------------------------------------------
|
|
272
|
+
|
|
273
|
+
def _accept_loop(self) -> None:
|
|
274
|
+
while True:
|
|
275
|
+
with self._lock:
|
|
276
|
+
server = self._server
|
|
277
|
+
if server is None:
|
|
278
|
+
return
|
|
279
|
+
try:
|
|
280
|
+
sock, address = server.accept()
|
|
281
|
+
except OSError:
|
|
282
|
+
return # The listening socket was closed; that is the exit.
|
|
283
|
+
sock.settimeout(SEND_TIMEOUT_S)
|
|
284
|
+
window = _Window(sock, address)
|
|
285
|
+
with self._lock:
|
|
286
|
+
if self._closed:
|
|
287
|
+
window.close()
|
|
288
|
+
return
|
|
289
|
+
self._windows = [item for item in self._windows if item.alive]
|
|
290
|
+
self._windows.append(window)
|
|
291
|
+
led_count = self.led_count
|
|
292
|
+
logger.info("ring window connected from %s", address)
|
|
293
|
+
window.send_control(protocol.encode(protocol.hello(led_count=led_count)))
|
|
294
|
+
threading.Thread(
|
|
295
|
+
target=self._read_loop,
|
|
296
|
+
args=(window,),
|
|
297
|
+
name="lefx-simulator-reader",
|
|
298
|
+
daemon=True,
|
|
299
|
+
).start()
|
|
300
|
+
|
|
301
|
+
def _read_loop(self, window: _Window) -> None:
|
|
302
|
+
try:
|
|
303
|
+
while window.alive:
|
|
304
|
+
try:
|
|
305
|
+
message = protocol.read_message(window.sock)
|
|
306
|
+
except TimeoutError:
|
|
307
|
+
# The window has nothing to say. Silence is not a fault:
|
|
308
|
+
# sliders only report when they move.
|
|
309
|
+
continue
|
|
310
|
+
if message is None:
|
|
311
|
+
break
|
|
312
|
+
self._handle(message)
|
|
313
|
+
except (OSError, protocol.ProtocolError) as exc:
|
|
314
|
+
logger.debug("window %s reader stopped: %s", window.address, exc)
|
|
315
|
+
finally:
|
|
316
|
+
window.close()
|
|
317
|
+
with self._lock:
|
|
318
|
+
self._windows = [item for item in self._windows if item.alive]
|
|
319
|
+
if not self._windows:
|
|
320
|
+
# No window, no reading. Keeping the last one would let an
|
|
321
|
+
# effect keep pointing at a direction nothing is measuring.
|
|
322
|
+
self._latest_inputs = None
|
|
323
|
+
logger.info("ring window disconnected: %s", window.address)
|
|
324
|
+
|
|
325
|
+
def _handle(self, message: dict[str, Any]) -> None:
|
|
326
|
+
if message.get("type") != protocol.INPUT:
|
|
327
|
+
return
|
|
328
|
+
direction = message.get("direction_deg")
|
|
329
|
+
state = message.get("detection_state", "none")
|
|
330
|
+
with self._lock:
|
|
331
|
+
self._latest_inputs = {
|
|
332
|
+
"direction_deg": None if direction is None else float(direction),
|
|
333
|
+
"detection_state": str(state),
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
__all__ = ["SEND_TIMEOUT_S", "SimulatorLink", "default_port"]
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""The wire format between the service and the ring window.
|
|
2
|
+
|
|
3
|
+
Length-prefixed JSON over a loopback TCP connection: a four-byte big-endian
|
|
4
|
+
length followed by that many bytes of UTF-8 JSON. Framing is explicit because
|
|
5
|
+
TCP is a byte stream — without a length, two frames sent quickly enough arrive
|
|
6
|
+
as one read, and a large one arrives in pieces.
|
|
7
|
+
|
|
8
|
+
Small and readable on purpose. This carries a colour ring and two slider values
|
|
9
|
+
between two processes on the same machine; anything cleverer would be harder to
|
|
10
|
+
debug than the thing it transports.
|
|
11
|
+
|
|
12
|
+
Free of Qt and of everything else optional: both halves of the simulator import
|
|
13
|
+
this, and only one of them has a GUI.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import struct
|
|
20
|
+
from typing import Any, Mapping
|
|
21
|
+
|
|
22
|
+
PROTOCOL_VERSION = 3
|
|
23
|
+
|
|
24
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
25
|
+
DEFAULT_PORT = 8787
|
|
26
|
+
"""Loopback only. The simulator is a local stand-in for a cable, not a network
|
|
27
|
+
service, and binding it to anything reachable would make it one.
|
|
28
|
+
|
|
29
|
+
Deliberately clear of 8765 and its neighbours: the HTTP interface uses 8765 and
|
|
30
|
+
falls back through the ports just above it, and earlier generations of this
|
|
31
|
+
controller took 8766. A default that collides with software the same person is
|
|
32
|
+
likely to be running is a bad default, however free the port is in the abstract.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
PORT_ENV_VAR = "LEFX_SIMULATOR_PORT"
|
|
36
|
+
"""Lets both halves agree on a port without either being told on the command
|
|
37
|
+
line — useful when several checkouts run side by side."""
|
|
38
|
+
|
|
39
|
+
MAX_MESSAGE_BYTES = 1 << 20
|
|
40
|
+
"""A ring of colours is a few hundred bytes. Anything of this size is a bug or
|
|
41
|
+
a stray client, and reading it would be the mistake."""
|
|
42
|
+
|
|
43
|
+
_HEADER = struct.Struct(">I")
|
|
44
|
+
HEADER_SIZE = _HEADER.size
|
|
45
|
+
|
|
46
|
+
# Message kinds
|
|
47
|
+
HELLO = "hello"
|
|
48
|
+
FRAME = "frame"
|
|
49
|
+
INPUT = "input"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ProtocolError(Exception):
|
|
53
|
+
"""The peer sent something that is not a message of this protocol."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def encode(message: Mapping[str, Any]) -> bytes:
|
|
57
|
+
body = json.dumps(message, separators=(",", ":")).encode("utf-8")
|
|
58
|
+
if len(body) > MAX_MESSAGE_BYTES:
|
|
59
|
+
raise ProtocolError(f"message of {len(body)} bytes exceeds the limit")
|
|
60
|
+
return _HEADER.pack(len(body)) + body
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def decode(body: bytes) -> dict[str, Any]:
|
|
64
|
+
try:
|
|
65
|
+
message = json.loads(body.decode("utf-8"))
|
|
66
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
67
|
+
raise ProtocolError(f"not valid JSON: {exc}") from exc
|
|
68
|
+
if not isinstance(message, dict):
|
|
69
|
+
raise ProtocolError("a message must be a JSON object")
|
|
70
|
+
return message
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def payload_length(header: bytes) -> int:
|
|
74
|
+
if len(header) != HEADER_SIZE:
|
|
75
|
+
raise ProtocolError(f"a header is {HEADER_SIZE} bytes, got {len(header)}")
|
|
76
|
+
(length,) = _HEADER.unpack(header)
|
|
77
|
+
if length > MAX_MESSAGE_BYTES:
|
|
78
|
+
raise ProtocolError(f"announced {length} bytes, over the limit")
|
|
79
|
+
return length
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def hello(*, led_count: int) -> dict[str, Any]:
|
|
83
|
+
"""Sent to a window the moment it connects, so it can size the ring."""
|
|
84
|
+
return {"type": HELLO, "protocol": PROTOCOL_VERSION, "led_count": int(led_count)}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def frame(leds: tuple[int, ...] | list[int], timestamp: float) -> dict[str, Any]:
|
|
88
|
+
return {"type": FRAME, "leds": [int(value) for value in leds], "timestamp": float(timestamp)}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def inputs(*, direction_deg: float | None, detection_state: str) -> dict[str, Any]:
|
|
92
|
+
"""What the window reports back — the same shape the hardware produces.
|
|
93
|
+
|
|
94
|
+
Deliberately identical to the reSpeaker's decoded ``DOA_VALUE``: the point
|
|
95
|
+
of the simulator is that nothing above the port can tell the two apart.
|
|
96
|
+
"""
|
|
97
|
+
return {
|
|
98
|
+
"type": INPUT,
|
|
99
|
+
"direction_deg": None if direction_deg is None else float(direction_deg),
|
|
100
|
+
"detection_state": str(detection_state),
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_message(sock: Any) -> dict[str, Any] | None:
|
|
105
|
+
"""Read exactly one message, or ``None`` when the peer closed cleanly.
|
|
106
|
+
|
|
107
|
+
Both halves need this, and both would otherwise get the short-read handling
|
|
108
|
+
subtly different — ``recv`` returning fewer bytes than asked for is normal,
|
|
109
|
+
not an error.
|
|
110
|
+
"""
|
|
111
|
+
header = _read_exactly(sock, HEADER_SIZE)
|
|
112
|
+
if header is None:
|
|
113
|
+
return None
|
|
114
|
+
body = _read_exactly(sock, payload_length(header))
|
|
115
|
+
if body is None:
|
|
116
|
+
raise ProtocolError("connection ended between header and body")
|
|
117
|
+
return decode(body)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _read_exactly(sock: Any, count: int) -> bytes | None:
|
|
121
|
+
"""``None`` for a clean close on a message boundary; a partial one raises.
|
|
122
|
+
|
|
123
|
+
A read timeout is only benign at a boundary — there, it means the peer had
|
|
124
|
+
nothing to say. Half way through a message it means the rest is lost and the
|
|
125
|
+
stream is out of step, so it becomes a protocol error rather than something
|
|
126
|
+
a caller might reasonably retry into a garbled read.
|
|
127
|
+
"""
|
|
128
|
+
chunks: list[bytes] = []
|
|
129
|
+
remaining = count
|
|
130
|
+
while remaining > 0:
|
|
131
|
+
try:
|
|
132
|
+
chunk = sock.recv(remaining)
|
|
133
|
+
except TimeoutError:
|
|
134
|
+
if chunks:
|
|
135
|
+
raise ProtocolError("timed out mid-message") from None
|
|
136
|
+
raise
|
|
137
|
+
if not chunk:
|
|
138
|
+
if chunks:
|
|
139
|
+
raise ProtocolError("connection ended mid-message")
|
|
140
|
+
return None
|
|
141
|
+
chunks.append(chunk)
|
|
142
|
+
remaining -= len(chunk)
|
|
143
|
+
return b"".join(chunks)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
__all__ = [
|
|
147
|
+
"DEFAULT_HOST",
|
|
148
|
+
"DEFAULT_PORT",
|
|
149
|
+
"FRAME",
|
|
150
|
+
"HEADER_SIZE",
|
|
151
|
+
"HELLO",
|
|
152
|
+
"INPUT",
|
|
153
|
+
"MAX_MESSAGE_BYTES",
|
|
154
|
+
"PORT_ENV_VAR",
|
|
155
|
+
"PROTOCOL_VERSION",
|
|
156
|
+
"ProtocolError",
|
|
157
|
+
"decode",
|
|
158
|
+
"encode",
|
|
159
|
+
"frame",
|
|
160
|
+
"hello",
|
|
161
|
+
"inputs",
|
|
162
|
+
"payload_length",
|
|
163
|
+
"read_message",
|
|
164
|
+
]
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""The direction-of-arrival input half of the software device.
|
|
2
|
+
|
|
3
|
+
Same shape as the hardware provider, down to the value ranges: ``direction_deg``
|
|
4
|
+
is a float in ``[0, 360)`` and ``detection_state`` is one of the values
|
|
5
|
+
``direction_indicator`` declares. An effect cannot tell which of the two it is
|
|
6
|
+
reading from, and that is the whole point of the simulator being a device rather
|
|
7
|
+
than a preview mode.
|
|
8
|
+
|
|
9
|
+
With no window attached, :meth:`sample` returns ``None`` — the same answer an
|
|
10
|
+
unplugged reSpeaker gives, which the engine turns into ``waiting`` and then,
|
|
11
|
+
once the grace period lapses, ``failed``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import threading
|
|
17
|
+
from typing import Any, Mapping
|
|
18
|
+
|
|
19
|
+
from lefx.sdk import DoaCalibration, InputContext
|
|
20
|
+
|
|
21
|
+
from .link import SimulatorLink
|
|
22
|
+
|
|
23
|
+
DETECTION_STATES = ("none", "sound", "speech")
|
|
24
|
+
"""Mirrors the enum ``direction_indicator`` declares. A window that reports
|
|
25
|
+
anything else is reporting something no effect can use."""
|
|
26
|
+
|
|
27
|
+
DEFAULT_MAX_HZ = 30.0
|
|
28
|
+
"""The same ceiling the reSpeaker's provider uses.
|
|
29
|
+
|
|
30
|
+
Nothing here needs protecting from being read too often — the value is already
|
|
31
|
+
in memory. It is rate-limited anyway because an update cadence is part of what a
|
|
32
|
+
device is: an effect that only looks smooth against a source refreshing as fast
|
|
33
|
+
as it renders would look different on hardware, and then the simulator would
|
|
34
|
+
have stopped being a stand-in for it.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SimulatorDoaProvider:
|
|
39
|
+
"""Hands out the direction the ring window's controls are set to."""
|
|
40
|
+
|
|
41
|
+
name = "simulator.doa"
|
|
42
|
+
capability = "doa"
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
link: SimulatorLink,
|
|
47
|
+
*,
|
|
48
|
+
max_hz: float = DEFAULT_MAX_HZ,
|
|
49
|
+
calibration: DoaCalibration | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
if max_hz <= 0:
|
|
52
|
+
raise ValueError("max_hz must be greater than zero")
|
|
53
|
+
self.link = link
|
|
54
|
+
self.max_hz = float(max_hz)
|
|
55
|
+
self.interval_s = 1.0 / self.max_hz
|
|
56
|
+
# Carried for the same reason the hardware carries it, and applied at
|
|
57
|
+
# the same point. A simulator whose readings needed no calibrating
|
|
58
|
+
# would be a device with one fewer way to be wrong than the one it
|
|
59
|
+
# stands in for, and the difference would show up first in whatever was
|
|
60
|
+
# being debugged against it.
|
|
61
|
+
self.calibration = calibration if calibration is not None else DoaCalibration()
|
|
62
|
+
self._last_attempt_at: float | None = None
|
|
63
|
+
self._lock = threading.RLock()
|
|
64
|
+
self._snapshot: dict[str, Any] | None = None
|
|
65
|
+
self._last_success_at: float | None = None
|
|
66
|
+
self._last_error: str | None = None
|
|
67
|
+
self._refresh_count = 0
|
|
68
|
+
self._closed = False
|
|
69
|
+
|
|
70
|
+
def refresh(self, now: float) -> bool:
|
|
71
|
+
"""Take the window's current setting, if the interval has elapsed.
|
|
72
|
+
|
|
73
|
+
Returns whether it tried — the same answer, on the same schedule, as the
|
|
74
|
+
hardware provider gives.
|
|
75
|
+
"""
|
|
76
|
+
with self._lock:
|
|
77
|
+
if self._closed:
|
|
78
|
+
return False
|
|
79
|
+
if self._last_attempt_at is not None and now - self._last_attempt_at < self.interval_s:
|
|
80
|
+
return False
|
|
81
|
+
self._last_attempt_at = now
|
|
82
|
+
self._refresh_count += 1
|
|
83
|
+
|
|
84
|
+
reading = self.link.latest_inputs()
|
|
85
|
+
if reading is None:
|
|
86
|
+
with self._lock:
|
|
87
|
+
self._snapshot = None
|
|
88
|
+
self._last_error = self.link.detail()
|
|
89
|
+
return True
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
snapshot = self._validate(reading)
|
|
93
|
+
snapshot["direction_deg"] = self.calibration.apply(snapshot["direction_deg"])
|
|
94
|
+
except ValueError as exc:
|
|
95
|
+
with self._lock:
|
|
96
|
+
self._snapshot = None
|
|
97
|
+
self._last_error = str(exc)
|
|
98
|
+
return True
|
|
99
|
+
|
|
100
|
+
with self._lock:
|
|
101
|
+
self._snapshot = snapshot
|
|
102
|
+
self._last_success_at = now
|
|
103
|
+
self._last_error = None
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _validate(reading: Mapping[str, Any]) -> dict[str, Any]:
|
|
108
|
+
"""Hold the window to the same contract the firmware is held to.
|
|
109
|
+
|
|
110
|
+
The window is a separate process that could be any build; letting an
|
|
111
|
+
out-of-range angle through here would make the simulator laxer than the
|
|
112
|
+
hardware, and the two would stop being interchangeable.
|
|
113
|
+
"""
|
|
114
|
+
direction = reading.get("direction_deg")
|
|
115
|
+
if direction is not None:
|
|
116
|
+
try:
|
|
117
|
+
direction = float(direction)
|
|
118
|
+
except (TypeError, ValueError):
|
|
119
|
+
raise ValueError(f"Invalid direction_deg: {reading.get('direction_deg')!r}") from None
|
|
120
|
+
if not 0.0 <= direction < 360.0:
|
|
121
|
+
raise ValueError(f"direction_deg is out of range: {direction!r}")
|
|
122
|
+
|
|
123
|
+
state = reading.get("detection_state", "none")
|
|
124
|
+
if state not in DETECTION_STATES:
|
|
125
|
+
raise ValueError(f"Unknown detection_state: {state!r}")
|
|
126
|
+
|
|
127
|
+
return {"direction_deg": direction, "detection_state": state}
|
|
128
|
+
|
|
129
|
+
def sample(self, ctx: InputContext) -> Mapping[str, Any] | None:
|
|
130
|
+
del ctx
|
|
131
|
+
with self._lock:
|
|
132
|
+
return None if self._snapshot is None else dict(self._snapshot)
|
|
133
|
+
|
|
134
|
+
def status(self, now: float) -> dict[str, Any]:
|
|
135
|
+
with self._lock:
|
|
136
|
+
age_ms = (
|
|
137
|
+
None
|
|
138
|
+
if self._last_success_at is None
|
|
139
|
+
else max(0, int(round((now - self._last_success_at) * 1000.0)))
|
|
140
|
+
)
|
|
141
|
+
return {
|
|
142
|
+
"provider_id": self.capability,
|
|
143
|
+
"device": self.name,
|
|
144
|
+
"max_hz": self.max_hz,
|
|
145
|
+
"refresh_count": self._refresh_count,
|
|
146
|
+
"age_ms": age_ms,
|
|
147
|
+
"last_error": self._last_error,
|
|
148
|
+
"available": self._snapshot is not None,
|
|
149
|
+
"calibration": self.calibration.to_dict(),
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
"""Idempotent. The link is shared with the sink, so it is not closed here."""
|
|
154
|
+
with self._lock:
|
|
155
|
+
self._closed = True
|
|
156
|
+
self._snapshot = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
__all__ = ["DEFAULT_MAX_HZ", "DETECTION_STATES", "SimulatorDoaProvider"]
|