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.
@@ -0,0 +1,113 @@
1
+ """What the entry points resolve to.
2
+
3
+ Mirrors the hardware package deliberately: two factories, one shared transport,
4
+ ``**options`` tolerated everywhere. The service treats both devices through the
5
+ same code path, so anything asymmetric here would show up as the service having
6
+ to know which one it has.
7
+
8
+ Nothing in this import chain touches Qt. ``registration``, ``link``, ``sink``
9
+ and ``provider`` must stay importable in a service process that has no GUI
10
+ toolkit installed at all — PySide6 is an extra, and the window is a separate
11
+ program.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import threading
17
+ from typing import Any
18
+
19
+ from lefx.sdk import FrameSink, InputProvider, resolve_calibration
20
+
21
+ from .link import SimulatorLink
22
+ from .provider import DEFAULT_MAX_HZ, SimulatorDoaProvider
23
+ from .sink import SimulatorFrameSink
24
+
25
+ DEVICE_NAME = "simulator"
26
+ """The key this device's calibration is stored under."""
27
+
28
+ _lock = threading.Lock()
29
+ _link: SimulatorLink | None = None
30
+
31
+
32
+ def shared_link(**options: Any) -> SimulatorLink:
33
+ """The one loopback link, created on first use and left listening.
34
+
35
+ Sink and provider share it the way they share a USB cable on the hardware:
36
+ two listeners on one port is not a thing, and two links would leave the
37
+ window able to reach only one of them.
38
+ """
39
+ global _link
40
+ with _lock:
41
+ if _link is None:
42
+ _link = SimulatorLink(**options)
43
+ link = _link
44
+ link.start()
45
+ return link
46
+
47
+
48
+ def reset_shared_link() -> None:
49
+ """Drop the shared link, closing it first. For tests and restarts."""
50
+ global _link
51
+ with _lock:
52
+ link, _link = _link, None
53
+ if link is not None:
54
+ link.close()
55
+
56
+
57
+ def _link_options(led_count: int, host: str | None, port: int | str | None) -> dict[str, Any]:
58
+ """Only pass what was actually given, so the link keeps its own defaults.
59
+
60
+ ``port`` may arrive as text from ``--sink-option port=8770``; the CLI does
61
+ not know the type a sink wants for an option, so the conversion belongs here.
62
+ """
63
+ options: dict[str, Any] = {"led_count": int(led_count)}
64
+ if host is not None:
65
+ options["host"] = str(host)
66
+ if port is not None:
67
+ options["port"] = int(port)
68
+ return options
69
+
70
+
71
+ def create_frame_sink(
72
+ *, led_count: int = 12, host: str | None = None, port: int | str | None = None, **options: Any
73
+ ) -> FrameSink:
74
+ del options
75
+ link = shared_link(**_link_options(led_count, host, port))
76
+ return SimulatorFrameSink(link, led_count=led_count)
77
+
78
+
79
+ def create_doa_provider(
80
+ *,
81
+ led_count: int = 12,
82
+ host: str | None = None,
83
+ port: int | str | None = None,
84
+ max_hz: float = DEFAULT_MAX_HZ,
85
+ angle_offset_deg: Any = None,
86
+ reverse: Any = None,
87
+ calibration_file: Any = None,
88
+ **options: Any,
89
+ ) -> InputProvider:
90
+ del options
91
+ # The sink is built before the providers, so when both are the simulator's
92
+ # this call finds the link the sink already configured and its own defaults
93
+ # never come into play.
94
+ link = shared_link(**_link_options(led_count, host, port))
95
+ return SimulatorDoaProvider(
96
+ link,
97
+ max_hz=max_hz,
98
+ calibration=resolve_calibration(
99
+ DEVICE_NAME,
100
+ angle_offset_deg=angle_offset_deg,
101
+ reverse=reverse,
102
+ path=calibration_file,
103
+ ),
104
+ )
105
+
106
+
107
+ __all__ = [
108
+ "DEVICE_NAME",
109
+ "create_doa_provider",
110
+ "create_frame_sink",
111
+ "reset_shared_link",
112
+ "shared_link",
113
+ ]
@@ -0,0 +1,105 @@
1
+ """The ring display.
2
+
3
+ Ported from the old PySide6 demo, with its two defects fixed: the LED count is a
4
+ parameter rather than a literal twelve, and the widget no longer reaches into a
5
+ controller — it is given colours and draws them, which is all a display does.
6
+
7
+ Black is drawn as black. In a composed frame ``None`` means "contribute
8
+ nothing"; ``0x000000`` is a colour and covers what is under it. Only opaque
9
+ integers reach a sink, so what arrives here is always a colour — and painting
10
+ one of them as "off" would misrepresent a ring the hardware would light dark.
11
+
12
+ Importing this module needs PySide6. Nothing on the service side imports it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+
19
+ from PySide6.QtCore import Qt
20
+ from PySide6.QtGui import QColor, QPainter, QPen
21
+ from PySide6.QtWidgets import QWidget
22
+
23
+ BODY_COLOR = QColor(20, 22, 28)
24
+ RIM_COLOR = QColor(40, 44, 52)
25
+ SOCKET_COLOR = QColor(32, 35, 42)
26
+
27
+
28
+ class LedRingWidget(QWidget):
29
+ """Draws one LED per position, arranged clockwise from the top."""
30
+
31
+ def __init__(self, led_count: int = 12, parent: QWidget | None = None) -> None:
32
+ super().__init__(parent)
33
+ self.setMinimumSize(220, 220)
34
+ self._led_count = max(1, int(led_count))
35
+ self._colors: list[int] = [0] * self._led_count
36
+
37
+ @property
38
+ def led_count(self) -> int:
39
+ return self._led_count
40
+
41
+ def set_led_count(self, led_count: int) -> None:
42
+ """Resize the ring — the service announces its size on connection."""
43
+ count = max(1, int(led_count))
44
+ if count == self._led_count:
45
+ return
46
+ self._led_count = count
47
+ self._colors = [0] * count
48
+ self.update()
49
+
50
+ def set_colors(self, colors: list[int]) -> None:
51
+ """Show one frame. A frame of the wrong length is not drawn at all.
52
+
53
+ Padding or truncating would put colours on positions the sender never
54
+ addressed, which is a worse answer than the ring simply not moving.
55
+ """
56
+ if len(colors) != self._led_count:
57
+ return
58
+ self._colors = list(colors)
59
+ self.update()
60
+
61
+ def paintEvent(self, event) -> None: # noqa: N802 — Qt's spelling
62
+ del event
63
+ painter = QPainter(self)
64
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
65
+
66
+ center_x = self.width() / 2.0
67
+ center_y = self.height() / 2.0
68
+ radius = min(self.width(), self.height()) / 2.0 - 25.0
69
+
70
+ painter.setPen(QPen(RIM_COLOR, 4))
71
+ painter.setBrush(BODY_COLOR)
72
+ painter.drawEllipse(
73
+ int(center_x - radius - 10),
74
+ int(center_y - radius - 10),
75
+ int((radius + 10) * 2),
76
+ int((radius + 10) * 2),
77
+ )
78
+
79
+ # Keep the dots from overlapping once the ring is densely populated,
80
+ # and from becoming absurd when it holds three.
81
+ spacing = 2.0 * math.pi * radius / self._led_count
82
+ led_radius = max(3.0, min(14.0, spacing * 0.35))
83
+
84
+ for index, color_int in enumerate(self._colors):
85
+ # Zero at the top, increasing clockwise: the same convention
86
+ # position_for_angle uses, so LED n is where an effect expects it.
87
+ angle = math.radians(index * 360.0 / self._led_count - 90.0)
88
+ x = center_x + radius * math.cos(angle)
89
+ y = center_y + radius * math.sin(angle)
90
+
91
+ painter.setPen(QPen(SOCKET_COLOR, 1))
92
+ painter.setBrush(
93
+ QColor((color_int >> 16) & 0xFF, (color_int >> 8) & 0xFF, color_int & 0xFF)
94
+ )
95
+ painter.drawEllipse(
96
+ int(x - led_radius),
97
+ int(y - led_radius),
98
+ int(led_radius * 2),
99
+ int(led_radius * 2),
100
+ )
101
+
102
+ painter.end()
103
+
104
+
105
+ __all__ = ["LedRingWidget"]
@@ -0,0 +1,69 @@
1
+ """The output half of the software device.
2
+
3
+ Same port, same obligations as the hardware sink: it never raises, and it says
4
+ whether it can deliver. What differs is only the reason it cannot — a closed
5
+ window instead of an unplugged cable — and that difference lives in the detail
6
+ string, where the rest of the system reads it as text rather than branching on it.
7
+
8
+ Unlike USB, a local socket write is cheap, so there is no change detection here.
9
+ Sending every frame keeps the window honest about the render rate.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+
16
+ from lefx.sdk import OutputFrame, SinkStatus
17
+
18
+ from .link import SimulatorLink
19
+
20
+ logger = logging.getLogger("lefx.device.simulated_respeaker.sink")
21
+
22
+
23
+ class SimulatorFrameSink:
24
+ """Sends composed frames to the ring window."""
25
+
26
+ name = "simulator"
27
+
28
+ def __init__(self, link: SimulatorLink, *, led_count: int = 12) -> None:
29
+ self.link = link
30
+ self.led_count = int(led_count)
31
+ self._error: str | None = None
32
+ self._closed = False
33
+
34
+ def apply_frame(self, frame: OutputFrame) -> None:
35
+ if self._closed:
36
+ return
37
+ leds = tuple(frame.leds)
38
+ if len(leds) != self.led_count:
39
+ # The window was told the ring size when it connected; a frame of a
40
+ # different length would draw wrongly rather than not at all.
41
+ self._error = f"frame has {len(leds)} LEDs, this ring has {self.led_count}"
42
+ return
43
+ try:
44
+ self.link.send_frame(leds, frame.timestamp)
45
+ self._error = None
46
+ except Exception as exc:
47
+ # Same rule as the hardware: a frame arrives thirty times a second,
48
+ # and a display that went away between two of them is not an
49
+ # exception for the render loop to handle.
50
+ self._error = str(exc)
51
+ logger.debug("frame not delivered: %s", exc)
52
+
53
+ def status(self) -> SinkStatus:
54
+ if self._closed:
55
+ return SinkStatus(available=False, detail="sink closed")
56
+ if self._error is not None:
57
+ return SinkStatus(available=False, detail=self._error)
58
+ detail = self.link.detail()
59
+ return SinkStatus(available=detail is None, detail=detail)
60
+
61
+ def close(self) -> None:
62
+ """Idempotent."""
63
+ if self._closed:
64
+ return
65
+ self._closed = True
66
+ self.link.close()
67
+
68
+
69
+ __all__ = ["SimulatorFrameSink"]
@@ -0,0 +1,168 @@
1
+ """The ring window: display plus the controls that stand in for microphones.
2
+
3
+ A full device double needs both halves. The ring shows what the hardware would
4
+ show; the controls produce what the hardware would measure, in the same shape and
5
+ the same ranges. Setting the direction here and watching ``direction_indicator``
6
+ follow is the same test as speaking into the array.
7
+
8
+ Everything the socket thread produces crosses into the GUI thread through Qt
9
+ signals. Painting from another thread is the classic way to make a Qt program
10
+ crash in ways that look like anything but threading.
11
+
12
+ Needs PySide6. Imported only by the window process.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from PySide6.QtCore import Qt, Signal
18
+ from PySide6.QtWidgets import (
19
+ QCheckBox,
20
+ QComboBox,
21
+ QFormLayout,
22
+ QGroupBox,
23
+ QHBoxLayout,
24
+ QLabel,
25
+ QMainWindow,
26
+ QSlider,
27
+ QVBoxLayout,
28
+ QWidget,
29
+ )
30
+
31
+ from . import protocol
32
+ from .client import SimulatorClient
33
+ from .provider import DETECTION_STATES
34
+ from .ring import LedRingWidget
35
+
36
+ STYLE = """
37
+ QMainWindow, QWidget { background-color: #16181d; color: #d8dce4; }
38
+ QGroupBox { border: 1px solid #2b2f39; border-radius: 6px; margin-top: 10px; padding-top: 12px; }
39
+ QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 4px; color: #8d94a3; }
40
+ QLabel#status_ok { color: #5fd08a; }
41
+ QLabel#status_bad { color: #e08a5f; }
42
+ """
43
+
44
+
45
+ class SimulatorWindow(QMainWindow):
46
+ """The simulator's user interface, and the client that feeds it."""
47
+
48
+ frame_received = Signal(list)
49
+ led_count_received = Signal(int)
50
+ connection_changed = Signal(bool, str)
51
+
52
+ def __init__(
53
+ self,
54
+ *,
55
+ host: str = protocol.DEFAULT_HOST,
56
+ port: int | None = None,
57
+ led_count: int = 12,
58
+ ) -> None:
59
+ super().__init__()
60
+ self.setWindowTitle("reSpeaker LED — Simulator")
61
+ self.setStyleSheet(STYLE)
62
+ self.resize(420, 620)
63
+
64
+ self.ring = LedRingWidget(led_count)
65
+ self._build_ui()
66
+
67
+ # Queued across threads by Qt, which is the point: the client's reader
68
+ # thread emits, the GUI thread receives.
69
+ self.frame_received.connect(self._on_frame)
70
+ self.led_count_received.connect(self.ring.set_led_count)
71
+ self.connection_changed.connect(self._on_connection)
72
+
73
+ self.client = SimulatorClient(
74
+ host=host,
75
+ port=port,
76
+ on_frame=lambda leds, _timestamp: self.frame_received.emit(leds),
77
+ on_led_count=self.led_count_received.emit,
78
+ on_state=lambda connected, detail: self.connection_changed.emit(
79
+ connected, detail or ""
80
+ ),
81
+ )
82
+ self.client.start()
83
+ self._publish_controls()
84
+
85
+ # -- construction -------------------------------------------------------
86
+
87
+ def _build_ui(self) -> None:
88
+ layout = QVBoxLayout()
89
+ layout.setContentsMargins(16, 16, 16, 16)
90
+ layout.setSpacing(12)
91
+
92
+ self.status = QLabel("Verbinde …")
93
+ self.status.setObjectName("status_bad")
94
+ self.status.setAlignment(Qt.AlignmentFlag.AlignCenter)
95
+ layout.addWidget(self.status)
96
+ layout.addWidget(self.ring, stretch=1)
97
+ layout.addWidget(self._build_controls())
98
+
99
+ central = QWidget(self)
100
+ central.setLayout(layout)
101
+ self.setCentralWidget(central)
102
+
103
+ def _build_controls(self) -> QGroupBox:
104
+ box = QGroupBox("Simulierte Eingaben")
105
+ form = QFormLayout()
106
+
107
+ self.direction = QSlider(Qt.Orientation.Horizontal)
108
+ # Whole degrees over the full circle: 360 is 0, so the range stops one
109
+ # short of it — exactly the range the firmware reports.
110
+ self.direction.setRange(0, 359)
111
+ self.direction.valueChanged.connect(self._publish_controls)
112
+ self.direction_label = QLabel("0°")
113
+
114
+ row = QHBoxLayout()
115
+ row.addWidget(self.direction, stretch=1)
116
+ row.addWidget(self.direction_label)
117
+ holder = QWidget()
118
+ holder.setLayout(row)
119
+ form.addRow("Richtung", holder)
120
+
121
+ self.detection = QComboBox()
122
+ self.detection.addItems(DETECTION_STATES)
123
+ self.detection.currentTextChanged.connect(self._publish_controls)
124
+ form.addRow("Erkennung", self.detection)
125
+
126
+ # The runtime input is nullable, and a device that measures nothing is a
127
+ # case effects have to survive. Without this the null path could only be
128
+ # reached by unplugging something.
129
+ self.reporting = QCheckBox("Richtung melden")
130
+ self.reporting.setChecked(True)
131
+ self.reporting.toggled.connect(self._publish_controls)
132
+ form.addRow("", self.reporting)
133
+
134
+ box.setLayout(form)
135
+ return box
136
+
137
+ # -- signals ------------------------------------------------------------
138
+
139
+ def _publish_controls(self) -> None:
140
+ degrees = float(self.direction.value())
141
+ self.direction_label.setText(f"{int(degrees)}°")
142
+ self.client.set_controls(
143
+ direction_deg=degrees if self.reporting.isChecked() else None,
144
+ detection_state=self.detection.currentText(),
145
+ )
146
+
147
+ def _on_frame(self, leds: list) -> None:
148
+ self.ring.set_colors([int(value) for value in leds])
149
+
150
+ def _on_connection(self, connected: bool, detail: str) -> None:
151
+ self.status.setText(
152
+ f"Verbunden mit {self.client.host}:{self.client.port}"
153
+ if connected
154
+ else (detail or "Nicht verbunden")
155
+ )
156
+ self.status.setObjectName("status_ok" if connected else "status_bad")
157
+ # Qt only re-evaluates the stylesheet when told the selector changed.
158
+ self.status.style().polish(self.status)
159
+ if not connected:
160
+ self.ring.set_colors([0] * self.ring.led_count)
161
+
162
+ def closeEvent(self, event) -> None: # noqa: N802 — Qt's spelling
163
+ """Closing the window is the simulator's equivalent of unplugging."""
164
+ self.client.stop()
165
+ super().closeEvent(event)
166
+
167
+
168
+ __all__ = ["SimulatorWindow"]