led-controller-version-3 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-3.0.2.dist-info/METADATA +172 -0
- led_controller_version_3-3.0.2.dist-info/RECORD +52 -0
- led_controller_version_3-3.0.2.dist-info/WHEEL +4 -0
- led_controller_version_3-3.0.2.dist-info/entry_points.txt +13 -0
- lefx/device/respeaker/__init__.py +35 -0
- lefx/device/respeaker/cli.py +146 -0
- lefx/device/respeaker/contention.py +523 -0
- lefx/device/respeaker/provider.py +158 -0
- lefx/device/respeaker/registration.py +130 -0
- lefx/device/respeaker/sink.py +108 -0
- lefx/device/respeaker/transport.py +344 -0
- lefx/device/respeaker/xvf.py +313 -0
- lefx/engine/__init__.py +110 -0
- lefx/engine/composer.py +203 -0
- lefx/engine/config.py +27 -0
- lefx/engine/errors.py +84 -0
- lefx/engine/inputs.py +196 -0
- lefx/engine/invocation.py +129 -0
- lefx/engine/layers.py +114 -0
- lefx/engine/library.py +181 -0
- lefx/engine/packages/__init__.py +45 -0
- lefx/engine/packages/loader.py +375 -0
- lefx/engine/packages/manifest.py +308 -0
- lefx/engine/registry.py +347 -0
- lefx/engine/renderer.py +63 -0
- lefx/engine/runtime.py +393 -0
- lefx/engine/store.py +125 -0
- lefx/interfaces/__init__.py +40 -0
- lefx/interfaces/api.py +301 -0
- lefx/interfaces/cli.py +380 -0
- lefx/interfaces/client.py +165 -0
- lefx/interfaces/config.py +305 -0
- lefx/interfaces/discovery.py +308 -0
- lefx/interfaces/hosting.py +123 -0
- lefx/interfaces/paths.py +79 -0
- lefx/interfaces/presentation.py +118 -0
- lefx/interfaces/service.py +468 -0
- lefx/sdk/__init__.py +176 -0
- lefx/sdk/calibration.py +202 -0
- lefx/sdk/color.py +108 -0
- lefx/sdk/context.py +72 -0
- lefx/sdk/definitions.py +526 -0
- lefx/sdk/effects.py +63 -0
- lefx/sdk/errors.py +90 -0
- lefx/sdk/parameters.py +469 -0
- lefx/sdk/ports.py +76 -0
- lefx/sdk/validation.py +150 -0
- lefx/sdk/values.py +212 -0
- lefx/sets/core_set/__init__.py +32 -0
- lefx/sets/core_set/core-set.lefxset +0 -0
- lefx/sets/smartspeaker_set/__init__.py +32 -0
- lefx/sets/smartspeaker_set/smartspeaker-set.lefxset +0 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""What the entry points resolve to.
|
|
2
|
+
|
|
3
|
+
Two factories, one per direction, declared separately in ``pyproject.toml`` as
|
|
4
|
+
``lefx.frame_sinks: respeaker`` and ``lefx.input_providers: respeaker.doa``.
|
|
5
|
+
The service calls whichever it needs and never imports this package by name.
|
|
6
|
+
|
|
7
|
+
Both share a single transport. Output and input are independent objects — the
|
|
8
|
+
point of registering them separately — but there is one USB endpoint, and two
|
|
9
|
+
transports would take turns losing to each other over it.
|
|
10
|
+
|
|
11
|
+
Every factory takes ``**options`` and ignores what it does not know: the service
|
|
12
|
+
passes the same keywords to every installed factory, so tolerating unfamiliar
|
|
13
|
+
ones is part of the contract rather than politeness.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import threading
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from lefx.sdk import FrameSink, InputProvider, resolve_calibration
|
|
22
|
+
|
|
23
|
+
from . import xvf
|
|
24
|
+
from .provider import DEFAULT_MAX_HZ, ReSpeakerDoaProvider
|
|
25
|
+
from .sink import ReSpeakerFrameSink
|
|
26
|
+
from .transport import UsbTransport
|
|
27
|
+
|
|
28
|
+
DEVICE_NAME = "respeaker"
|
|
29
|
+
"""The key this device's calibration is stored under."""
|
|
30
|
+
|
|
31
|
+
_lock = threading.Lock()
|
|
32
|
+
_transport: UsbTransport | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def as_bool(value: Any) -> bool:
|
|
36
|
+
"""Coerce a sink option to a flag.
|
|
37
|
+
|
|
38
|
+
``--sink-option force_claim=true`` arrives as text: the CLI cannot know what
|
|
39
|
+
type a given sink wants for a given option, so the conversion belongs to the
|
|
40
|
+
side that declared the option.
|
|
41
|
+
"""
|
|
42
|
+
if isinstance(value, bool):
|
|
43
|
+
return value
|
|
44
|
+
return str(value).strip().casefold() in {"1", "true", "yes", "on", "ja", "an"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def shared_transport(**options: Any) -> UsbTransport:
|
|
48
|
+
"""The one managed USB connection, created on first use and kept running.
|
|
49
|
+
|
|
50
|
+
``options`` configures the transport the first time only; later callers get
|
|
51
|
+
the connection that already exists rather than a second one configured
|
|
52
|
+
differently.
|
|
53
|
+
"""
|
|
54
|
+
global _transport
|
|
55
|
+
with _lock:
|
|
56
|
+
if _transport is None:
|
|
57
|
+
_transport = UsbTransport(**options)
|
|
58
|
+
transport = _transport
|
|
59
|
+
# Outside the lock: start() takes the transport's own locks, and it also
|
|
60
|
+
# revives a transport that a previous shutdown stopped.
|
|
61
|
+
transport.start()
|
|
62
|
+
return transport
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def reset_shared_transport() -> None:
|
|
66
|
+
"""Drop the shared transport, stopping it first. For tests and restarts."""
|
|
67
|
+
global _transport
|
|
68
|
+
with _lock:
|
|
69
|
+
transport, _transport = _transport, None
|
|
70
|
+
if transport is not None:
|
|
71
|
+
transport.close()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _transport_options(force_claim: Any, claim_unrelated: Any) -> dict[str, Any]:
|
|
75
|
+
"""Only what the caller actually asked for.
|
|
76
|
+
|
|
77
|
+
Force-claiming terminates another program, so it is never inferred from a
|
|
78
|
+
default. It has to be spelled out, every time, by whoever is running this.
|
|
79
|
+
"""
|
|
80
|
+
options: dict[str, Any] = {}
|
|
81
|
+
if force_claim is not None:
|
|
82
|
+
options["force_claim"] = as_bool(force_claim)
|
|
83
|
+
if claim_unrelated is not None:
|
|
84
|
+
options["claim_unrelated"] = as_bool(claim_unrelated)
|
|
85
|
+
return options
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def create_frame_sink(
|
|
89
|
+
*,
|
|
90
|
+
led_count: int = xvf.RING_LED_COUNT,
|
|
91
|
+
force_claim: Any = None,
|
|
92
|
+
claim_unrelated: Any = None,
|
|
93
|
+
**options: Any,
|
|
94
|
+
) -> FrameSink:
|
|
95
|
+
del options
|
|
96
|
+
transport = shared_transport(**_transport_options(force_claim, claim_unrelated))
|
|
97
|
+
return ReSpeakerFrameSink(transport, led_count=led_count)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def create_doa_provider(
|
|
101
|
+
*,
|
|
102
|
+
max_hz: float = DEFAULT_MAX_HZ,
|
|
103
|
+
force_claim: Any = None,
|
|
104
|
+
claim_unrelated: Any = None,
|
|
105
|
+
angle_offset_deg: Any = None,
|
|
106
|
+
reverse: Any = None,
|
|
107
|
+
calibration_file: Any = None,
|
|
108
|
+
**options: Any,
|
|
109
|
+
) -> InputProvider:
|
|
110
|
+
del options
|
|
111
|
+
transport = shared_transport(**_transport_options(force_claim, claim_unrelated))
|
|
112
|
+
return ReSpeakerDoaProvider(
|
|
113
|
+
transport,
|
|
114
|
+
max_hz=max_hz,
|
|
115
|
+
calibration=resolve_calibration(
|
|
116
|
+
DEVICE_NAME,
|
|
117
|
+
angle_offset_deg=angle_offset_deg,
|
|
118
|
+
reverse=reverse,
|
|
119
|
+
path=calibration_file,
|
|
120
|
+
),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
__all__ = [
|
|
125
|
+
"DEVICE_NAME",
|
|
126
|
+
"create_doa_provider",
|
|
127
|
+
"create_frame_sink",
|
|
128
|
+
"reset_shared_transport",
|
|
129
|
+
"shared_transport",
|
|
130
|
+
]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""The LED output half of the device.
|
|
2
|
+
|
|
3
|
+
Writes composed frames to the ring and reports whether it can. It never raises
|
|
4
|
+
at the port: a frame arrives thirty times a second, and a cable pulled between
|
|
5
|
+
two of them is an ordinary condition, not an exception the render loop should
|
|
6
|
+
have to catch. What went wrong is answered by :meth:`ReSpeakerFrameSink.status`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
|
|
13
|
+
from lefx.sdk import OutputFrame, SinkStatus
|
|
14
|
+
|
|
15
|
+
from . import xvf
|
|
16
|
+
from .transport import UsbTransport
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger("lefx.device.respeaker.sink")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ReSpeakerFrameSink:
|
|
22
|
+
"""Puts a frame on the reSpeaker's LED ring."""
|
|
23
|
+
|
|
24
|
+
name = "respeaker"
|
|
25
|
+
|
|
26
|
+
def __init__(self, transport: UsbTransport, *, led_count: int = xvf.RING_LED_COUNT) -> None:
|
|
27
|
+
self.transport = transport
|
|
28
|
+
self.led_count = int(led_count)
|
|
29
|
+
self._ring_mode = False
|
|
30
|
+
self._last_leds: tuple[int, ...] | None = None
|
|
31
|
+
self._write_error: str | None = None
|
|
32
|
+
self._closed = False
|
|
33
|
+
|
|
34
|
+
# Configuration disagreeing with the hardware is a standing fault, not a
|
|
35
|
+
# transient one: it is reported for as long as it holds, rather than
|
|
36
|
+
# letting every single frame fail the firmware's length check.
|
|
37
|
+
self._config_error: str | None = None
|
|
38
|
+
if self.led_count != xvf.RING_LED_COUNT:
|
|
39
|
+
self._config_error = (
|
|
40
|
+
f"configured for {self.led_count} LEDs, but this device's ring "
|
|
41
|
+
f"carries {xvf.RING_LED_COUNT}"
|
|
42
|
+
)
|
|
43
|
+
logger.error("%s", self._config_error)
|
|
44
|
+
|
|
45
|
+
def apply_frame(self, frame: OutputFrame) -> None:
|
|
46
|
+
leds = tuple(frame.leds)
|
|
47
|
+
if len(leds) != xvf.RING_LED_COUNT:
|
|
48
|
+
self._write_error = (
|
|
49
|
+
f"frame has {len(leds)} LEDs, the ring takes {xvf.RING_LED_COUNT}"
|
|
50
|
+
)
|
|
51
|
+
return
|
|
52
|
+
if not self.transport.is_connected:
|
|
53
|
+
# The transport owns the explanation while the cable is out, so a
|
|
54
|
+
# stale write error would only obscure it. The next connected frame
|
|
55
|
+
# starts from a clean slate.
|
|
56
|
+
self._forget()
|
|
57
|
+
self._write_error = None
|
|
58
|
+
return
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
# A reconnected device has forgotten the ring mode along with
|
|
62
|
+
# everything else, so re-assert it whenever the handle is new.
|
|
63
|
+
# Read unconditionally: folding this into the condition below would
|
|
64
|
+
# let short-circuiting skip the read on the very frame that sets the
|
|
65
|
+
# mode, leaving the flag to fire again on the next one.
|
|
66
|
+
new_session = self.transport.consume_session_dirty()
|
|
67
|
+
if new_session or not self._ring_mode:
|
|
68
|
+
self.transport.write("LED_EFFECT", [xvf.LED_EFFECT_RING_MODE])
|
|
69
|
+
self._ring_mode = True
|
|
70
|
+
self._last_leds = None
|
|
71
|
+
if leds != self._last_leds:
|
|
72
|
+
# USB writes are the expensive part of a frame. A ring that did
|
|
73
|
+
# not change does not need to be sent again.
|
|
74
|
+
self.transport.write("LED_RING_COLOR", list(leds))
|
|
75
|
+
self._last_leds = leds
|
|
76
|
+
self._write_error = None
|
|
77
|
+
except Exception as exc:
|
|
78
|
+
self._forget()
|
|
79
|
+
self._write_error = str(exc)
|
|
80
|
+
logger.debug("frame not delivered: %s", exc)
|
|
81
|
+
|
|
82
|
+
def status(self) -> SinkStatus:
|
|
83
|
+
if self._closed:
|
|
84
|
+
return SinkStatus(available=False, detail="sink closed")
|
|
85
|
+
if self._config_error is not None:
|
|
86
|
+
return SinkStatus(available=False, detail=self._config_error)
|
|
87
|
+
if not self.transport.is_connected:
|
|
88
|
+
detail = self.transport.last_error or "reSpeaker not connected"
|
|
89
|
+
return SinkStatus(available=False, detail=detail)
|
|
90
|
+
if self._write_error is not None:
|
|
91
|
+
return SinkStatus(available=False, detail=self._write_error)
|
|
92
|
+
return SinkStatus(available=True, detail=None)
|
|
93
|
+
|
|
94
|
+
def close(self) -> None:
|
|
95
|
+
"""Idempotent — shutdown paths overlap, and closing twice is not a fault."""
|
|
96
|
+
if self._closed:
|
|
97
|
+
return
|
|
98
|
+
self._closed = True
|
|
99
|
+
self._forget()
|
|
100
|
+
self.transport.close()
|
|
101
|
+
|
|
102
|
+
def _forget(self) -> None:
|
|
103
|
+
"""Drop what we believe about the device, so nothing is skipped later."""
|
|
104
|
+
self._ring_mode = False
|
|
105
|
+
self._last_leds = None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
__all__ = ["ReSpeakerFrameSink"]
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""The USB connection to the device: discovery, reconnection and locked I/O.
|
|
2
|
+
|
|
3
|
+
One transport serves both directions. The frame sink and the DoA provider are
|
|
4
|
+
separate objects — a failing read must not take the LED output down — but they
|
|
5
|
+
share this, because two objects opening the same USB endpoint would fight over
|
|
6
|
+
it.
|
|
7
|
+
|
|
8
|
+
The connection is *managed*, not merely opened: a background thread reconnects
|
|
9
|
+
after an unplug and proves a live connection with a periodic ``VERSION`` read.
|
|
10
|
+
Callers therefore never handle "is the cable in" themselves; they read
|
|
11
|
+
:attr:`is_connected` and get on with it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import enum
|
|
17
|
+
import logging
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
from typing import Any, Callable
|
|
21
|
+
|
|
22
|
+
import usb.util
|
|
23
|
+
|
|
24
|
+
from . import xvf
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("lefx.device.respeaker.transport")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConnectionState(enum.Enum):
|
|
30
|
+
DISCONNECTED = "disconnected"
|
|
31
|
+
CONNECTING = "connecting"
|
|
32
|
+
CONNECTED = "connected"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class UsbTransport:
|
|
36
|
+
"""Keeps a reSpeaker reachable, and serialises access to it."""
|
|
37
|
+
|
|
38
|
+
probe_command = "VERSION"
|
|
39
|
+
"""Read to prove a link is real — on connecting, and as the heartbeat.
|
|
40
|
+
|
|
41
|
+
Read-only and cheap, so asking repeatedly costs nothing and changes nothing.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
retry_interval_s: float = 3.0,
|
|
48
|
+
heartbeat_interval_s: float = 2.0,
|
|
49
|
+
on_connected: Callable[[], None] | None = None,
|
|
50
|
+
on_disconnected: Callable[[str], None] | None = None,
|
|
51
|
+
finder: Callable[[], Any] | None = None,
|
|
52
|
+
force_claim: bool = False,
|
|
53
|
+
claim_unrelated: bool = False,
|
|
54
|
+
) -> None:
|
|
55
|
+
self.retry_interval_s = retry_interval_s
|
|
56
|
+
self.heartbeat_interval_s = heartbeat_interval_s
|
|
57
|
+
self.on_connected = on_connected
|
|
58
|
+
self.on_disconnected = on_disconnected
|
|
59
|
+
self.force_claim = force_claim
|
|
60
|
+
self.claim_unrelated = claim_unrelated
|
|
61
|
+
# Injectable so the reconnect and heartbeat logic can be exercised
|
|
62
|
+
# without a device on the bus. Defaults to the real one.
|
|
63
|
+
self._finder = finder if finder is not None else xvf.find
|
|
64
|
+
|
|
65
|
+
self._state = ConnectionState.DISCONNECTED
|
|
66
|
+
self._device: Any | None = None
|
|
67
|
+
|
|
68
|
+
self._io_lock = threading.RLock()
|
|
69
|
+
self._state_lock = threading.RLock()
|
|
70
|
+
self._stop = threading.Event()
|
|
71
|
+
self._monitor: threading.Thread | None = None
|
|
72
|
+
|
|
73
|
+
# Set whenever a fresh device appears, so whoever configures the device
|
|
74
|
+
# on connect knows its settings were lost with the old handle.
|
|
75
|
+
self._session_dirty = True
|
|
76
|
+
|
|
77
|
+
# Force-claiming is allowed once per connection cycle, not once per
|
|
78
|
+
# retry. The retry loop runs every few seconds forever; a transport that
|
|
79
|
+
# terminated processes on that schedule would be a menace. Cleared again
|
|
80
|
+
# on a successful connect, so a device lost and re-taken later can still
|
|
81
|
+
# be fought for once more.
|
|
82
|
+
self._claim_spent = False
|
|
83
|
+
self._last_claim: Any | None = None
|
|
84
|
+
|
|
85
|
+
self._connect_count = 0
|
|
86
|
+
self._disconnect_count = 0
|
|
87
|
+
self._last_connected_at: float | None = None
|
|
88
|
+
self._last_error: str | None = None
|
|
89
|
+
self._retry_count = 0
|
|
90
|
+
|
|
91
|
+
# -- state --------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def state(self) -> ConnectionState:
|
|
95
|
+
with self._state_lock:
|
|
96
|
+
return self._state
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def is_connected(self) -> bool:
|
|
100
|
+
return self.state is ConnectionState.CONNECTED
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def last_error(self) -> str | None:
|
|
104
|
+
with self._state_lock:
|
|
105
|
+
return self._last_error
|
|
106
|
+
|
|
107
|
+
def stats(self) -> dict[str, Any]:
|
|
108
|
+
with self._state_lock:
|
|
109
|
+
return {
|
|
110
|
+
"state": self._state.value,
|
|
111
|
+
"connect_count": self._connect_count,
|
|
112
|
+
"disconnect_count": self._disconnect_count,
|
|
113
|
+
"last_connected_at": self._last_connected_at,
|
|
114
|
+
"last_error": self._last_error,
|
|
115
|
+
"retry_count": self._retry_count,
|
|
116
|
+
"force_claim": self.force_claim,
|
|
117
|
+
"last_claim": None if self._last_claim is None else self._last_claim.summary(),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
def consume_session_dirty(self) -> bool:
|
|
121
|
+
"""Report — once — that the device handle was replaced since last asked.
|
|
122
|
+
|
|
123
|
+
A reconnected device has forgotten everything that was written to it, so
|
|
124
|
+
the sink uses this to re-send its mode instead of assuming the ring is
|
|
125
|
+
still where it left it.
|
|
126
|
+
"""
|
|
127
|
+
with self._state_lock:
|
|
128
|
+
dirty = self._session_dirty
|
|
129
|
+
self._session_dirty = False
|
|
130
|
+
return dirty
|
|
131
|
+
|
|
132
|
+
# -- lifecycle ----------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
def start(self) -> None:
|
|
135
|
+
with self._state_lock:
|
|
136
|
+
if self._monitor is not None and self._monitor.is_alive():
|
|
137
|
+
return
|
|
138
|
+
self._stop.clear()
|
|
139
|
+
self._monitor = threading.Thread(
|
|
140
|
+
target=self._run, name="respeaker-usb-monitor", daemon=True
|
|
141
|
+
)
|
|
142
|
+
self._monitor.start()
|
|
143
|
+
|
|
144
|
+
def stop(self) -> None:
|
|
145
|
+
self._stop.set()
|
|
146
|
+
monitor = self._monitor
|
|
147
|
+
if monitor is not None:
|
|
148
|
+
monitor.join(timeout=self.retry_interval_s + 1.0)
|
|
149
|
+
self._monitor = None
|
|
150
|
+
self._disconnect("transport stopped")
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
"""Idempotent. Stopping an already stopped transport is not an error."""
|
|
154
|
+
self.stop()
|
|
155
|
+
|
|
156
|
+
def __enter__(self) -> "UsbTransport":
|
|
157
|
+
self.start()
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
def __exit__(self, *exc: object) -> None:
|
|
161
|
+
self.stop()
|
|
162
|
+
|
|
163
|
+
# -- I/O ----------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def write(self, name: str, data: list) -> None:
|
|
166
|
+
with self._io_lock:
|
|
167
|
+
device = self._require_device()
|
|
168
|
+
try:
|
|
169
|
+
device.write(name, data)
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
self._disconnect(f"write {name} failed: {exc}")
|
|
172
|
+
raise
|
|
173
|
+
|
|
174
|
+
def read(self, name: str) -> tuple:
|
|
175
|
+
with self._io_lock:
|
|
176
|
+
device = self._require_device()
|
|
177
|
+
try:
|
|
178
|
+
return device.read(name)
|
|
179
|
+
except Exception as exc:
|
|
180
|
+
self._disconnect(f"read {name} failed: {exc}")
|
|
181
|
+
raise
|
|
182
|
+
|
|
183
|
+
def _require_device(self) -> Any:
|
|
184
|
+
if not self.is_connected or self._device is None:
|
|
185
|
+
raise ConnectionError("reSpeaker is not connected")
|
|
186
|
+
return self._device
|
|
187
|
+
|
|
188
|
+
# -- the monitor thread -------------------------------------------------
|
|
189
|
+
|
|
190
|
+
def _run(self) -> None:
|
|
191
|
+
while not self._stop.is_set():
|
|
192
|
+
if self.state is ConnectionState.CONNECTED:
|
|
193
|
+
if self._heartbeat() and self._stop.wait(self.heartbeat_interval_s):
|
|
194
|
+
break
|
|
195
|
+
continue
|
|
196
|
+
if self._try_connect():
|
|
197
|
+
if self._stop.wait(self.heartbeat_interval_s):
|
|
198
|
+
break
|
|
199
|
+
elif self._stop.wait(self.retry_interval_s):
|
|
200
|
+
break
|
|
201
|
+
|
|
202
|
+
def _try_connect(self) -> bool:
|
|
203
|
+
with self._state_lock:
|
|
204
|
+
self._state = ConnectionState.CONNECTING
|
|
205
|
+
self._retry_count += 1
|
|
206
|
+
|
|
207
|
+
try:
|
|
208
|
+
with self._io_lock:
|
|
209
|
+
device = self._finder()
|
|
210
|
+
if device is not None:
|
|
211
|
+
# Enumerating a device is not the same as being able to use
|
|
212
|
+
# it: on Windows a reSpeaker bound to the wrong driver shows
|
|
213
|
+
# up on the bus and refuses every transfer. Proving the link
|
|
214
|
+
# here keeps is_connected meaning "reachable" rather than
|
|
215
|
+
# "listed", so the sink reports the problem instead of
|
|
216
|
+
# discovering it one frame at a time.
|
|
217
|
+
device.read(self.probe_command)
|
|
218
|
+
self._device = device
|
|
219
|
+
with self._state_lock:
|
|
220
|
+
self._state = ConnectionState.CONNECTED
|
|
221
|
+
self._connect_count += 1
|
|
222
|
+
self._last_connected_at = time.time()
|
|
223
|
+
self._retry_count = 0
|
|
224
|
+
self._session_dirty = True
|
|
225
|
+
self._last_error = None
|
|
226
|
+
self._claim_spent = False
|
|
227
|
+
logger.info("reSpeaker connected")
|
|
228
|
+
self._notify(self.on_connected, "on_connected")
|
|
229
|
+
return True
|
|
230
|
+
except Exception as exc:
|
|
231
|
+
# No device on the bus is the normal case while nothing is plugged
|
|
232
|
+
# in; it is not worth a warning on every retry.
|
|
233
|
+
logger.debug("connection attempt failed: %s", exc)
|
|
234
|
+
with self._state_lock:
|
|
235
|
+
self._last_error = str(exc)
|
|
236
|
+
if self._should_claim(exc):
|
|
237
|
+
return self._claim_and_retry()
|
|
238
|
+
|
|
239
|
+
with self._state_lock:
|
|
240
|
+
self._state = ConnectionState.DISCONNECTED
|
|
241
|
+
return False
|
|
242
|
+
|
|
243
|
+
def _should_claim(self, exc: Exception) -> bool:
|
|
244
|
+
"""Whether this failure is the kind another process could be causing.
|
|
245
|
+
|
|
246
|
+
A device that is simply absent is not contended, and running a process
|
|
247
|
+
hunt for it would be noise. The signature that matters is access being
|
|
248
|
+
denied to a device that *is* on the bus.
|
|
249
|
+
"""
|
|
250
|
+
if not self.force_claim:
|
|
251
|
+
return False
|
|
252
|
+
with self._state_lock:
|
|
253
|
+
if self._claim_spent:
|
|
254
|
+
return False
|
|
255
|
+
text = str(exc).casefold()
|
|
256
|
+
return "access" in text or "errno 13" in text or "permission" in text
|
|
257
|
+
|
|
258
|
+
def _claim_and_retry(self) -> bool:
|
|
259
|
+
"""Try to take the device from whatever is holding it, then reconnect.
|
|
260
|
+
|
|
261
|
+
Only reached when force-claiming was asked for explicitly. It runs at
|
|
262
|
+
most once between successful connections.
|
|
263
|
+
"""
|
|
264
|
+
from . import contention
|
|
265
|
+
|
|
266
|
+
with self._state_lock:
|
|
267
|
+
self._claim_spent = True
|
|
268
|
+
|
|
269
|
+
logger.warning("the reSpeaker is held by another process; force claim was requested")
|
|
270
|
+
try:
|
|
271
|
+
report = contention.release_device(
|
|
272
|
+
contention.device_probe(), only_related=not self.claim_unrelated
|
|
273
|
+
)
|
|
274
|
+
except Exception as exc:
|
|
275
|
+
logger.warning("force claim failed: %s", exc)
|
|
276
|
+
with self._state_lock:
|
|
277
|
+
self._state = ConnectionState.DISCONNECTED
|
|
278
|
+
return False
|
|
279
|
+
|
|
280
|
+
self._last_claim = report
|
|
281
|
+
logger.warning("force claim: %s", report.summary())
|
|
282
|
+
if not report.reachable_after:
|
|
283
|
+
with self._state_lock:
|
|
284
|
+
self._state = ConnectionState.DISCONNECTED
|
|
285
|
+
self._last_error = report.note or report.summary()
|
|
286
|
+
return False
|
|
287
|
+
# The device answers now, so an ordinary connection attempt will work.
|
|
288
|
+
# Recursion is bounded: _claim_spent is set above, so the retry cannot
|
|
289
|
+
# come back here.
|
|
290
|
+
return self._try_connect()
|
|
291
|
+
|
|
292
|
+
def _heartbeat(self) -> bool:
|
|
293
|
+
"""Prove the handle still works. A dead cable often reads fine until asked."""
|
|
294
|
+
try:
|
|
295
|
+
self.read(self.probe_command)
|
|
296
|
+
return True
|
|
297
|
+
except Exception as exc:
|
|
298
|
+
logger.warning("heartbeat failed: %s", exc)
|
|
299
|
+
return False
|
|
300
|
+
|
|
301
|
+
def _disconnect(self, reason: str) -> None:
|
|
302
|
+
with self._state_lock:
|
|
303
|
+
if self._state is ConnectionState.DISCONNECTED:
|
|
304
|
+
return
|
|
305
|
+
logger.warning("reSpeaker disconnected: %s", reason)
|
|
306
|
+
self._state = ConnectionState.DISCONNECTED
|
|
307
|
+
self._disconnect_count += 1
|
|
308
|
+
self._last_error = reason
|
|
309
|
+
self._session_dirty = True
|
|
310
|
+
|
|
311
|
+
with self._io_lock:
|
|
312
|
+
device = self._device
|
|
313
|
+
self._device = None
|
|
314
|
+
if device is not None:
|
|
315
|
+
try:
|
|
316
|
+
handle = getattr(device, "dev", None)
|
|
317
|
+
if handle is not None:
|
|
318
|
+
usb.util.dispose_resources(handle)
|
|
319
|
+
except Exception as exc:
|
|
320
|
+
logger.debug("could not dispose USB resources: %s", exc)
|
|
321
|
+
|
|
322
|
+
self._notify(self.on_disconnected, "on_disconnected", reason)
|
|
323
|
+
|
|
324
|
+
def _notify(self, callback: Callable[..., None] | None, label: str, *args: Any) -> None:
|
|
325
|
+
"""Run a lifecycle callback off the caller's thread.
|
|
326
|
+
|
|
327
|
+
Both ``_try_connect`` and the read/write error paths hold ``_io_lock``
|
|
328
|
+
when a transition happens. Calling a listener inline would let one that
|
|
329
|
+
takes its own lock deadlock against a render thread holding that lock
|
|
330
|
+
and waiting for ``_io_lock``, so callbacks never inherit our locks.
|
|
331
|
+
"""
|
|
332
|
+
if callback is None:
|
|
333
|
+
return
|
|
334
|
+
|
|
335
|
+
def run() -> None:
|
|
336
|
+
try:
|
|
337
|
+
callback(*args)
|
|
338
|
+
except Exception:
|
|
339
|
+
logger.exception("%s callback failed", label)
|
|
340
|
+
|
|
341
|
+
threading.Thread(target=run, name=f"respeaker-{label}", daemon=True).start()
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
__all__ = ["ConnectionState", "UsbTransport"]
|