aiostreamsdk 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.
- aiostreamsdk/__init__.py +48 -0
- aiostreamsdk/client.py +293 -0
- aiostreamsdk/events.py +87 -0
- aiostreamsdk/exceptions.py +29 -0
- aiostreamsdk/models.py +106 -0
- aiostreamsdk/py.typed +0 -0
- aiostreamsdk-0.1.0.dist-info/METADATA +110 -0
- aiostreamsdk-0.1.0.dist-info/RECORD +10 -0
- aiostreamsdk-0.1.0.dist-info/WHEEL +4 -0
- aiostreamsdk-0.1.0.dist-info/licenses/LICENSE +21 -0
aiostreamsdk/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Async client for StreamUnlimited StreamSDK audio devices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
from .client import (
|
|
8
|
+
PATH_GO_ONLINE,
|
|
9
|
+
PATH_GO_STANDBY,
|
|
10
|
+
PATH_PLAYER_CONTROL,
|
|
11
|
+
PATH_POWER,
|
|
12
|
+
PATH_REBOOT,
|
|
13
|
+
StreamSDKClient,
|
|
14
|
+
)
|
|
15
|
+
from .events import EventListener
|
|
16
|
+
from .exceptions import (
|
|
17
|
+
StreamSDKApiError,
|
|
18
|
+
StreamSDKConnectionError,
|
|
19
|
+
StreamSDKError,
|
|
20
|
+
StreamSDKNotModifiableError,
|
|
21
|
+
StreamSDKPathNotFoundError,
|
|
22
|
+
)
|
|
23
|
+
from .models import Event, Node, unwrap, wrap
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
__version__ = version("aiostreamsdk")
|
|
27
|
+
except PackageNotFoundError: # pragma: no cover
|
|
28
|
+
__version__ = "0.0.0"
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"PATH_GO_ONLINE",
|
|
32
|
+
"PATH_GO_STANDBY",
|
|
33
|
+
"PATH_PLAYER_CONTROL",
|
|
34
|
+
"PATH_POWER",
|
|
35
|
+
"PATH_REBOOT",
|
|
36
|
+
"Event",
|
|
37
|
+
"EventListener",
|
|
38
|
+
"Node",
|
|
39
|
+
"StreamSDKApiError",
|
|
40
|
+
"StreamSDKClient",
|
|
41
|
+
"StreamSDKConnectionError",
|
|
42
|
+
"StreamSDKError",
|
|
43
|
+
"StreamSDKNotModifiableError",
|
|
44
|
+
"StreamSDKPathNotFoundError",
|
|
45
|
+
"__version__",
|
|
46
|
+
"unwrap",
|
|
47
|
+
"wrap",
|
|
48
|
+
]
|
aiostreamsdk/client.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Async client for the StreamSDK HTTP API.
|
|
2
|
+
|
|
3
|
+
The API is a tree of nodes addressed by paths such as ``player:volume``:
|
|
4
|
+
|
|
5
|
+
* ``GET /api/getData?path=...&roles=@all`` reads a node,
|
|
6
|
+
* ``GET /api/getRows?path=...&roles=@all&from=0&to=100`` lists a container,
|
|
7
|
+
* ``POST /api/setData`` with ``{"path", "role", "value"}`` writes a value
|
|
8
|
+
(role ``value``) or triggers an action (role ``activate``),
|
|
9
|
+
* ``POST /api/event/modifyQueue`` and ``GET /api/event/pollQueue`` deliver
|
|
10
|
+
change events.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
from collections.abc import Iterable
|
|
17
|
+
import json
|
|
18
|
+
from types import TracebackType
|
|
19
|
+
from typing import Any, Self
|
|
20
|
+
|
|
21
|
+
import aiohttp
|
|
22
|
+
|
|
23
|
+
from .exceptions import (
|
|
24
|
+
StreamSDKApiError,
|
|
25
|
+
StreamSDKConnectionError,
|
|
26
|
+
StreamSDKError,
|
|
27
|
+
StreamSDKNotModifiableError,
|
|
28
|
+
StreamSDKPathNotFoundError,
|
|
29
|
+
)
|
|
30
|
+
from .models import Node
|
|
31
|
+
|
|
32
|
+
DEFAULT_TIMEOUT = 10.0
|
|
33
|
+
DEFAULT_PORT = 80
|
|
34
|
+
|
|
35
|
+
PATH_POWER = "powermanager:target"
|
|
36
|
+
PATH_GO_ONLINE = "powermanager:goOnline"
|
|
37
|
+
PATH_GO_STANDBY = "powermanager:goNetworkStandby"
|
|
38
|
+
PATH_REBOOT = "powermanager:goReboot"
|
|
39
|
+
PATH_PLAYER_CONTROL = "player:player/control"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class StreamSDKClient:
|
|
43
|
+
"""Talk to one StreamSDK device over its local HTTP API.
|
|
44
|
+
|
|
45
|
+
Pass an existing :class:`aiohttp.ClientSession` (recommended), or use the
|
|
46
|
+
client as an async context manager to let it manage its own session.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
host: str,
|
|
52
|
+
session: aiohttp.ClientSession | None = None,
|
|
53
|
+
*,
|
|
54
|
+
port: int = DEFAULT_PORT,
|
|
55
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
56
|
+
) -> None:
|
|
57
|
+
"""Create a client for the device at ``host``."""
|
|
58
|
+
self.host = host
|
|
59
|
+
self.port = port
|
|
60
|
+
self._session = session
|
|
61
|
+
self._owns_session = session is None
|
|
62
|
+
self._timeout = timeout
|
|
63
|
+
|
|
64
|
+
async def __aenter__(self) -> Self:
|
|
65
|
+
"""Enter the context, creating a session if needed."""
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
async def __aexit__(
|
|
69
|
+
self,
|
|
70
|
+
exc_type: type[BaseException] | None,
|
|
71
|
+
exc: BaseException | None,
|
|
72
|
+
traceback: TracebackType | None,
|
|
73
|
+
) -> None:
|
|
74
|
+
"""Close the session if the client created it."""
|
|
75
|
+
await self.close()
|
|
76
|
+
|
|
77
|
+
async def close(self) -> None:
|
|
78
|
+
"""Close the session if the client created it."""
|
|
79
|
+
if self._owns_session and self._session is not None:
|
|
80
|
+
await self._session.close()
|
|
81
|
+
self._session = None
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def base_url(self) -> str:
|
|
85
|
+
"""URL of the API root."""
|
|
86
|
+
host = f"[{self.host}]" if ":" in self.host else self.host
|
|
87
|
+
port = "" if self.port == DEFAULT_PORT else f":{self.port}"
|
|
88
|
+
return f"http://{host}{port}/api"
|
|
89
|
+
|
|
90
|
+
def _get_session(self) -> aiohttp.ClientSession:
|
|
91
|
+
if self._session is None:
|
|
92
|
+
self._session = aiohttp.ClientSession()
|
|
93
|
+
self._owns_session = True
|
|
94
|
+
return self._session
|
|
95
|
+
|
|
96
|
+
async def _request(
|
|
97
|
+
self,
|
|
98
|
+
method: str,
|
|
99
|
+
endpoint: str,
|
|
100
|
+
*,
|
|
101
|
+
params: dict[str, str] | None = None,
|
|
102
|
+
payload: dict[str, Any] | None = None,
|
|
103
|
+
timeout: float | None = None,
|
|
104
|
+
) -> Any:
|
|
105
|
+
"""Send one request and decode the JSON answer."""
|
|
106
|
+
url = f"{self.base_url}/{endpoint}"
|
|
107
|
+
try:
|
|
108
|
+
async with self._get_session().request(
|
|
109
|
+
method,
|
|
110
|
+
url,
|
|
111
|
+
params=params,
|
|
112
|
+
data=json.dumps(payload) if payload is not None else None,
|
|
113
|
+
headers={"Content-Type": "application/json"}
|
|
114
|
+
if payload is not None
|
|
115
|
+
else None,
|
|
116
|
+
timeout=aiohttp.ClientTimeout(total=timeout or self._timeout),
|
|
117
|
+
) as response:
|
|
118
|
+
text = await response.text()
|
|
119
|
+
status = response.status
|
|
120
|
+
except (TimeoutError, aiohttp.ClientError) as err:
|
|
121
|
+
raise StreamSDKConnectionError(
|
|
122
|
+
f"Error talking to {self.host}: {err!r}"
|
|
123
|
+
) from err
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
data = json.loads(text) if text else None
|
|
127
|
+
except ValueError as err:
|
|
128
|
+
raise StreamSDKConnectionError(
|
|
129
|
+
f"Invalid answer from {self.host} (HTTP {status})"
|
|
130
|
+
) from err
|
|
131
|
+
|
|
132
|
+
if isinstance(data, dict) and isinstance(data.get("error"), dict):
|
|
133
|
+
error = data["error"]
|
|
134
|
+
name = str(error.get("name", "unknown"))
|
|
135
|
+
message = str(error.get("message", ""))
|
|
136
|
+
if name.endswith("invalidPath"):
|
|
137
|
+
raise StreamSDKPathNotFoundError(name, message)
|
|
138
|
+
if "not modifiable" in message.lower():
|
|
139
|
+
raise StreamSDKNotModifiableError(name, message)
|
|
140
|
+
raise StreamSDKApiError(name, message)
|
|
141
|
+
if status >= 400:
|
|
142
|
+
raise StreamSDKConnectionError(f"HTTP {status} from {self.host}")
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
async def get_node(self, path: str) -> Node:
|
|
146
|
+
"""Read a node with all its metadata."""
|
|
147
|
+
data = await self._request(
|
|
148
|
+
"GET", "getData", params={"path": path, "roles": "@all"}
|
|
149
|
+
)
|
|
150
|
+
if not isinstance(data, dict):
|
|
151
|
+
raise StreamSDKApiError("invalidAnswer", f"Unexpected answer for {path}")
|
|
152
|
+
return Node.from_api(path, data)
|
|
153
|
+
|
|
154
|
+
async def get_nodes(
|
|
155
|
+
self, paths: Iterable[str], *, max_parallel: int = 4
|
|
156
|
+
) -> dict[str, Node]:
|
|
157
|
+
"""Read several nodes; paths the device does not have are left out.
|
|
158
|
+
|
|
159
|
+
Connection errors are raised; other API errors skip the node.
|
|
160
|
+
"""
|
|
161
|
+
semaphore = asyncio.Semaphore(max_parallel)
|
|
162
|
+
|
|
163
|
+
async def fetch(path: str) -> Node | None:
|
|
164
|
+
async with semaphore:
|
|
165
|
+
try:
|
|
166
|
+
return await self.get_node(path)
|
|
167
|
+
except StreamSDKApiError:
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
ordered = list(dict.fromkeys(paths))
|
|
171
|
+
results = await asyncio.gather(*(fetch(path) for path in ordered))
|
|
172
|
+
return {
|
|
173
|
+
path: node
|
|
174
|
+
for path, node in zip(ordered, results, strict=True)
|
|
175
|
+
if node is not None
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async def get_value(self, path: str) -> Any:
|
|
179
|
+
"""Read only the (typed) value of a node."""
|
|
180
|
+
data = await self._request(
|
|
181
|
+
"GET", "getData", params={"path": path, "roles": "value"}
|
|
182
|
+
)
|
|
183
|
+
if isinstance(data, list) and data:
|
|
184
|
+
return data[0]
|
|
185
|
+
if isinstance(data, dict):
|
|
186
|
+
return data.get("value")
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
async def get_rows(
|
|
190
|
+
self, path: str, start: int = 0, end: int = 200
|
|
191
|
+
) -> list[dict[str, Any]]:
|
|
192
|
+
"""List the children of a container node."""
|
|
193
|
+
data = await self._request(
|
|
194
|
+
"GET",
|
|
195
|
+
"getRows",
|
|
196
|
+
params={
|
|
197
|
+
"path": path,
|
|
198
|
+
"roles": "@all",
|
|
199
|
+
"from": str(start),
|
|
200
|
+
"to": str(end),
|
|
201
|
+
},
|
|
202
|
+
)
|
|
203
|
+
rows = data.get("rows") if isinstance(data, dict) else None
|
|
204
|
+
return [row for row in rows or [] if isinstance(row, dict)]
|
|
205
|
+
|
|
206
|
+
async def set_value(self, path: str, value: dict[str, Any]) -> None:
|
|
207
|
+
"""Write a typed value (see :func:`aiostreamsdk.wrap`).
|
|
208
|
+
|
|
209
|
+
Note that writes count as user activity and wake the device.
|
|
210
|
+
"""
|
|
211
|
+
await self._request(
|
|
212
|
+
"POST",
|
|
213
|
+
"setData",
|
|
214
|
+
payload={"path": path, "role": "value", "value": value},
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
async def activate(self, path: str, value: Any = None) -> Any:
|
|
218
|
+
"""Trigger an action node."""
|
|
219
|
+
return await self._request(
|
|
220
|
+
"POST",
|
|
221
|
+
"setData",
|
|
222
|
+
payload={
|
|
223
|
+
"path": path,
|
|
224
|
+
"role": "activate",
|
|
225
|
+
"value": {} if value is None else value,
|
|
226
|
+
},
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
async def wake(self) -> None:
|
|
230
|
+
"""Leave network standby."""
|
|
231
|
+
await self.activate(PATH_GO_ONLINE)
|
|
232
|
+
|
|
233
|
+
async def standby(self) -> None:
|
|
234
|
+
"""Go to network standby."""
|
|
235
|
+
await self.activate(PATH_GO_STANDBY)
|
|
236
|
+
|
|
237
|
+
async def reboot(self) -> None:
|
|
238
|
+
"""Reboot the device."""
|
|
239
|
+
await self.activate(PATH_REBOOT)
|
|
240
|
+
|
|
241
|
+
async def player_control(self, control: str, **extra: Any) -> None:
|
|
242
|
+
"""Send a player command: play, pause, stop, next, previous, ..."""
|
|
243
|
+
await self.activate(PATH_PLAYER_CONTROL, {"control": control, **extra})
|
|
244
|
+
|
|
245
|
+
async def play_item(self, media_roles: dict[str, Any]) -> None:
|
|
246
|
+
"""Play an item, e.g. an input row from ``getRows("ui:")``."""
|
|
247
|
+
await self.player_control("play", mediaRoles=media_roles)
|
|
248
|
+
|
|
249
|
+
async def create_queue(self, paths: Iterable[str]) -> str:
|
|
250
|
+
"""Create an event queue subscribed to value changes of ``paths``."""
|
|
251
|
+
data = await self._request(
|
|
252
|
+
"POST",
|
|
253
|
+
"event/modifyQueue",
|
|
254
|
+
payload={
|
|
255
|
+
"queueId": "",
|
|
256
|
+
"subscribe": [{"path": p, "type": "itemWithValue"} for p in paths],
|
|
257
|
+
"unsubscribe": [],
|
|
258
|
+
},
|
|
259
|
+
)
|
|
260
|
+
if not isinstance(data, str) or not data:
|
|
261
|
+
raise StreamSDKApiError("invalidAnswer", "No queue id returned")
|
|
262
|
+
return data
|
|
263
|
+
|
|
264
|
+
async def poll_queue(
|
|
265
|
+
self, queue_id: str, timeout: int = 10
|
|
266
|
+
) -> list[dict[str, Any]]:
|
|
267
|
+
"""Wait up to ``timeout`` seconds for events on a queue."""
|
|
268
|
+
data = await self._request(
|
|
269
|
+
"GET",
|
|
270
|
+
"event/pollQueue",
|
|
271
|
+
params={"queueId": queue_id, "timeout": str(timeout)},
|
|
272
|
+
timeout=timeout + self._timeout,
|
|
273
|
+
)
|
|
274
|
+
if not isinstance(data, list):
|
|
275
|
+
raise StreamSDKApiError("invalidAnswer", "Event queue answer is not a list")
|
|
276
|
+
return [event for event in data if isinstance(event, dict)]
|
|
277
|
+
|
|
278
|
+
async def delete_queue(self, queue_id: str, paths: Iterable[str]) -> None:
|
|
279
|
+
"""Unsubscribe paths from a queue (best effort, never raises)."""
|
|
280
|
+
try:
|
|
281
|
+
await self._request(
|
|
282
|
+
"POST",
|
|
283
|
+
"event/modifyQueue",
|
|
284
|
+
payload={
|
|
285
|
+
"queueId": queue_id,
|
|
286
|
+
"subscribe": [],
|
|
287
|
+
"unsubscribe": [
|
|
288
|
+
{"path": p, "type": "itemWithValue"} for p in paths
|
|
289
|
+
],
|
|
290
|
+
},
|
|
291
|
+
)
|
|
292
|
+
except StreamSDKError:
|
|
293
|
+
return
|
aiostreamsdk/events.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Follow value changes of a device through its event queue."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Callable, Iterable
|
|
7
|
+
import logging
|
|
8
|
+
|
|
9
|
+
from .client import StreamSDKClient
|
|
10
|
+
from .exceptions import StreamSDKError
|
|
11
|
+
from .models import Event
|
|
12
|
+
|
|
13
|
+
_LOGGER = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
EventCallback = Callable[[list[Event]], None]
|
|
16
|
+
ConnectionCallback = Callable[[bool], None]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class EventListener:
|
|
20
|
+
"""Subscribe to paths and call back with value changes.
|
|
21
|
+
|
|
22
|
+
:meth:`run` long-polls the device until it is cancelled. When the queue
|
|
23
|
+
is lost (device offline or rebooted, queue expired), it waits
|
|
24
|
+
``retry_delay`` seconds and subscribes again.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
client: StreamSDKClient,
|
|
30
|
+
paths: Iterable[str],
|
|
31
|
+
on_events: EventCallback,
|
|
32
|
+
*,
|
|
33
|
+
on_connection_change: ConnectionCallback | None = None,
|
|
34
|
+
poll_timeout: int = 10,
|
|
35
|
+
retry_delay: float = 5.0,
|
|
36
|
+
) -> None:
|
|
37
|
+
"""Prepare a listener; nothing happens until :meth:`run` is awaited."""
|
|
38
|
+
self._client = client
|
|
39
|
+
self._paths = list(dict.fromkeys(paths))
|
|
40
|
+
self._on_events = on_events
|
|
41
|
+
self._on_connection_change = on_connection_change
|
|
42
|
+
self._poll_timeout = poll_timeout
|
|
43
|
+
self._retry_delay = retry_delay
|
|
44
|
+
self._connected = False
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def connected(self) -> bool:
|
|
48
|
+
"""True while a queue is subscribed and answering."""
|
|
49
|
+
return self._connected
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def paths(self) -> list[str]:
|
|
53
|
+
"""Subscribed paths."""
|
|
54
|
+
return list(self._paths)
|
|
55
|
+
|
|
56
|
+
def _set_connected(self, connected: bool) -> None:
|
|
57
|
+
if connected == self._connected:
|
|
58
|
+
return
|
|
59
|
+
self._connected = connected
|
|
60
|
+
if self._on_connection_change is not None:
|
|
61
|
+
self._on_connection_change(connected)
|
|
62
|
+
|
|
63
|
+
async def run(self) -> None:
|
|
64
|
+
"""Listen until cancelled."""
|
|
65
|
+
queue_id: str | None = None
|
|
66
|
+
try:
|
|
67
|
+
while True:
|
|
68
|
+
try:
|
|
69
|
+
if queue_id is None:
|
|
70
|
+
queue_id = await self._client.create_queue(self._paths)
|
|
71
|
+
self._set_connected(True)
|
|
72
|
+
raw = await self._client.poll_queue(queue_id, self._poll_timeout)
|
|
73
|
+
except StreamSDKError as err:
|
|
74
|
+
if self._connected:
|
|
75
|
+
_LOGGER.debug(
|
|
76
|
+
"Event queue of %s lost (%s), retrying",
|
|
77
|
+
self._client.host,
|
|
78
|
+
err,
|
|
79
|
+
)
|
|
80
|
+
self._set_connected(False)
|
|
81
|
+
queue_id = None
|
|
82
|
+
await asyncio.sleep(self._retry_delay)
|
|
83
|
+
continue
|
|
84
|
+
if raw:
|
|
85
|
+
self._on_events([Event.from_api(item) for item in raw])
|
|
86
|
+
finally:
|
|
87
|
+
self._set_connected(False)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Errors raised by aiostreamsdk."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class StreamSDKError(Exception):
|
|
7
|
+
"""Base error."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class StreamSDKConnectionError(StreamSDKError):
|
|
11
|
+
"""The device could not be reached or did not answer in time."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class StreamSDKApiError(StreamSDKError):
|
|
15
|
+
"""The device answered with an application-level error."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, name: str, message: str) -> None:
|
|
18
|
+
"""Store the StreamSDK error name and message."""
|
|
19
|
+
super().__init__(f"{name}: {message}")
|
|
20
|
+
self.name = name
|
|
21
|
+
self.message = message
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class StreamSDKPathNotFoundError(StreamSDKApiError):
|
|
25
|
+
"""The requested node does not exist on this device."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class StreamSDKNotModifiableError(StreamSDKApiError):
|
|
29
|
+
"""The node exists but cannot be written."""
|
aiostreamsdk/models.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Values, nodes and events of the StreamSDK API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field, replace
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def unwrap(value: Any) -> Any:
|
|
10
|
+
"""Return the plain value of a typed StreamSDK value.
|
|
11
|
+
|
|
12
|
+
``{"type": "i32_", "i32_": 40}`` becomes ``40``. Values without a type
|
|
13
|
+
wrapper (for example ``player:player/data``) are returned unchanged.
|
|
14
|
+
"""
|
|
15
|
+
if isinstance(value, dict):
|
|
16
|
+
type_name = value.get("type")
|
|
17
|
+
if isinstance(type_name, str) and type_name in value:
|
|
18
|
+
return value[type_name]
|
|
19
|
+
return value
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def wrap(type_name: str, value: Any) -> dict[str, Any]:
|
|
23
|
+
"""Build a typed StreamSDK value, e.g. ``wrap("bool_", True)``."""
|
|
24
|
+
return {"type": type_name, type_name: value}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class Node:
|
|
29
|
+
"""A node of the StreamSDK tree with its metadata."""
|
|
30
|
+
|
|
31
|
+
path: str
|
|
32
|
+
type: str
|
|
33
|
+
title: str | None = None
|
|
34
|
+
value: Any = None
|
|
35
|
+
modifiable: bool = False
|
|
36
|
+
edit: dict[str, Any] = field(default_factory=dict)
|
|
37
|
+
unit: str | None = None
|
|
38
|
+
description: str | None = None
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_api(cls, path: str, data: dict[str, Any]) -> Node:
|
|
42
|
+
"""Create a node from a getData/getRows answer."""
|
|
43
|
+
edit = data.get("edit")
|
|
44
|
+
return cls(
|
|
45
|
+
path=str(data.get("path", path)),
|
|
46
|
+
type=str(data.get("type", "value")),
|
|
47
|
+
title=data.get("title"),
|
|
48
|
+
value=data.get("value"),
|
|
49
|
+
modifiable=bool(data.get("modifiable", False)),
|
|
50
|
+
edit=edit if isinstance(edit, dict) else {},
|
|
51
|
+
unit=data.get("valueUnit"),
|
|
52
|
+
description=data.get("description"),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def native(self) -> Any:
|
|
57
|
+
"""The plain value without its type wrapper."""
|
|
58
|
+
return unwrap(self.value)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def value_type(self) -> str | None:
|
|
62
|
+
"""The StreamSDK type of the value, e.g. ``i32_`` or ``bool_``."""
|
|
63
|
+
if isinstance(self.value, dict):
|
|
64
|
+
type_name = self.value.get("type")
|
|
65
|
+
if isinstance(type_name, str):
|
|
66
|
+
return type_name
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def enum_path(self) -> str | None:
|
|
71
|
+
"""Path of the container listing allowed values, if any."""
|
|
72
|
+
if self.edit.get("type") == "enum_" and self.edit.get("enumPath"):
|
|
73
|
+
return str(self.edit["enumPath"])
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
def with_value(self, value: Any) -> Node:
|
|
77
|
+
"""Return a copy of the node with a new value."""
|
|
78
|
+
return replace(self, value=value)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, slots=True)
|
|
82
|
+
class Event:
|
|
83
|
+
"""One entry from an event queue."""
|
|
84
|
+
|
|
85
|
+
path: str
|
|
86
|
+
item_type: str
|
|
87
|
+
value: Any = None
|
|
88
|
+
has_value: bool = False
|
|
89
|
+
rows_events: list[Any] = field(default_factory=list)
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_api(cls, data: dict[str, Any]) -> Event:
|
|
93
|
+
"""Create an event from a pollQueue entry."""
|
|
94
|
+
rows = data.get("rowsEvents")
|
|
95
|
+
return cls(
|
|
96
|
+
path=str(data.get("path", "")),
|
|
97
|
+
item_type=str(data.get("itemType", "")),
|
|
98
|
+
value=data.get("itemValue"),
|
|
99
|
+
has_value="itemValue" in data,
|
|
100
|
+
rows_events=rows if isinstance(rows, list) else [],
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def native(self) -> Any:
|
|
105
|
+
"""The plain new value."""
|
|
106
|
+
return unwrap(self.value)
|
aiostreamsdk/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aiostreamsdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async client for the local HTTP API of StreamUnlimited StreamSDK audio devices (Teufel, Fosi, VSSL, Arcam, ...)
|
|
5
|
+
Project-URL: Homepage, https://github.com/nyxdis/aiostreamsdk
|
|
6
|
+
Project-URL: Issues, https://github.com/nyxdis/aiostreamsdk/issues
|
|
7
|
+
Author: nyxdis
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: asyncio,audio,nsdk,streamsdk,streamunlimited,teufel
|
|
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
|
+
# aiostreamsdk
|
|
27
|
+
|
|
28
|
+
Async Python client for the local HTTP API of audio devices built on
|
|
29
|
+
[StreamUnlimited](https://www.streamunlimited.com/) **StreamSDK** (also called NSDK):
|
|
30
|
+
Teufel Cinebar Pro 2 and Motiv Home, and probably Fosi Audio S3, VSSL MX, Arcam,
|
|
31
|
+
JBL and other streamers with a StreamUnlimited module.
|
|
32
|
+
|
|
33
|
+
The API is undocumented. This library was written against a Teufel Cinebar Pro 2
|
|
34
|
+
(firmware 1.0.201) and a Teufel Motiv Home (firmware 1.0.36). It needs no login:
|
|
35
|
+
anyone on the local network can talk to these devices.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install aiostreamsdk
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Requires Python 3.12+ and aiohttp.
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import asyncio
|
|
49
|
+
|
|
50
|
+
from aiostreamsdk import EventListener, StreamSDKClient, wrap
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def main() -> None:
|
|
54
|
+
async with StreamSDKClient("192.168.1.50") as sdk:
|
|
55
|
+
# Read a node with its metadata
|
|
56
|
+
volume = await sdk.get_node("player:volume")
|
|
57
|
+
print(volume.native, volume.edit) # 26 {'type': 'slider', 'min': '0', ...}
|
|
58
|
+
|
|
59
|
+
# Power
|
|
60
|
+
power = await sdk.get_node("powermanager:target")
|
|
61
|
+
print(power.native["target"]) # "online" or "networkStandby"
|
|
62
|
+
await sdk.wake()
|
|
63
|
+
|
|
64
|
+
# Write a typed value (writes wake the device)
|
|
65
|
+
await sdk.set_value("player:volume", wrap("i32_", 30))
|
|
66
|
+
|
|
67
|
+
# List inputs and play one
|
|
68
|
+
inputs = [r for r in await sdk.get_rows("ui:") if r.get("type") == "audio"]
|
|
69
|
+
await sdk.play_item(inputs[0])
|
|
70
|
+
|
|
71
|
+
# Follow changes
|
|
72
|
+
listener = EventListener(
|
|
73
|
+
sdk,
|
|
74
|
+
["player:volume", "powermanager:target"],
|
|
75
|
+
lambda events: print([(e.path, e.native) for e in events]),
|
|
76
|
+
)
|
|
77
|
+
await listener.run() # until cancelled
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
asyncio.run(main())
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## The API in short
|
|
84
|
+
|
|
85
|
+
| Request | Purpose |
|
|
86
|
+
|---|---|
|
|
87
|
+
| `GET /api/getData?path=<p>&roles=@all` | Read a node (value, title, `modifiable`, `edit` limits or `enumPath`) |
|
|
88
|
+
| `GET /api/getRows?path=<p>&roles=@all&from=0&to=100` | List a container (inputs at `ui:`, settings at `settings:/`) |
|
|
89
|
+
| `POST /api/setData` `{"path", "role": "value", "value"}` | Write a typed value such as `{"type": "i32_", "i32_": 30}` |
|
|
90
|
+
| `POST /api/setData` `{"path", "role": "activate", "value"}` | Trigger an action, e.g. `powermanager:goOnline` |
|
|
91
|
+
| `POST /api/event/modifyQueue` / `GET /api/event/pollQueue` | Subscribe to and long-poll value changes |
|
|
92
|
+
|
|
93
|
+
Useful paths: `powermanager:target` (power state), `powermanager:goOnline` /
|
|
94
|
+
`goNetworkStandby` / `goReboot`, `player:volume`, `settings:/mediaPlayer/mute`,
|
|
95
|
+
`player:player/data` (player state and current item), `player:player/control`
|
|
96
|
+
(play, pause, stop, next, previous). Which other nodes exist depends on the model;
|
|
97
|
+
`get_nodes()` skips the ones a device does not have.
|
|
98
|
+
|
|
99
|
+
## Development
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
uv sync
|
|
103
|
+
uv run ruff format . && uv run ruff check . && uv run mypy && uv run pytest
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Releases are published to PyPI from GitHub releases via Trusted Publishing.
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
aiostreamsdk/__init__.py,sha256=4A2M38xMpfuNdmwPhkvhafPp2Mi30TQ22Hf5QkH5PTA,1062
|
|
2
|
+
aiostreamsdk/client.py,sha256=dqMRCSU9OoITj945mmXp-xpIdfx4oUOkUCV1vFrhW9A,10159
|
|
3
|
+
aiostreamsdk/events.py,sha256=7Ws48K4ptzwr8E6DOT_Ktu9oQUGkow4THhuZmjDh4Vg,2905
|
|
4
|
+
aiostreamsdk/exceptions.py,sha256=eY5bc-hqystjkrsSp3j0PSSgLjQMU9C_4ykLvbOUlA8,794
|
|
5
|
+
aiostreamsdk/models.py,sha256=QZxaYaWnqSOLjgfoHF-yAAhydQRsN-Ug0TB9fjVUK-M,3330
|
|
6
|
+
aiostreamsdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
aiostreamsdk-0.1.0.dist-info/METADATA,sha256=O8pSwQJ3SANTmGX8sq5xM39pXjBTygyQrGui37MRS9o,3918
|
|
8
|
+
aiostreamsdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
aiostreamsdk-0.1.0.dist-info/licenses/LICENSE,sha256=qWIr9jbW7aCU_GT3ylslrpKVEa3_XijqntVdA7bpJLE,1063
|
|
10
|
+
aiostreamsdk-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.
|