aiotssdk 0.1.0__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.
- aiotssdk/__init__.py +40 -0
- aiotssdk/client.py +380 -0
- aiotssdk/discovery.py +78 -0
- aiotssdk/exceptions.py +55 -0
- aiotssdk/models.py +67 -0
- aiotssdk/py.typed +0 -0
- aiotssdk-0.1.0.dist-info/METADATA +113 -0
- aiotssdk-0.1.0.dist-info/RECORD +10 -0
- aiotssdk-0.1.0.dist-info/WHEEL +4 -0
- aiotssdk-0.1.0.dist-info/licenses/LICENSE +21 -0
aiotssdk/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Async client for Teufel TSSDK audio devices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
from .client import DEFAULT_PORT, TssdkClient
|
|
8
|
+
from .discovery import DISCOVERY_PORT, discover, get_device_info
|
|
9
|
+
from .exceptions import (
|
|
10
|
+
TssdkApiError,
|
|
11
|
+
TssdkConnectionError,
|
|
12
|
+
TssdkError,
|
|
13
|
+
TssdkInvalidArgumentError,
|
|
14
|
+
TssdkNoSuchProcedureError,
|
|
15
|
+
TssdkNotAllowedError,
|
|
16
|
+
)
|
|
17
|
+
from .models import CallResult, DeviceInfo, Event
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
__version__ = version("aiotssdk")
|
|
21
|
+
except PackageNotFoundError: # pragma: no cover
|
|
22
|
+
__version__ = "0.0.0"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"DEFAULT_PORT",
|
|
26
|
+
"DISCOVERY_PORT",
|
|
27
|
+
"CallResult",
|
|
28
|
+
"DeviceInfo",
|
|
29
|
+
"Event",
|
|
30
|
+
"TssdkApiError",
|
|
31
|
+
"TssdkClient",
|
|
32
|
+
"TssdkConnectionError",
|
|
33
|
+
"TssdkError",
|
|
34
|
+
"TssdkInvalidArgumentError",
|
|
35
|
+
"TssdkNoSuchProcedureError",
|
|
36
|
+
"TssdkNotAllowedError",
|
|
37
|
+
"__version__",
|
|
38
|
+
"discover",
|
|
39
|
+
"get_device_info",
|
|
40
|
+
]
|
aiotssdk/client.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""Async client for the TSSDK WAMP API.
|
|
2
|
+
|
|
3
|
+
TSSDK devices run a WAMP v2 router on ``ws://<host>:8001`` (JSON serializer,
|
|
4
|
+
realm ``teufel``, no authentication). Every setting is a property ``X``:
|
|
5
|
+
|
|
6
|
+
* call ``X.get`` reads it,
|
|
7
|
+
* call ``X.set`` with the new value as the only positional argument writes it,
|
|
8
|
+
* topic ``X`` publishes the new value whenever it changes.
|
|
9
|
+
|
|
10
|
+
Actions are plain calls such as ``playback.pause``. The device does not answer
|
|
11
|
+
WebSocket pings, so the client sends none.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
from collections.abc import Awaitable, Callable
|
|
18
|
+
import contextlib
|
|
19
|
+
import itertools
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
from types import TracebackType
|
|
23
|
+
from typing import Any, Self
|
|
24
|
+
|
|
25
|
+
import aiohttp
|
|
26
|
+
|
|
27
|
+
from .exceptions import TssdkConnectionError, TssdkError, api_error
|
|
28
|
+
from .models import CallResult, Event
|
|
29
|
+
|
|
30
|
+
_LOGGER = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
DEFAULT_PORT = 8001
|
|
33
|
+
DEFAULT_REALM = "teufel"
|
|
34
|
+
DEFAULT_TIMEOUT = 10.0
|
|
35
|
+
GOODBYE_TIMEOUT = 1.0
|
|
36
|
+
SUBPROTOCOL = "wamp.2.json"
|
|
37
|
+
|
|
38
|
+
HELLO, WELCOME, ABORT, GOODBYE, ERROR = 1, 2, 3, 6, 8
|
|
39
|
+
SUBSCRIBE, SUBSCRIBED, UNSUBSCRIBE, UNSUBSCRIBED, EVENT = 32, 33, 34, 35, 36
|
|
40
|
+
CALL, RESULT = 48, 50
|
|
41
|
+
|
|
42
|
+
ROLES: dict[str, Any] = {"roles": {"caller": {}, "subscriber": {}}}
|
|
43
|
+
|
|
44
|
+
EventCallback = Callable[[Event], None]
|
|
45
|
+
DisconnectCallback = Callable[[Exception | None], None]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TssdkClient:
|
|
49
|
+
"""Talk to one TSSDK device over its local WAMP API.
|
|
50
|
+
|
|
51
|
+
Pass an existing :class:`aiohttp.ClientSession` (recommended), or use the
|
|
52
|
+
client as an async context manager to let it manage its own session.
|
|
53
|
+
|
|
54
|
+
Subscriptions are remembered: after a lost connection, call
|
|
55
|
+
:meth:`connect` again and they are renewed.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
host: str,
|
|
61
|
+
session: aiohttp.ClientSession | None = None,
|
|
62
|
+
*,
|
|
63
|
+
port: int = DEFAULT_PORT,
|
|
64
|
+
realm: str = DEFAULT_REALM,
|
|
65
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
66
|
+
) -> None:
|
|
67
|
+
"""Create a client for the device at ``host``."""
|
|
68
|
+
self.host = host
|
|
69
|
+
self.port = port
|
|
70
|
+
self.realm = realm
|
|
71
|
+
self._session = session
|
|
72
|
+
self._owns_session = session is None
|
|
73
|
+
self._timeout = timeout
|
|
74
|
+
self._ws: aiohttp.ClientWebSocketResponse | None = None
|
|
75
|
+
self._reader: asyncio.Task[None] | None = None
|
|
76
|
+
self._session_id: int | None = None
|
|
77
|
+
self._ids = itertools.count(1)
|
|
78
|
+
self._pending: dict[int, asyncio.Future[list[Any]]] = {}
|
|
79
|
+
self._send_lock = asyncio.Lock()
|
|
80
|
+
self._connect_lock = asyncio.Lock()
|
|
81
|
+
self._callbacks: dict[str, list[EventCallback]] = {}
|
|
82
|
+
self._subscription_ids: dict[str, int] = {}
|
|
83
|
+
self._topics_by_id: dict[int, str] = {}
|
|
84
|
+
self._disconnect_callbacks: list[DisconnectCallback] = []
|
|
85
|
+
self._closing_ws: aiohttp.ClientWebSocketResponse | None = None
|
|
86
|
+
self._goodbye: asyncio.Future[None] | None = None
|
|
87
|
+
|
|
88
|
+
async def __aenter__(self) -> Self:
|
|
89
|
+
"""Connect and return the client."""
|
|
90
|
+
await self.connect()
|
|
91
|
+
return self
|
|
92
|
+
|
|
93
|
+
async def __aexit__(
|
|
94
|
+
self,
|
|
95
|
+
exc_type: type[BaseException] | None,
|
|
96
|
+
exc: BaseException | None,
|
|
97
|
+
traceback: TracebackType | None,
|
|
98
|
+
) -> None:
|
|
99
|
+
"""Disconnect and close the session if the client created it."""
|
|
100
|
+
await self.close()
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def url(self) -> str:
|
|
104
|
+
"""The WebSocket URL of the device."""
|
|
105
|
+
return f"ws://{self.host}:{self.port}"
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def connected(self) -> bool:
|
|
109
|
+
"""Whether a WAMP session is established."""
|
|
110
|
+
return self._session_id is not None and self._ws is not None
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def session_id(self) -> int | None:
|
|
114
|
+
"""The WAMP session id, while connected."""
|
|
115
|
+
return self._session_id
|
|
116
|
+
|
|
117
|
+
def add_disconnect_callback(
|
|
118
|
+
self, callback: DisconnectCallback
|
|
119
|
+
) -> Callable[[], None]:
|
|
120
|
+
"""Call ``callback`` when an established connection ends; returns a remover.
|
|
121
|
+
|
|
122
|
+
The callback gets the error that ended the connection, or ``None`` when
|
|
123
|
+
:meth:`disconnect` was called.
|
|
124
|
+
"""
|
|
125
|
+
self._disconnect_callbacks.append(callback)
|
|
126
|
+
return lambda: self._disconnect_callbacks.remove(callback)
|
|
127
|
+
|
|
128
|
+
async def connect(self) -> None:
|
|
129
|
+
"""Open the WebSocket, join the realm and renew all subscriptions.
|
|
130
|
+
|
|
131
|
+
Does nothing when already connected.
|
|
132
|
+
"""
|
|
133
|
+
async with self._connect_lock:
|
|
134
|
+
if self.connected:
|
|
135
|
+
return
|
|
136
|
+
if self._session is None:
|
|
137
|
+
self._session = aiohttp.ClientSession()
|
|
138
|
+
try:
|
|
139
|
+
ws = await self._session.ws_connect(
|
|
140
|
+
self.url,
|
|
141
|
+
protocols=(SUBPROTOCOL,),
|
|
142
|
+
heartbeat=None,
|
|
143
|
+
timeout=aiohttp.ClientWSTimeout(ws_close=self._timeout),
|
|
144
|
+
)
|
|
145
|
+
except (aiohttp.ClientError, OSError, TimeoutError) as err:
|
|
146
|
+
raise TssdkConnectionError(
|
|
147
|
+
f"Cannot connect to {self.url}: {err}"
|
|
148
|
+
) from err
|
|
149
|
+
try:
|
|
150
|
+
session_id = await self._join(ws)
|
|
151
|
+
except BaseException:
|
|
152
|
+
await ws.close()
|
|
153
|
+
raise
|
|
154
|
+
self._ws = ws
|
|
155
|
+
self._session_id = session_id
|
|
156
|
+
self._reader = asyncio.create_task(
|
|
157
|
+
self._read(ws), name=f"aiotssdk {self.host}"
|
|
158
|
+
)
|
|
159
|
+
topics = list(self._callbacks)
|
|
160
|
+
for topic in topics:
|
|
161
|
+
try:
|
|
162
|
+
await self._subscribe(topic)
|
|
163
|
+
except TssdkConnectionError:
|
|
164
|
+
raise
|
|
165
|
+
except TssdkError as err:
|
|
166
|
+
_LOGGER.warning("Could not renew subscription to %s: %s", topic, err)
|
|
167
|
+
|
|
168
|
+
async def _join(self, ws: aiohttp.ClientWebSocketResponse) -> int:
|
|
169
|
+
await ws.send_str(json.dumps([HELLO, self.realm, ROLES]))
|
|
170
|
+
try:
|
|
171
|
+
msg = await ws.receive(timeout=self._timeout)
|
|
172
|
+
except TimeoutError as err:
|
|
173
|
+
raise TssdkConnectionError("No WELCOME from the device") from err
|
|
174
|
+
if msg.type is not aiohttp.WSMsgType.TEXT:
|
|
175
|
+
raise TssdkConnectionError(f"Session closed while joining: {msg.type.name}")
|
|
176
|
+
data = json.loads(msg.data)
|
|
177
|
+
if data[0] == WELCOME:
|
|
178
|
+
return int(data[1])
|
|
179
|
+
if data[0] == ABORT:
|
|
180
|
+
raise TssdkConnectionError(f"Device refused the session: {data[2]}")
|
|
181
|
+
raise TssdkConnectionError(f"Unexpected message while joining: {data!r}")
|
|
182
|
+
|
|
183
|
+
async def disconnect(self) -> None:
|
|
184
|
+
"""Leave the session and close the WebSocket; subscriptions are kept."""
|
|
185
|
+
ws, reader = self._ws, self._reader
|
|
186
|
+
if ws is None:
|
|
187
|
+
return
|
|
188
|
+
self._closing_ws = ws
|
|
189
|
+
self._goodbye = asyncio.get_running_loop().create_future()
|
|
190
|
+
with contextlib.suppress(TssdkError, TimeoutError):
|
|
191
|
+
await self._send([GOODBYE, {}, "wamp.close.system_shutdown"])
|
|
192
|
+
async with asyncio.timeout(min(self._timeout, GOODBYE_TIMEOUT)):
|
|
193
|
+
await asyncio.shield(self._goodbye)
|
|
194
|
+
await ws.close()
|
|
195
|
+
if reader is not None:
|
|
196
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
197
|
+
await reader
|
|
198
|
+
|
|
199
|
+
async def close(self) -> None:
|
|
200
|
+
"""Disconnect and close the session if the client created it."""
|
|
201
|
+
await self.disconnect()
|
|
202
|
+
if self._owns_session and self._session is not None:
|
|
203
|
+
await self._session.close()
|
|
204
|
+
self._session = None
|
|
205
|
+
|
|
206
|
+
async def call(self, procedure: str, *args: Any, **kwargs: Any) -> CallResult:
|
|
207
|
+
"""Call ``procedure`` and return its results.
|
|
208
|
+
|
|
209
|
+
Raises :class:`TssdkApiError` (or a subclass) when the device answers
|
|
210
|
+
with an error, and :class:`TssdkConnectionError` when not connected,
|
|
211
|
+
the connection drops or the device does not answer in time.
|
|
212
|
+
"""
|
|
213
|
+
msg: list[Any] = [CALL, 0, {}, procedure]
|
|
214
|
+
if args or kwargs:
|
|
215
|
+
msg.append(list(args))
|
|
216
|
+
if kwargs:
|
|
217
|
+
msg.append(kwargs)
|
|
218
|
+
data = await self._request(msg)
|
|
219
|
+
return CallResult(
|
|
220
|
+
list(data[3]) if len(data) > 3 else [],
|
|
221
|
+
dict(data[4]) if len(data) > 4 else {},
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
async def get(self, name: str) -> Any:
|
|
225
|
+
"""Read property ``name`` (calls ``<name>.get``)."""
|
|
226
|
+
return (await self.call(f"{name}.get")).value
|
|
227
|
+
|
|
228
|
+
async def set(self, name: str, value: Any) -> None:
|
|
229
|
+
"""Write property ``name`` (calls ``<name>.set`` with ``value``)."""
|
|
230
|
+
await self.call(f"{name}.set", value)
|
|
231
|
+
|
|
232
|
+
async def subscribe(
|
|
233
|
+
self, topic: str, callback: EventCallback
|
|
234
|
+
) -> Callable[[], Awaitable[None]]:
|
|
235
|
+
"""Call ``callback`` with every event on ``topic``; returns an async remover.
|
|
236
|
+
|
|
237
|
+
Topics must match exactly (property events use the property name).
|
|
238
|
+
When not connected, the subscription is made on the next :meth:`connect`.
|
|
239
|
+
"""
|
|
240
|
+
callbacks = self._callbacks.setdefault(topic, [])
|
|
241
|
+
callbacks.append(callback)
|
|
242
|
+
if self.connected and topic not in self._subscription_ids:
|
|
243
|
+
try:
|
|
244
|
+
await self._subscribe(topic)
|
|
245
|
+
except BaseException:
|
|
246
|
+
callbacks.remove(callback)
|
|
247
|
+
if not callbacks:
|
|
248
|
+
del self._callbacks[topic]
|
|
249
|
+
raise
|
|
250
|
+
|
|
251
|
+
async def remove() -> None:
|
|
252
|
+
await self._unsubscribe(topic, callback)
|
|
253
|
+
|
|
254
|
+
return remove
|
|
255
|
+
|
|
256
|
+
async def _subscribe(self, topic: str) -> None:
|
|
257
|
+
data = await self._request([SUBSCRIBE, 0, {}, topic])
|
|
258
|
+
sub_id = int(data[2])
|
|
259
|
+
self._subscription_ids[topic] = sub_id
|
|
260
|
+
self._topics_by_id[sub_id] = topic
|
|
261
|
+
|
|
262
|
+
async def _unsubscribe(self, topic: str, callback: EventCallback) -> None:
|
|
263
|
+
callbacks = self._callbacks.get(topic, [])
|
|
264
|
+
if callback in callbacks:
|
|
265
|
+
callbacks.remove(callback)
|
|
266
|
+
if callbacks:
|
|
267
|
+
return
|
|
268
|
+
self._callbacks.pop(topic, None)
|
|
269
|
+
sub_id = self._subscription_ids.pop(topic, None)
|
|
270
|
+
if sub_id is None:
|
|
271
|
+
return
|
|
272
|
+
self._topics_by_id.pop(sub_id, None)
|
|
273
|
+
if self.connected:
|
|
274
|
+
with contextlib.suppress(TssdkError):
|
|
275
|
+
await self._request([UNSUBSCRIBE, 0, sub_id])
|
|
276
|
+
|
|
277
|
+
async def _request(self, msg: list[Any]) -> list[Any]:
|
|
278
|
+
if not self.connected:
|
|
279
|
+
raise TssdkConnectionError("Not connected")
|
|
280
|
+
request_id = next(self._ids)
|
|
281
|
+
msg[1] = request_id
|
|
282
|
+
future: asyncio.Future[list[Any]] = asyncio.get_running_loop().create_future()
|
|
283
|
+
self._pending[request_id] = future
|
|
284
|
+
try:
|
|
285
|
+
await self._send(msg)
|
|
286
|
+
async with asyncio.timeout(self._timeout):
|
|
287
|
+
return await future
|
|
288
|
+
except TimeoutError as err:
|
|
289
|
+
raise TssdkConnectionError(f"No answer to {msg[0]} {msg[-1]!r}") from err
|
|
290
|
+
finally:
|
|
291
|
+
self._pending.pop(request_id, None)
|
|
292
|
+
|
|
293
|
+
async def _send(self, msg: list[Any]) -> None:
|
|
294
|
+
if self._ws is None:
|
|
295
|
+
raise TssdkConnectionError("Not connected")
|
|
296
|
+
try:
|
|
297
|
+
async with self._send_lock:
|
|
298
|
+
await self._ws.send_str(json.dumps(msg))
|
|
299
|
+
except (aiohttp.ClientError, ConnectionError) as err:
|
|
300
|
+
raise TssdkConnectionError(f"Send failed: {err}") from err
|
|
301
|
+
|
|
302
|
+
async def _read(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
303
|
+
error: Exception | None = None
|
|
304
|
+
try:
|
|
305
|
+
async for msg in ws:
|
|
306
|
+
if msg.type is aiohttp.WSMsgType.TEXT:
|
|
307
|
+
self._dispatch(json.loads(msg.data))
|
|
308
|
+
elif msg.type is aiohttp.WSMsgType.ERROR:
|
|
309
|
+
error = TssdkConnectionError(f"WebSocket error: {ws.exception()}")
|
|
310
|
+
break
|
|
311
|
+
else:
|
|
312
|
+
if ws is not self._closing_ws:
|
|
313
|
+
error = TssdkConnectionError("Connection closed by the device")
|
|
314
|
+
except (aiohttp.ClientError, ValueError) as err:
|
|
315
|
+
error = TssdkConnectionError(f"Connection lost: {err}")
|
|
316
|
+
finally:
|
|
317
|
+
self._connection_lost(error or TssdkConnectionError("Connection closed"))
|
|
318
|
+
if not ws.closed:
|
|
319
|
+
await ws.close()
|
|
320
|
+
self._notify_disconnect(error)
|
|
321
|
+
|
|
322
|
+
def _dispatch(self, data: list[Any]) -> None:
|
|
323
|
+
kind = data[0]
|
|
324
|
+
if kind == EVENT:
|
|
325
|
+
topic = self._topics_by_id.get(data[1])
|
|
326
|
+
if topic is None:
|
|
327
|
+
return
|
|
328
|
+
event = Event(
|
|
329
|
+
topic,
|
|
330
|
+
list(data[4]) if len(data) > 4 else [],
|
|
331
|
+
dict(data[5]) if len(data) > 5 else {},
|
|
332
|
+
)
|
|
333
|
+
for callback in list(self._callbacks.get(topic, [])):
|
|
334
|
+
try:
|
|
335
|
+
callback(event)
|
|
336
|
+
except Exception:
|
|
337
|
+
_LOGGER.exception("Error in event callback for %s", topic)
|
|
338
|
+
elif kind in (RESULT, SUBSCRIBED, UNSUBSCRIBED):
|
|
339
|
+
self._resolve(data[1], data)
|
|
340
|
+
elif kind == ERROR:
|
|
341
|
+
future = self._pending.get(data[2])
|
|
342
|
+
if future is not None and not future.done():
|
|
343
|
+
future.set_exception(
|
|
344
|
+
api_error(
|
|
345
|
+
data[4],
|
|
346
|
+
list(data[5]) if len(data) > 5 else None,
|
|
347
|
+
dict(data[6]) if len(data) > 6 else None,
|
|
348
|
+
)
|
|
349
|
+
)
|
|
350
|
+
elif kind == GOODBYE:
|
|
351
|
+
if self._goodbye is not None and not self._goodbye.done():
|
|
352
|
+
self._goodbye.set_result(None)
|
|
353
|
+
elif self._ws is not None:
|
|
354
|
+
task = asyncio.ensure_future(
|
|
355
|
+
self._send([GOODBYE, {}, "wamp.close.goodbye_and_out"])
|
|
356
|
+
)
|
|
357
|
+
task.add_done_callback(lambda t: t.exception())
|
|
358
|
+
|
|
359
|
+
def _resolve(self, request_id: int, data: list[Any]) -> None:
|
|
360
|
+
future = self._pending.get(request_id)
|
|
361
|
+
if future is not None and not future.done():
|
|
362
|
+
future.set_result(data)
|
|
363
|
+
|
|
364
|
+
def _connection_lost(self, error: Exception) -> None:
|
|
365
|
+
self._ws = None
|
|
366
|
+
self._session_id = None
|
|
367
|
+
self._reader = None
|
|
368
|
+
self._subscription_ids.clear()
|
|
369
|
+
self._topics_by_id.clear()
|
|
370
|
+
for future in self._pending.values():
|
|
371
|
+
if not future.done():
|
|
372
|
+
future.set_exception(error)
|
|
373
|
+
self._pending.clear()
|
|
374
|
+
|
|
375
|
+
def _notify_disconnect(self, error: Exception | None) -> None:
|
|
376
|
+
for callback in list(self._disconnect_callbacks):
|
|
377
|
+
try:
|
|
378
|
+
callback(error)
|
|
379
|
+
except Exception:
|
|
380
|
+
_LOGGER.exception("Error in disconnect callback")
|
aiotssdk/discovery.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""UDP discovery of TSSDK devices.
|
|
2
|
+
|
|
3
|
+
Devices answer ``{"discoveryType": "device", "discoveryVersion": 1}`` sent to
|
|
4
|
+
UDP port 8000 with their id, name, model, color, firmware, MAC and WAMP port.
|
|
5
|
+
Unicast works too, which makes it a cheap way to identify a device by address.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import contextlib
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .exceptions import TssdkConnectionError
|
|
17
|
+
from .models import DeviceInfo
|
|
18
|
+
|
|
19
|
+
_LOGGER = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
DISCOVERY_PORT = 8000
|
|
22
|
+
BROADCAST = "255.255.255.255"
|
|
23
|
+
REQUEST = json.dumps({"discoveryType": "device", "discoveryVersion": 1}).encode()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _DiscoveryProtocol(asyncio.DatagramProtocol):
|
|
27
|
+
def __init__(self, first_only: bool) -> None:
|
|
28
|
+
self.devices: dict[str, DeviceInfo] = {}
|
|
29
|
+
self.done = asyncio.get_running_loop().create_future()
|
|
30
|
+
self._first_only = first_only
|
|
31
|
+
|
|
32
|
+
def datagram_received(self, data: bytes, addr: tuple[str | Any, int]) -> None:
|
|
33
|
+
try:
|
|
34
|
+
payload = json.loads(data)
|
|
35
|
+
info = DeviceInfo.from_response(str(addr[0]), payload)
|
|
36
|
+
except (ValueError, KeyError, TypeError):
|
|
37
|
+
_LOGGER.debug("Ignoring discovery reply from %s: %r", addr[0], data[:200])
|
|
38
|
+
return
|
|
39
|
+
self.devices.setdefault(info.device_id, info)
|
|
40
|
+
if self._first_only and not self.done.done():
|
|
41
|
+
self.done.set_result(None)
|
|
42
|
+
|
|
43
|
+
def error_received(self, exc: Exception) -> None:
|
|
44
|
+
_LOGGER.debug("Discovery socket error: %s", exc)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def discover(
|
|
48
|
+
host: str | None = None, *, port: int = DISCOVERY_PORT, timeout: float = 2.0
|
|
49
|
+
) -> list[DeviceInfo]:
|
|
50
|
+
"""Find TSSDK devices.
|
|
51
|
+
|
|
52
|
+
With ``host``, ask that address only and return as soon as it answers;
|
|
53
|
+
otherwise broadcast and collect every answer until ``timeout``.
|
|
54
|
+
"""
|
|
55
|
+
loop = asyncio.get_running_loop()
|
|
56
|
+
transport, protocol = await loop.create_datagram_endpoint(
|
|
57
|
+
lambda: _DiscoveryProtocol(first_only=host is not None),
|
|
58
|
+
# Replies come from devices on the LAN, so listen on all interfaces.
|
|
59
|
+
local_addr=("0.0.0.0", 0), # nosec B104
|
|
60
|
+
allow_broadcast=host is None,
|
|
61
|
+
)
|
|
62
|
+
try:
|
|
63
|
+
transport.sendto(REQUEST, (host or BROADCAST, port))
|
|
64
|
+
with contextlib.suppress(TimeoutError):
|
|
65
|
+
await asyncio.wait_for(asyncio.shield(protocol.done), timeout)
|
|
66
|
+
finally:
|
|
67
|
+
transport.close()
|
|
68
|
+
return list(protocol.devices.values())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def get_device_info(
|
|
72
|
+
host: str, *, port: int = DISCOVERY_PORT, timeout: float = 2.0
|
|
73
|
+
) -> DeviceInfo:
|
|
74
|
+
"""Identify the device at ``host``; raises TssdkConnectionError if it does not answer."""
|
|
75
|
+
devices = await discover(host, port=port, timeout=timeout)
|
|
76
|
+
if not devices:
|
|
77
|
+
raise TssdkConnectionError(f"No discovery answer from {host}")
|
|
78
|
+
return devices[0]
|
aiotssdk/exceptions.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Errors raised by aiotssdk."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TssdkError(Exception):
|
|
9
|
+
"""Base error."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TssdkConnectionError(TssdkError):
|
|
13
|
+
"""The device could not be reached, closed the session or did not answer in time."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TssdkApiError(TssdkError):
|
|
17
|
+
"""The device answered a call or subscription with a WAMP error."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
error: str,
|
|
22
|
+
args: list[Any] | None = None,
|
|
23
|
+
kwargs: dict[str, Any] | None = None,
|
|
24
|
+
) -> None:
|
|
25
|
+
"""Store the WAMP error URI and its payload."""
|
|
26
|
+
super().__init__(error if not args else f"{error}: {args}")
|
|
27
|
+
self.error = error
|
|
28
|
+
self.error_args = args or []
|
|
29
|
+
self.error_kwargs = kwargs or {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TssdkNoSuchProcedureError(TssdkApiError):
|
|
33
|
+
"""The device does not offer this procedure (``wamp.error.no_such_procedure``)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TssdkInvalidArgumentError(TssdkApiError):
|
|
37
|
+
"""The arguments were rejected (``wamp.error.invalid_argument``)."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TssdkNotAllowedError(TssdkApiError):
|
|
41
|
+
"""The call is not allowed in the current state (``de.teufel.error.not_allowed``)."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
ERRORS: dict[str, type[TssdkApiError]] = {
|
|
45
|
+
"wamp.error.no_such_procedure": TssdkNoSuchProcedureError,
|
|
46
|
+
"wamp.error.invalid_argument": TssdkInvalidArgumentError,
|
|
47
|
+
"de.teufel.error.not_allowed": TssdkNotAllowedError,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def api_error(
|
|
52
|
+
error: str, args: list[Any] | None = None, kwargs: dict[str, Any] | None = None
|
|
53
|
+
) -> TssdkApiError:
|
|
54
|
+
"""Build the most specific error for a WAMP error URI."""
|
|
55
|
+
return ERRORS.get(error, TssdkApiError)(error, args, kwargs)
|
aiotssdk/models.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Data types returned by aiotssdk."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class CallResult:
|
|
11
|
+
"""Positional and keyword results of a WAMP call."""
|
|
12
|
+
|
|
13
|
+
args: list[Any] = field(default_factory=list)
|
|
14
|
+
kwargs: dict[str, Any] = field(default_factory=dict)
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def value(self) -> Any:
|
|
18
|
+
"""The first positional result, or ``None``."""
|
|
19
|
+
return self.args[0] if self.args else None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class Event:
|
|
24
|
+
"""An event published on a topic, e.g. a property change."""
|
|
25
|
+
|
|
26
|
+
topic: str
|
|
27
|
+
args: list[Any] = field(default_factory=list)
|
|
28
|
+
kwargs: dict[str, Any] = field(default_factory=dict)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def value(self) -> Any:
|
|
32
|
+
"""The first positional payload (the new property value), or ``None``."""
|
|
33
|
+
return self.args[0] if self.args else None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class DeviceInfo:
|
|
38
|
+
"""A device's answer to a UDP discovery request."""
|
|
39
|
+
|
|
40
|
+
host: str
|
|
41
|
+
device_id: str
|
|
42
|
+
name: str | None = None
|
|
43
|
+
model_id: int | None = None
|
|
44
|
+
model_name: str | None = None
|
|
45
|
+
product_name: str | None = None
|
|
46
|
+
color_id: int | None = None
|
|
47
|
+
color_name: str | None = None
|
|
48
|
+
firmware_version: str | None = None
|
|
49
|
+
mac_address: str | None = None
|
|
50
|
+
wamp_port: int | None = None
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def from_response(cls, host: str, data: dict[str, Any]) -> DeviceInfo:
|
|
54
|
+
"""Build from a discovery response; raises ``KeyError`` without a deviceId."""
|
|
55
|
+
return cls(
|
|
56
|
+
host=host,
|
|
57
|
+
device_id=str(data["deviceId"]),
|
|
58
|
+
name=data.get("deviceName"),
|
|
59
|
+
model_id=data.get("modelId"),
|
|
60
|
+
model_name=data.get("modelName"),
|
|
61
|
+
product_name=data.get("productName"),
|
|
62
|
+
color_id=data.get("colorId"),
|
|
63
|
+
color_name=data.get("colorName"),
|
|
64
|
+
firmware_version=data.get("firmwareVersion"),
|
|
65
|
+
mac_address=data.get("macAddress"),
|
|
66
|
+
wamp_port=data.get("wampPort"),
|
|
67
|
+
)
|
aiotssdk/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aiotssdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async client for the local WAMP API of Teufel TSSDK audio devices (STEREO M 2, ...)
|
|
5
|
+
Project-URL: Homepage, https://github.com/nyxdis/aiotssdk
|
|
6
|
+
Project-URL: Issues, https://github.com/nyxdis/aiotssdk/issues
|
|
7
|
+
Author: nyxdis
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: asyncio,audio,teufel,tssdk,wamp
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Home Automation
|
|
20
|
+
Classifier: Topic :: Multimedia :: Sound/Audio
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: aiohttp>=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# aiotssdk
|
|
27
|
+
|
|
28
|
+
[](https://github.com/nyxdis/aiotssdk/actions/workflows/ci.yml)
|
|
29
|
+
[](https://scorecard.dev/viewer/?uri=github.com/nyxdis/aiotssdk)
|
|
30
|
+
[](https://pypi.org/project/aiotssdk/)
|
|
31
|
+
|
|
32
|
+
Async Python client for the local network API of Teufel audio devices with the
|
|
33
|
+
**TSSDK** firmware, such as the Teufel STEREO M 2.
|
|
34
|
+
|
|
35
|
+
These devices run a [WAMP](https://wamp-proto.org/) router on port 8001
|
|
36
|
+
(WebSocket, JSON, realm `teufel`) that needs no login: anyone on the local network
|
|
37
|
+
can talk to them. Older Teufel streaming devices (Cinebar Pro 2, Motiv Home) use a
|
|
38
|
+
different API; see [aiostreamsdk](https://github.com/nyxdis/aiostreamsdk) for those.
|
|
39
|
+
|
|
40
|
+
This is an unofficial project, not affiliated with or endorsed by Teufel. It was
|
|
41
|
+
tested against a Teufel STEREO M 2 (firmware 1.5.1). Known procedures, value types
|
|
42
|
+
and quirks are collected in [docs/protocol.md](docs/protocol.md).
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install aiotssdk
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Requires Python 3.12+ and aiohttp.
|
|
51
|
+
|
|
52
|
+
## Usage
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import asyncio
|
|
56
|
+
|
|
57
|
+
from aiotssdk import TssdkClient, TssdkNotAllowedError, discover
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def main() -> None:
|
|
61
|
+
# Find devices on the network (UDP broadcast), or identify one by address
|
|
62
|
+
for device in await discover():
|
|
63
|
+
print(device.host, device.name, device.model_name, device.firmware_version)
|
|
64
|
+
|
|
65
|
+
async with TssdkClient("192.168.1.50") as tssdk:
|
|
66
|
+
# Properties: X.get / X.set / topic X
|
|
67
|
+
print(await tssdk.get("audiocontrol.volume")) # 31
|
|
68
|
+
await tssdk.set("audiocontrol.volume", 35)
|
|
69
|
+
print(await tssdk.get("audiocontrol.eq.graphic.bands"))
|
|
70
|
+
|
|
71
|
+
# Actions are plain calls
|
|
72
|
+
await tssdk.call("power.standby.leave")
|
|
73
|
+
try:
|
|
74
|
+
await tssdk.call("playback.seek", 60)
|
|
75
|
+
except TssdkNotAllowedError:
|
|
76
|
+
print("seeking is not possible for this source")
|
|
77
|
+
|
|
78
|
+
# Follow changes (exact topic names only)
|
|
79
|
+
await tssdk.subscribe(
|
|
80
|
+
"audiocontrol.volume", lambda event: print("volume", event.value)
|
|
81
|
+
)
|
|
82
|
+
tssdk.add_disconnect_callback(lambda err: print("disconnected", err))
|
|
83
|
+
await asyncio.sleep(60)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
asyncio.run(main())
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
After a lost connection, call `connect()` again: subscriptions are renewed
|
|
90
|
+
automatically. The device does not answer WebSocket pings, so the client sends
|
|
91
|
+
none; poll a cheap property now and then if you need to notice a dead connection.
|
|
92
|
+
|
|
93
|
+
## Errors
|
|
94
|
+
|
|
95
|
+
| Exception | When |
|
|
96
|
+
|---|---|
|
|
97
|
+
| `TssdkConnectionError` | cannot connect, connection lost, no answer in time |
|
|
98
|
+
| `TssdkNoSuchProcedureError` | the device does not offer the procedure |
|
|
99
|
+
| `TssdkInvalidArgumentError` | the arguments were rejected |
|
|
100
|
+
| `TssdkNotAllowedError` | not possible in the current state (e.g. seeking AirPlay) |
|
|
101
|
+
| `TssdkApiError` | any other WAMP error; `.error` holds the URI |
|
|
102
|
+
|
|
103
|
+
## Development
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
uv sync
|
|
107
|
+
uv run pytest
|
|
108
|
+
uv run ruff check . && uv run ruff format --check . && uv run mypy
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
aiotssdk/__init__.py,sha256=klCrccdzZqEdaeBTKJwOSah6JEVa6B-VGe-RY17GBTw,951
|
|
2
|
+
aiotssdk/client.py,sha256=D73oCBD92idkOGaES8Qo_50jFfnLAxJ8pIryqns3R10,14483
|
|
3
|
+
aiotssdk/discovery.py,sha256=FZ-cerywEELEosSPHK3ZwM1ynaxy96_qVp7lrrLxGcY,2817
|
|
4
|
+
aiotssdk/exceptions.py,sha256=2ZOgWBtOKQdl79hza1TJROkszDwOw8iSAKHoJHc2jUw,1638
|
|
5
|
+
aiotssdk/models.py,sha256=4O-EHVuUu58S-C_iK5t1ZauunrX9avWR4stAcNjuv2Y,2071
|
|
6
|
+
aiotssdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
aiotssdk-0.1.0.dist-info/METADATA,sha256=H4XBA30X6jHhptd_vWpXVBXUf2rG4mx-7-7qlkzILaY,4040
|
|
8
|
+
aiotssdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
aiotssdk-0.1.0.dist-info/licenses/LICENSE,sha256=qWIr9jbW7aCU_GT3ylslrpKVEa3_XijqntVdA7bpJLE,1063
|
|
10
|
+
aiotssdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nyxdis
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|