led-controller-version-3-device-simulated-respeaker 3.0.2__tar.gz
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/.gitignore +11 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/PKG-INFO +86 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/README.md +70 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/pyproject.toml +49 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/__init__.py +31 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/__main__.py +15 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/app.py +69 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/client.py +203 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/link.py +337 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/protocol.py +164 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/provider.py +159 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/registration.py +113 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/ring.py +105 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/sink.py +69 -0
- led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/window.py +168 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Becomes .gitignore in the release repository.
|
|
2
|
+
#
|
|
3
|
+
# Short on purpose. This tree is generated, and the one thing that has to be
|
|
4
|
+
# tracked here and is *not* tracked in the development repository is the built
|
|
5
|
+
# .lefxset catalogue — output there, source here.
|
|
6
|
+
__pycache__/
|
|
7
|
+
*.pyc
|
|
8
|
+
.venv/
|
|
9
|
+
build/
|
|
10
|
+
dist/
|
|
11
|
+
*.egg-info/
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: led-controller-version-3-device-simulated-respeaker
|
|
3
|
+
Version: 3.0.2
|
|
4
|
+
Summary: Software device double for the LED ring: frame sink, simulated DoA input and a visual ring window
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Keywords: led,preview,respeaker,simulator
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Requires-Python: <3.13,>=3.12
|
|
12
|
+
Requires-Dist: led-controller-version-3==3.0.2
|
|
13
|
+
Provides-Extra: gui
|
|
14
|
+
Requires-Dist: pyside6>=6.0.0; extra == 'gui'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# led-controller-version-3-device-simulated-respeaker
|
|
18
|
+
|
|
19
|
+
Ein vollständiger Software-Ersatz für die Hardware — dieselben Ports, dieselbe
|
|
20
|
+
Rolle. Der Dienst merkt nicht, dass die Gegenstelle kein Gerät ist.
|
|
21
|
+
|
|
22
|
+
Es enthält:
|
|
23
|
+
|
|
24
|
+
- `SimulatorFrameSink` — überträgt den LED-Frame über einen lokalen Transport,
|
|
25
|
+
- `SimulatorDoaProvider` — liest die im Fenster eingestellte Richtung und
|
|
26
|
+
Sprachaktivität zurück,
|
|
27
|
+
- die Ringanzeige als eigenständige Anwendung.
|
|
28
|
+
|
|
29
|
+
Die dienstseitige Hälfte braucht kein Qt. PySide6 ist ein Extra und wird nur
|
|
30
|
+
gebraucht, wenn das Fenster geöffnet wird:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
uv pip install "led-controller-version-3-device-simulated-respeaker[gui]"
|
|
34
|
+
lefx-simulator
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Ohne installiertes Konsolenskript geht es als Modul. `app.py` direkt als Datei
|
|
38
|
+
zu starten geht **nicht** — die Datei erreicht ihre Nachbarmodule über relative
|
|
39
|
+
Importe, und eine über den Pfad gestartete Datei hat kein Paket, relativ zu dem
|
|
40
|
+
das ginge:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
uv run python -m lefx.device.simulated_respeaker
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Als Exe
|
|
47
|
+
|
|
48
|
+
Für eine Maschine ohne Python-Checkout, oder um das Fenster offen zu lassen,
|
|
49
|
+
während am Checkout gearbeitet wird:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
uv sync --group build
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
uv run --group build python scripts/build_simulator.py
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Ergebnis ist `build/dist/lefx-simulator.exe` (~47 MB, eine Datei).
|
|
60
|
+
`--onedir` startet schneller, `--windowed` verbirgt die Konsole — dann sieht man
|
|
61
|
+
allerdings auch nicht mehr, wenn der Dienst nicht erreichbar ist.
|
|
62
|
+
|
|
63
|
+
Damit lassen sich auch kontrollierte Overlays wie `direction_indicator` ohne
|
|
64
|
+
angeschlossenen reSpeaker entwickeln und prüfen — der Effekt fragt nach der
|
|
65
|
+
Fähigkeit `doa` und bekommt sie hier ebenso wie von der Hardware.
|
|
66
|
+
|
|
67
|
+
## Transport
|
|
68
|
+
|
|
69
|
+
Der Dienst hört auf `127.0.0.1:8787`, das Fenster verbindet sich dorthin.
|
|
70
|
+
Diese Richtung entspricht der Hardware: der Dienst läuft, ob ein Gerät
|
|
71
|
+
angeschlossen ist oder nicht, und ein später erscheinendes Fenster ist ein
|
|
72
|
+
gewöhnliches Ereignis, kein Neustart. Das Fenster verbindet sich selbsttätig neu.
|
|
73
|
+
|
|
74
|
+
Der Port lässt sich auf beiden Seiten setzen:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
uv run lefx serve --sink simulator --sink-option port=8770
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Alternativ über `LEFX_SIMULATOR_PORT`, das beide Hälften lesen.
|
|
81
|
+
|
|
82
|
+
## Grenzen
|
|
83
|
+
|
|
84
|
+
Ohne verbundenes Fenster meldet die Senke `available=False` und der Provider
|
|
85
|
+
liefert `None` — dieselbe Bedeutung wie ein abgezogenes Kabel. Der Dienst läuft
|
|
86
|
+
weiter, kontrollierte Overlays gehen über `waiting` nach `failed`.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# led-controller-version-3-device-simulated-respeaker
|
|
2
|
+
|
|
3
|
+
Ein vollständiger Software-Ersatz für die Hardware — dieselben Ports, dieselbe
|
|
4
|
+
Rolle. Der Dienst merkt nicht, dass die Gegenstelle kein Gerät ist.
|
|
5
|
+
|
|
6
|
+
Es enthält:
|
|
7
|
+
|
|
8
|
+
- `SimulatorFrameSink` — überträgt den LED-Frame über einen lokalen Transport,
|
|
9
|
+
- `SimulatorDoaProvider` — liest die im Fenster eingestellte Richtung und
|
|
10
|
+
Sprachaktivität zurück,
|
|
11
|
+
- die Ringanzeige als eigenständige Anwendung.
|
|
12
|
+
|
|
13
|
+
Die dienstseitige Hälfte braucht kein Qt. PySide6 ist ein Extra und wird nur
|
|
14
|
+
gebraucht, wenn das Fenster geöffnet wird:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
uv pip install "led-controller-version-3-device-simulated-respeaker[gui]"
|
|
18
|
+
lefx-simulator
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Ohne installiertes Konsolenskript geht es als Modul. `app.py` direkt als Datei
|
|
22
|
+
zu starten geht **nicht** — die Datei erreicht ihre Nachbarmodule über relative
|
|
23
|
+
Importe, und eine über den Pfad gestartete Datei hat kein Paket, relativ zu dem
|
|
24
|
+
das ginge:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
uv run python -m lefx.device.simulated_respeaker
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Als Exe
|
|
31
|
+
|
|
32
|
+
Für eine Maschine ohne Python-Checkout, oder um das Fenster offen zu lassen,
|
|
33
|
+
während am Checkout gearbeitet wird:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uv sync --group build
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
uv run --group build python scripts/build_simulator.py
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Ergebnis ist `build/dist/lefx-simulator.exe` (~47 MB, eine Datei).
|
|
44
|
+
`--onedir` startet schneller, `--windowed` verbirgt die Konsole — dann sieht man
|
|
45
|
+
allerdings auch nicht mehr, wenn der Dienst nicht erreichbar ist.
|
|
46
|
+
|
|
47
|
+
Damit lassen sich auch kontrollierte Overlays wie `direction_indicator` ohne
|
|
48
|
+
angeschlossenen reSpeaker entwickeln und prüfen — der Effekt fragt nach der
|
|
49
|
+
Fähigkeit `doa` und bekommt sie hier ebenso wie von der Hardware.
|
|
50
|
+
|
|
51
|
+
## Transport
|
|
52
|
+
|
|
53
|
+
Der Dienst hört auf `127.0.0.1:8787`, das Fenster verbindet sich dorthin.
|
|
54
|
+
Diese Richtung entspricht der Hardware: der Dienst läuft, ob ein Gerät
|
|
55
|
+
angeschlossen ist oder nicht, und ein später erscheinendes Fenster ist ein
|
|
56
|
+
gewöhnliches Ereignis, kein Neustart. Das Fenster verbindet sich selbsttätig neu.
|
|
57
|
+
|
|
58
|
+
Der Port lässt sich auf beiden Seiten setzen:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
uv run lefx serve --sink simulator --sink-option port=8770
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Alternativ über `LEFX_SIMULATOR_PORT`, das beide Hälften lesen.
|
|
65
|
+
|
|
66
|
+
## Grenzen
|
|
67
|
+
|
|
68
|
+
Ohne verbundenes Fenster meldet die Senke `available=False` und der Provider
|
|
69
|
+
liefert `None` — dieselbe Bedeutung wie ein abgezogenes Kabel. Der Dienst läuft
|
|
70
|
+
weiter, kontrollierte Overlays gehen über `waiting` nach `failed`.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27.0"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "led-controller-version-3-device-simulated-respeaker"
|
|
7
|
+
version = "3.0.2"
|
|
8
|
+
description = "Software device double for the LED ring: frame sink, simulated DoA input and a visual ring window"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.12,<3.13"
|
|
12
|
+
keywords = ["respeaker", "led", "simulator", "preview"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
# The service-side half — sink, provider and transport client — carries no GUI
|
|
21
|
+
# dependency. Only the person who opens the ring window needs Qt, so PySide6 is
|
|
22
|
+
# an extra rather than a hard requirement.
|
|
23
|
+
dependencies = [
|
|
24
|
+
# Only for the ports in lefx.sdk. That the schema now ships inside the
|
|
25
|
+
# runtime distribution does not license reaching into the rest of it: the
|
|
26
|
+
# architecture test holds this package to lefx.sdk and nothing else, which
|
|
27
|
+
# is what keeps it swappable with the hardware.
|
|
28
|
+
"led-controller-version-3==3.0.2",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
gui = [
|
|
33
|
+
"PySide6>=6.0.0",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.scripts]
|
|
37
|
+
lefx-simulator = "lefx.device.simulated_respeaker.app:main"
|
|
38
|
+
|
|
39
|
+
# A provider is named "<device>.<capability>". Registering the capability alone
|
|
40
|
+
# would collide with the hardware's the moment both packages are installed;
|
|
41
|
+
# naming the device keeps them apart while an effect still asks only for "doa".
|
|
42
|
+
[project.entry-points."lefx.frame_sinks"]
|
|
43
|
+
simulator = "lefx.device.simulated_respeaker.registration:create_frame_sink"
|
|
44
|
+
|
|
45
|
+
[project.entry-points."lefx.input_providers"]
|
|
46
|
+
"simulator.doa" = "lefx.device.simulated_respeaker.registration:create_doa_provider"
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/lefx"]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Software device double — frame sink, simulated DoA input and ring window.
|
|
2
|
+
|
|
3
|
+
Depends on ``lefx.sdk`` and nothing else from the system, exactly as the hardware
|
|
4
|
+
package does. It is a device, not a preview: it fills the same ports, reports
|
|
5
|
+
direction in the same shape and range, and passes the same conformance suite.
|
|
6
|
+
|
|
7
|
+
Only the names exported here are service-side and free of Qt. The ring window
|
|
8
|
+
lives in :mod:`lefx.device.simulated_respeaker.window` and is reached through the
|
|
9
|
+
``lefx-simulator`` console script.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from .link import SimulatorLink, default_port
|
|
15
|
+
from .provider import DETECTION_STATES, SimulatorDoaProvider
|
|
16
|
+
from .registration import create_doa_provider, create_frame_sink, shared_link
|
|
17
|
+
from .sink import SimulatorFrameSink
|
|
18
|
+
|
|
19
|
+
__version__ = "3.0.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"DETECTION_STATES",
|
|
23
|
+
"SimulatorDoaProvider",
|
|
24
|
+
"SimulatorFrameSink",
|
|
25
|
+
"SimulatorLink",
|
|
26
|
+
"__version__",
|
|
27
|
+
"create_doa_provider",
|
|
28
|
+
"create_frame_sink",
|
|
29
|
+
"default_port",
|
|
30
|
+
"shared_link",
|
|
31
|
+
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Makes ``python -m lefx.device.simulated_respeaker`` work.
|
|
2
|
+
|
|
3
|
+
Running ``app.py`` as a plain file cannot work: the module reaches its siblings
|
|
4
|
+
with relative imports, and a file executed by path has no package to be relative
|
|
5
|
+
to. Running it as a module gives it one — so this is the form to reach for when
|
|
6
|
+
the console script is not on PATH, which is most of the time during development.
|
|
7
|
+
|
|
8
|
+
python -m lefx.device.simulated_respeaker --port 8787
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from .app import main
|
|
14
|
+
|
|
15
|
+
raise SystemExit(main())
|
led_controller_version_3_device_simulated_respeaker-3.0.2/src/lefx/device/simulated_respeaker/app.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""The ``lefx-simulator`` console script.
|
|
2
|
+
|
|
3
|
+
Qt is imported here and only here, behind a check that turns a missing optional
|
|
4
|
+
dependency into a sentence instead of a traceback. That is what keeps the extra
|
|
5
|
+
honest: the service half of this package is installed without PySide6, and
|
|
6
|
+
nothing it imports leads to this module.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import logging
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from . import protocol
|
|
16
|
+
from .link import default_port
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
prog="lefx-simulator",
|
|
22
|
+
description="Open the ring window and connect it to a running lefx service.",
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument("--host", default=protocol.DEFAULT_HOST)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--port",
|
|
27
|
+
type=int,
|
|
28
|
+
default=None,
|
|
29
|
+
help=f"Service simulator port (default: ${protocol.PORT_ENV_VAR} or {protocol.DEFAULT_PORT})",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--led-count",
|
|
33
|
+
type=int,
|
|
34
|
+
default=12,
|
|
35
|
+
help="Ring size to draw until the service announces its own",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument("--verbose", action="store_true")
|
|
38
|
+
return parser
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def main(argv: list[str] | None = None) -> int:
|
|
42
|
+
args = build_parser().parse_args(argv)
|
|
43
|
+
logging.basicConfig(
|
|
44
|
+
level=logging.DEBUG if args.verbose else logging.INFO,
|
|
45
|
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
from PySide6.QtWidgets import QApplication
|
|
50
|
+
except ImportError:
|
|
51
|
+
print(
|
|
52
|
+
"The ring window needs PySide6, which is an optional extra:\n"
|
|
53
|
+
' uv pip install "led-controller-version-3-device-simulated-respeaker[gui]"\n'
|
|
54
|
+
"The service half of the simulator works without it.",
|
|
55
|
+
file=sys.stderr,
|
|
56
|
+
)
|
|
57
|
+
return 2
|
|
58
|
+
|
|
59
|
+
from .window import SimulatorWindow
|
|
60
|
+
|
|
61
|
+
port = default_port() if args.port is None else args.port
|
|
62
|
+
application = QApplication(sys.argv[:1])
|
|
63
|
+
window = SimulatorWindow(host=args.host, port=port, led_count=args.led_count)
|
|
64
|
+
window.show()
|
|
65
|
+
return int(application.exec())
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__": # pragma: no cover
|
|
69
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""The window-side half of the transport, without any window.
|
|
2
|
+
|
|
3
|
+
Kept apart from the Qt code so the connection can be tested headlessly, and so
|
|
4
|
+
the ring window contains drawing and controls rather than sockets. It dials the
|
|
5
|
+
service, reconnects when the service is not up yet or goes away, reports frames
|
|
6
|
+
through a callback and sends the current control values back.
|
|
7
|
+
|
|
8
|
+
Reconnection matters more here than it might look: the natural way to work is to
|
|
9
|
+
leave the window open and restart the service, and a window that had to be
|
|
10
|
+
reopened each time would be a worse device than a cable.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import socket
|
|
17
|
+
import threading
|
|
18
|
+
from typing import Any, Callable
|
|
19
|
+
|
|
20
|
+
from . import protocol
|
|
21
|
+
from .link import default_port
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("lefx.device.simulated_respeaker.client")
|
|
24
|
+
|
|
25
|
+
RECONNECT_INTERVAL_S = 1.0
|
|
26
|
+
CONNECT_TIMEOUT_S = 2.0
|
|
27
|
+
|
|
28
|
+
FrameCallback = Callable[[list[int], float], None]
|
|
29
|
+
StateCallback = Callable[[bool, str | None], None]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SimulatorClient:
|
|
33
|
+
"""Keeps a connection to the service, or keeps trying to."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
host: str = protocol.DEFAULT_HOST,
|
|
39
|
+
port: int | None = None,
|
|
40
|
+
on_frame: FrameCallback | None = None,
|
|
41
|
+
on_state: StateCallback | None = None,
|
|
42
|
+
on_led_count: Callable[[int], None] | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.host = host
|
|
45
|
+
self.port = default_port() if port is None else int(port)
|
|
46
|
+
self.on_frame = on_frame
|
|
47
|
+
self.on_state = on_state
|
|
48
|
+
self.on_led_count = on_led_count
|
|
49
|
+
|
|
50
|
+
self._lock = threading.RLock()
|
|
51
|
+
self._sock: socket.socket | None = None
|
|
52
|
+
self._stop = threading.Event()
|
|
53
|
+
self._thread: threading.Thread | None = None
|
|
54
|
+
self._connected = False
|
|
55
|
+
self._announced: bool | None = None
|
|
56
|
+
self._last_error: str | None = None
|
|
57
|
+
# Sent on every (re)connection, so a window that has been sitting at a
|
|
58
|
+
# given angle reports it again rather than looking silent.
|
|
59
|
+
self._controls: dict[str, Any] = {"direction_deg": 0.0, "detection_state": "none"}
|
|
60
|
+
|
|
61
|
+
# -- lifecycle ----------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
def start(self) -> None:
|
|
64
|
+
with self._lock:
|
|
65
|
+
if self._thread is not None and self._thread.is_alive():
|
|
66
|
+
return
|
|
67
|
+
self._stop.clear()
|
|
68
|
+
self._thread = threading.Thread(
|
|
69
|
+
target=self._run, name="lefx-simulator-client", daemon=True
|
|
70
|
+
)
|
|
71
|
+
self._thread.start()
|
|
72
|
+
|
|
73
|
+
def stop(self) -> None:
|
|
74
|
+
"""Idempotent."""
|
|
75
|
+
self._stop.set()
|
|
76
|
+
self._drop("stopped")
|
|
77
|
+
thread = self._thread
|
|
78
|
+
if thread is not None:
|
|
79
|
+
thread.join(timeout=CONNECT_TIMEOUT_S + 1.0)
|
|
80
|
+
self._thread = None
|
|
81
|
+
|
|
82
|
+
close = stop
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def connected(self) -> bool:
|
|
86
|
+
with self._lock:
|
|
87
|
+
return self._connected
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def last_error(self) -> str | None:
|
|
91
|
+
with self._lock:
|
|
92
|
+
return self._last_error
|
|
93
|
+
|
|
94
|
+
# -- controls -----------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def set_controls(self, *, direction_deg: float | None, detection_state: str) -> None:
|
|
97
|
+
"""Publish what the sliders currently say. Safe to call from the GUI thread."""
|
|
98
|
+
with self._lock:
|
|
99
|
+
controls = {"direction_deg": direction_deg, "detection_state": detection_state}
|
|
100
|
+
self._controls = controls
|
|
101
|
+
sock = self._sock
|
|
102
|
+
if sock is not None:
|
|
103
|
+
self._send(sock, protocol.inputs(**controls))
|
|
104
|
+
|
|
105
|
+
def _send(self, sock: socket.socket, message: dict[str, Any]) -> None:
|
|
106
|
+
try:
|
|
107
|
+
sock.sendall(protocol.encode(message))
|
|
108
|
+
except OSError as exc:
|
|
109
|
+
self._drop(f"send failed: {exc}")
|
|
110
|
+
|
|
111
|
+
# -- the connection thread ----------------------------------------------
|
|
112
|
+
|
|
113
|
+
def _run(self) -> None:
|
|
114
|
+
while not self._stop.is_set():
|
|
115
|
+
if self._connect():
|
|
116
|
+
self._read_until_closed()
|
|
117
|
+
if self._stop.wait(RECONNECT_INTERVAL_S):
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
def _connect(self) -> bool:
|
|
121
|
+
try:
|
|
122
|
+
sock = socket.create_connection((self.host, self.port), timeout=CONNECT_TIMEOUT_S)
|
|
123
|
+
except OSError as exc:
|
|
124
|
+
with self._lock:
|
|
125
|
+
self._last_error = f"cannot reach the service on {self.host}:{self.port}: {exc}"
|
|
126
|
+
self._announce(False)
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
# Blocking from here on: the reader should wait for frames, not spin.
|
|
130
|
+
sock.settimeout(None)
|
|
131
|
+
with self._lock:
|
|
132
|
+
self._sock = sock
|
|
133
|
+
self._connected = True
|
|
134
|
+
self._last_error = None
|
|
135
|
+
controls = dict(self._controls)
|
|
136
|
+
logger.info("connected to the service on %s:%s", self.host, self.port)
|
|
137
|
+
self._announce(True)
|
|
138
|
+
self._send(sock, protocol.inputs(**controls))
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
def _read_until_closed(self) -> None:
|
|
142
|
+
with self._lock:
|
|
143
|
+
sock = self._sock
|
|
144
|
+
if sock is None:
|
|
145
|
+
return
|
|
146
|
+
try:
|
|
147
|
+
while not self._stop.is_set():
|
|
148
|
+
message = protocol.read_message(sock)
|
|
149
|
+
if message is None:
|
|
150
|
+
break
|
|
151
|
+
self._handle(message)
|
|
152
|
+
except (OSError, protocol.ProtocolError) as exc:
|
|
153
|
+
self._drop(str(exc))
|
|
154
|
+
return
|
|
155
|
+
self._drop("the service closed the connection")
|
|
156
|
+
|
|
157
|
+
def _handle(self, message: dict[str, Any]) -> None:
|
|
158
|
+
kind = message.get("type")
|
|
159
|
+
if kind == protocol.HELLO:
|
|
160
|
+
led_count = message.get("led_count")
|
|
161
|
+
if self.on_led_count is not None and isinstance(led_count, int) and led_count > 0:
|
|
162
|
+
self.on_led_count(led_count)
|
|
163
|
+
elif kind == protocol.FRAME and self.on_frame is not None:
|
|
164
|
+
leds = message.get("leds")
|
|
165
|
+
if isinstance(leds, list):
|
|
166
|
+
self.on_frame([int(value) for value in leds], float(message.get("timestamp", 0.0)))
|
|
167
|
+
|
|
168
|
+
def _drop(self, reason: str) -> None:
|
|
169
|
+
with self._lock:
|
|
170
|
+
sock, self._sock = self._sock, None
|
|
171
|
+
was_connected = self._connected
|
|
172
|
+
self._connected = False
|
|
173
|
+
self._last_error = reason
|
|
174
|
+
if sock is not None:
|
|
175
|
+
try:
|
|
176
|
+
sock.close()
|
|
177
|
+
except OSError:
|
|
178
|
+
pass
|
|
179
|
+
if was_connected:
|
|
180
|
+
logger.info("disconnected: %s", reason)
|
|
181
|
+
self._announce(False)
|
|
182
|
+
|
|
183
|
+
def _announce(self, connected: bool) -> None:
|
|
184
|
+
"""Report a change, not a heartbeat.
|
|
185
|
+
|
|
186
|
+
A failed connection attempt happens once a second for as long as the
|
|
187
|
+
service is down; telling the window each time would turn a steady
|
|
188
|
+
"waiting" into a stream of identical updates.
|
|
189
|
+
"""
|
|
190
|
+
with self._lock:
|
|
191
|
+
if connected == self._announced:
|
|
192
|
+
return
|
|
193
|
+
self._announced = connected
|
|
194
|
+
detail = self._last_error
|
|
195
|
+
if self.on_state is None:
|
|
196
|
+
return
|
|
197
|
+
try:
|
|
198
|
+
self.on_state(connected, detail)
|
|
199
|
+
except Exception:
|
|
200
|
+
logger.exception("connection state callback failed")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = ["CONNECT_TIMEOUT_S", "RECONNECT_INTERVAL_S", "SimulatorClient"]
|