nad-serial 0.0.1__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.
- nad_serial/__init__.py +1085 -0
- nad_serial/_version.py +24 -0
- nad_serial/configs/README.md +133 -0
- nad_serial/configs/__init__.py +115 -0
- nad_serial/configs/amplifier.json +28 -0
- nad_serial/configs/c328.json +60 -0
- nad_serial/configs/c338.json +76 -0
- nad_serial/configs/c356.json +55 -0
- nad_serial/configs/c368.json +519 -0
- nad_serial/configs/c388.json +519 -0
- nad_serial/configs/c427.json +41 -0
- nad_serial/configs/dab.json +21 -0
- nad_serial/configs/device.json +37 -0
- nad_serial/configs/m15hd.json +2432 -0
- nad_serial/configs/m17.json +2388 -0
- nad_serial/configs/m51.json +38 -0
- nad_serial/configs/pg536m.json +41 -0
- nad_serial/configs/py.typed +0 -0
- nad_serial/configs/t175.json +2198 -0
- nad_serial/configs/t187.json +2631 -0
- nad_serial/configs/t755.json +1934 -0
- nad_serial/configs/t757.json +2348 -0
- nad_serial/configs/t758.json +2346 -0
- nad_serial/configs/t765.json +2207 -0
- nad_serial/configs/t775.json +2228 -0
- nad_serial/configs/t777.json +2659 -0
- nad_serial/configs/t778.json +2204 -0
- nad_serial/configs/t785.json +2228 -0
- nad_serial/configs/t787.json +2659 -0
- nad_serial/configs/tuner.json +64 -0
- nad_serial/configs/vxp.json +89 -0
- nad_serial/configs/xm.json +33 -0
- nad_serial/configs/zones.json +54 -0
- nad_serial/exceptions.py +33 -0
- nad_serial/helpers.py +135 -0
- nad_serial/py.typed +0 -0
- nad_serial-0.0.1.dist-info/METADATA +208 -0
- nad_serial-0.0.1.dist-info/RECORD +40 -0
- nad_serial-0.0.1.dist-info/WHEEL +4 -0
- nad_serial-0.0.1.dist-info/licenses/LICENSE.md +201 -0
nad_serial/__init__.py
ADDED
|
@@ -0,0 +1,1085 @@
|
|
|
1
|
+
"""The NAD Serial library."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Callable, Iterable
|
|
5
|
+
import contextlib
|
|
6
|
+
import logging
|
|
7
|
+
import math
|
|
8
|
+
from typing import Any, Final, override
|
|
9
|
+
|
|
10
|
+
import serialx
|
|
11
|
+
from serialx import SerialException
|
|
12
|
+
from serialx.common import Parity, StopBits
|
|
13
|
+
|
|
14
|
+
from .configs import async_read_device_config
|
|
15
|
+
from .exceptions import (
|
|
16
|
+
NADBaseError,
|
|
17
|
+
NADCommandError,
|
|
18
|
+
NADConnectionError,
|
|
19
|
+
NADResponseError,
|
|
20
|
+
NADTimeoutError,
|
|
21
|
+
)
|
|
22
|
+
from .helpers import (
|
|
23
|
+
REPORT_MESSAGE,
|
|
24
|
+
ValueType,
|
|
25
|
+
build_command,
|
|
26
|
+
parse_response,
|
|
27
|
+
parse_value,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
with contextlib.suppress(ModuleNotFoundError):
|
|
31
|
+
from ._version import __version__ as __version__
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_LINE_ENDINGS = (b"\r", b"\n", b"\x00")
|
|
35
|
+
|
|
36
|
+
TIMEOUT = 1.0
|
|
37
|
+
SETUP_TIMEOUT = 0.5
|
|
38
|
+
|
|
39
|
+
_DEVICE_TYPE_DETECTION_SETTINGS: Final = {
|
|
40
|
+
"model": "Main.Model",
|
|
41
|
+
"build": "Main.Build",
|
|
42
|
+
"version": "Main.Version",
|
|
43
|
+
"amplifier": "Main.Volume",
|
|
44
|
+
"tuner": "Tuner.Band",
|
|
45
|
+
"zones": "Zone2.Power",
|
|
46
|
+
}
|
|
47
|
+
_BASE_SETTINGS: Final = (
|
|
48
|
+
"Main.Build",
|
|
49
|
+
"Main.Model",
|
|
50
|
+
"Main.Serial",
|
|
51
|
+
"Main.SerialNumber",
|
|
52
|
+
"Main.Version",
|
|
53
|
+
"Main.Power",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class NADDevice:
|
|
60
|
+
"""A minimal NAD device."""
|
|
61
|
+
|
|
62
|
+
# The prefix of the device settings.
|
|
63
|
+
_prefix = "Main"
|
|
64
|
+
|
|
65
|
+
# The connection to the device
|
|
66
|
+
_connection: serialx.AsyncSerial
|
|
67
|
+
# The NAD build, e.g. T755_
|
|
68
|
+
_build: str | None = None
|
|
69
|
+
_device_type: str = "device"
|
|
70
|
+
# The device configuration
|
|
71
|
+
_device_config: dict[str, Any]
|
|
72
|
+
|
|
73
|
+
# The state of the settings
|
|
74
|
+
_setting_states: dict[str, ValueType | None]
|
|
75
|
+
_supported_settings: list[str]
|
|
76
|
+
|
|
77
|
+
_callbacks: list[Callable[[str, ValueType | None], None]]
|
|
78
|
+
|
|
79
|
+
# Whether the device sends updates on its own.
|
|
80
|
+
_sends_updates: bool | None = None
|
|
81
|
+
|
|
82
|
+
_request_lock: asyncio.Lock
|
|
83
|
+
_reader_task: asyncio.Task[None] | None = None
|
|
84
|
+
_pending_request: tuple[str, asyncio.Future[ValueType | None]] | None = None
|
|
85
|
+
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
connection: serialx.AsyncSerial,
|
|
89
|
+
build: str | None,
|
|
90
|
+
device_config: dict[str, Any],
|
|
91
|
+
):
|
|
92
|
+
"""Initializes a NAD device."""
|
|
93
|
+
self._connection = connection
|
|
94
|
+
self._build = build
|
|
95
|
+
self._device_config = device_config
|
|
96
|
+
self._setting_states = {}
|
|
97
|
+
self._supported_settings = []
|
|
98
|
+
self._callbacks = []
|
|
99
|
+
|
|
100
|
+
self._request_lock = asyncio.Lock()
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def connected(self) -> bool:
|
|
104
|
+
"""If there is a connection to the device."""
|
|
105
|
+
return self._connection.is_open
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def model(self) -> str | None:
|
|
109
|
+
"""The device model."""
|
|
110
|
+
return self._build.split("_")[0] if self._build is not None else None
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def build(self) -> str | None:
|
|
114
|
+
"""The device build."""
|
|
115
|
+
return self._build
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def name(self) -> str:
|
|
119
|
+
"""The device name."""
|
|
120
|
+
return f"NAD {self.model or self._device_type}"
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def firmware_version(self) -> str | None:
|
|
124
|
+
"""The firmware version."""
|
|
125
|
+
value = self.get_setting_value("Main.Version")
|
|
126
|
+
return str(value) if value else None
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def serial_number(self) -> str | None:
|
|
130
|
+
"""The serial number."""
|
|
131
|
+
value = self.get_setting_value("Main.Serial")
|
|
132
|
+
if not value:
|
|
133
|
+
value = self.get_setting_value("Main.SerialNumber")
|
|
134
|
+
return str(value) if value else None
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def sends_updates(self) -> bool:
|
|
138
|
+
"""If the device sends updates by itself."""
|
|
139
|
+
return bool(self._sends_updates)
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def supported_settings(self) -> list[str]:
|
|
143
|
+
"""The by the device supported settings."""
|
|
144
|
+
return self._supported_settings
|
|
145
|
+
|
|
146
|
+
def supports_setting(self, setting: str) -> bool:
|
|
147
|
+
"""Returns True if the given setting is supported."""
|
|
148
|
+
return self.get_setting_config(setting) is not None
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
async def _async_request_setting_value(
|
|
152
|
+
setting: str, connection: serialx.AsyncSerial
|
|
153
|
+
) -> ValueType | None:
|
|
154
|
+
command = build_command(setting, "?")
|
|
155
|
+
try:
|
|
156
|
+
# Empty read buffer
|
|
157
|
+
with contextlib.suppress(TimeoutError):
|
|
158
|
+
while True:
|
|
159
|
+
async with asyncio.timeout(0.05):
|
|
160
|
+
if not await connection.read(1024):
|
|
161
|
+
break
|
|
162
|
+
|
|
163
|
+
await connection.write(f"\r{command}\r".encode("ascii"))
|
|
164
|
+
|
|
165
|
+
async with asyncio.timeout(TIMEOUT):
|
|
166
|
+
while True:
|
|
167
|
+
try:
|
|
168
|
+
response = await connection.readuntil(_LINE_ENDINGS) # type: ignore[arg-type]
|
|
169
|
+
except asyncio.LimitOverrunError as ex:
|
|
170
|
+
logger.debug("Ignoring %d bytes", ex.consumed)
|
|
171
|
+
await connection.readexactly(ex.consumed)
|
|
172
|
+
continue
|
|
173
|
+
response_setting, response_value = parse_response(response)
|
|
174
|
+
if response_setting and response_setting.lower() == setting.lower():
|
|
175
|
+
return response_value
|
|
176
|
+
except TimeoutError:
|
|
177
|
+
return None
|
|
178
|
+
except (OSError, SerialException, asyncio.IncompleteReadError) as ex:
|
|
179
|
+
with contextlib.suppress(OSError, SerialException):
|
|
180
|
+
await connection.close()
|
|
181
|
+
raise NADConnectionError("Disconnected") from ex
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
async def async_connect(
|
|
185
|
+
url: str,
|
|
186
|
+
*,
|
|
187
|
+
build_hint: str | None = None,
|
|
188
|
+
) -> NADDevice:
|
|
189
|
+
"""Connects to the device and returns one of the NAD device classes."""
|
|
190
|
+
try:
|
|
191
|
+
connection = serialx.async_serial_for_url(
|
|
192
|
+
url,
|
|
193
|
+
baudrate=115200,
|
|
194
|
+
byte_size=8,
|
|
195
|
+
parity=Parity.NONE,
|
|
196
|
+
stopbits=StopBits.ONE,
|
|
197
|
+
write_timeout=TIMEOUT,
|
|
198
|
+
read_timeout=TIMEOUT,
|
|
199
|
+
)
|
|
200
|
+
await connection.open()
|
|
201
|
+
except (OSError, SerialException, ValueError, RuntimeError) as ex:
|
|
202
|
+
raise NADConnectionError(f"Unable to connect to {url}") from ex
|
|
203
|
+
|
|
204
|
+
build = await NADDevice._async_request_setting_value(
|
|
205
|
+
_DEVICE_TYPE_DETECTION_SETTINGS["build"], connection
|
|
206
|
+
)
|
|
207
|
+
if not build:
|
|
208
|
+
build = await NADDevice._async_request_setting_value(
|
|
209
|
+
_DEVICE_TYPE_DETECTION_SETTINGS["model"], connection
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
if not isinstance(build, str):
|
|
213
|
+
build = build_hint
|
|
214
|
+
|
|
215
|
+
if not build:
|
|
216
|
+
with contextlib.suppress(OSError, SerialException):
|
|
217
|
+
await connection.close()
|
|
218
|
+
raise NADConnectionError(f"Unable to connect to {url}")
|
|
219
|
+
|
|
220
|
+
value = await NADDevice._async_request_setting_value(
|
|
221
|
+
_DEVICE_TYPE_DETECTION_SETTINGS["version"], connection
|
|
222
|
+
)
|
|
223
|
+
version = value if isinstance(value, str) else None
|
|
224
|
+
|
|
225
|
+
device_config = await async_read_device_config(build, version=version)
|
|
226
|
+
|
|
227
|
+
detected_device_types = None
|
|
228
|
+
if not device_config or "device_types" not in device_config:
|
|
229
|
+
detected_device_types = []
|
|
230
|
+
for (
|
|
231
|
+
device_type,
|
|
232
|
+
detection_setting,
|
|
233
|
+
) in _DEVICE_TYPE_DETECTION_SETTINGS.items():
|
|
234
|
+
if device_type in ["model", "build", "version"]:
|
|
235
|
+
continue
|
|
236
|
+
|
|
237
|
+
value = await NADDevice._async_request_setting_value(
|
|
238
|
+
detection_setting, connection
|
|
239
|
+
)
|
|
240
|
+
if value:
|
|
241
|
+
detected_device_types.append(device_type)
|
|
242
|
+
|
|
243
|
+
device_config = await async_read_device_config(
|
|
244
|
+
build, detected_device_types, version
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
if detected_device_types is not None:
|
|
248
|
+
logger.warning(
|
|
249
|
+
"No device configuration found for NAD %s with detected device types %s. %s",
|
|
250
|
+
build,
|
|
251
|
+
detected_device_types,
|
|
252
|
+
REPORT_MESSAGE,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
device: NADDevice
|
|
256
|
+
device_types = device_config.get("device_types", [])
|
|
257
|
+
if (
|
|
258
|
+
"zones" in device_types
|
|
259
|
+
and "amplifier" in device_types
|
|
260
|
+
and "tuner" in device_types
|
|
261
|
+
):
|
|
262
|
+
device = NADMultiZoneReceiver(connection, build, device_config)
|
|
263
|
+
elif "amplifier" in device_types and "tuner" in device_types:
|
|
264
|
+
device = NADReceiver(connection, build, device_config)
|
|
265
|
+
elif "zones" in device_types and "amplifier" in device_types:
|
|
266
|
+
device = NADMultiZoneAmplifier(connection, build, device_config)
|
|
267
|
+
elif "amplifier" in device_types:
|
|
268
|
+
device = NADAmplifier(connection, build, device_config)
|
|
269
|
+
elif "tuner" in device_types:
|
|
270
|
+
device = NADTuner(connection, build, device_config)
|
|
271
|
+
else:
|
|
272
|
+
device = NADDevice(connection, build, device_config)
|
|
273
|
+
|
|
274
|
+
try:
|
|
275
|
+
await device._async_setup()
|
|
276
|
+
except NADBaseError:
|
|
277
|
+
await device.async_disconnect()
|
|
278
|
+
raise
|
|
279
|
+
except Exception as ex:
|
|
280
|
+
await device.async_disconnect()
|
|
281
|
+
raise NADConnectionError("Disconnected") from ex
|
|
282
|
+
|
|
283
|
+
return device
|
|
284
|
+
|
|
285
|
+
async def async_disconnect(self) -> None:
|
|
286
|
+
"""Closes the connection."""
|
|
287
|
+
await self._async_stop_reader()
|
|
288
|
+
|
|
289
|
+
if self._pending_request is not None and not self._pending_request[1].done():
|
|
290
|
+
self._pending_request[1].set_exception(NADConnectionError("Disconnected"))
|
|
291
|
+
self._pending_request = None
|
|
292
|
+
|
|
293
|
+
with contextlib.suppress(OSError, SerialException):
|
|
294
|
+
await self._connection.close()
|
|
295
|
+
|
|
296
|
+
async def async_reconnect(self) -> None:
|
|
297
|
+
"""Reconnects the connection."""
|
|
298
|
+
await self.async_disconnect()
|
|
299
|
+
try:
|
|
300
|
+
await self._connection.open()
|
|
301
|
+
except (OSError, SerialException, ValueError, RuntimeError) as ex:
|
|
302
|
+
raise NADConnectionError(f"Unable to connect to NAD {self.model}") from ex
|
|
303
|
+
self._start_reader()
|
|
304
|
+
|
|
305
|
+
# Read settings from the device
|
|
306
|
+
await self.async_request_settings(list(self._setting_states))
|
|
307
|
+
|
|
308
|
+
async def async_ping(self) -> bool:
|
|
309
|
+
"""Sends a message to the device to see if the connection is still up."""
|
|
310
|
+
try:
|
|
311
|
+
value = await self.async_request_setting("Main.Power")
|
|
312
|
+
except NADTimeoutError, NADConnectionError:
|
|
313
|
+
pass
|
|
314
|
+
else:
|
|
315
|
+
return value is not None
|
|
316
|
+
|
|
317
|
+
return False
|
|
318
|
+
|
|
319
|
+
def add_callback(
|
|
320
|
+
self, callback: Callable[[str, ValueType | None], None]
|
|
321
|
+
) -> Callable[[], None]:
|
|
322
|
+
"""Adds a callback."""
|
|
323
|
+
self._callbacks.append(callback)
|
|
324
|
+
|
|
325
|
+
def remove_callback() -> None:
|
|
326
|
+
with contextlib.suppress(ValueError):
|
|
327
|
+
self._callbacks.remove(callback)
|
|
328
|
+
|
|
329
|
+
return remove_callback
|
|
330
|
+
|
|
331
|
+
def _update_callbacks(self, setting: str, value: ValueType | None) -> None:
|
|
332
|
+
for callback in self._callbacks.copy():
|
|
333
|
+
try:
|
|
334
|
+
callback(setting, value)
|
|
335
|
+
except Exception:
|
|
336
|
+
logger.exception("Exception in callback: %s", callback)
|
|
337
|
+
|
|
338
|
+
async def _async_setup(self) -> None:
|
|
339
|
+
"""Setup the NAD device."""
|
|
340
|
+
self._sends_updates = self._device_config.get("sends_updates")
|
|
341
|
+
|
|
342
|
+
self._supported_settings = list(self._device_config["settings"].keys())
|
|
343
|
+
|
|
344
|
+
# Lowercase the setting names
|
|
345
|
+
self._device_config["settings"] = {
|
|
346
|
+
setting.lower(): config
|
|
347
|
+
for setting, config in self._device_config["settings"].items()
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
# Start the reader
|
|
351
|
+
self._start_reader()
|
|
352
|
+
|
|
353
|
+
# Read base settings from the device
|
|
354
|
+
await self.async_request_settings(_BASE_SETTINGS)
|
|
355
|
+
|
|
356
|
+
# Choose which option of max, min and step is used
|
|
357
|
+
for config in self._device_config["settings"].values():
|
|
358
|
+
for key in ("min", "max", "step"):
|
|
359
|
+
if (reference := config.get(key)) is None:
|
|
360
|
+
continue
|
|
361
|
+
if (choice := await self._async_choose_reference(reference)) is None:
|
|
362
|
+
del config[key]
|
|
363
|
+
else:
|
|
364
|
+
config[key] = choice
|
|
365
|
+
|
|
366
|
+
async def _async_choose_reference(
|
|
367
|
+
self, reference: float | str | list[int | float | str]
|
|
368
|
+
) -> int | float | str | None:
|
|
369
|
+
"""Returns the first option that gives a number: a number, or the name of a setting."""
|
|
370
|
+
for item in reference if isinstance(reference, list) else [reference]:
|
|
371
|
+
if not isinstance(item, str):
|
|
372
|
+
return item
|
|
373
|
+
if (value := self.get_setting_value(item)) is None:
|
|
374
|
+
with contextlib.suppress(TimeoutError, NADTimeoutError):
|
|
375
|
+
async with asyncio.timeout(SETUP_TIMEOUT):
|
|
376
|
+
value = await self.async_request_setting(item)
|
|
377
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
378
|
+
return item # the name, so later changes are followed
|
|
379
|
+
return None
|
|
380
|
+
|
|
381
|
+
def get_setting_config(self, setting: str) -> dict[str, Any] | None:
|
|
382
|
+
"""Gets the configuration for a setting, with min, max and step resolved to numbers.
|
|
383
|
+
|
|
384
|
+
A min, max or step that refers to another setting takes that setting's current value. It is
|
|
385
|
+
left out when that setting has no number value.
|
|
386
|
+
"""
|
|
387
|
+
settings: dict[str, dict[str, Any]] = self._device_config["settings"]
|
|
388
|
+
if (config := settings.get(setting.lower())) is None:
|
|
389
|
+
return None
|
|
390
|
+
|
|
391
|
+
references = [
|
|
392
|
+
key for key in ("min", "max", "step") if isinstance(config.get(key), str)
|
|
393
|
+
]
|
|
394
|
+
if not references:
|
|
395
|
+
return config
|
|
396
|
+
|
|
397
|
+
resolved = dict(config)
|
|
398
|
+
for key in references:
|
|
399
|
+
value = self.get_setting_value(config[key])
|
|
400
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
401
|
+
resolved[key] = value
|
|
402
|
+
else:
|
|
403
|
+
del resolved[key]
|
|
404
|
+
return resolved
|
|
405
|
+
|
|
406
|
+
def get_setting_value(self, setting: str) -> ValueType | None:
|
|
407
|
+
"""Gets the value of a setting from the setting state dict."""
|
|
408
|
+
return self._setting_states.get(setting.lower())
|
|
409
|
+
|
|
410
|
+
def _parse_response(self, response: bytes) -> tuple[str | None, ValueType | None]:
|
|
411
|
+
setting, value = parse_response(response)
|
|
412
|
+
if setting is None or value is None:
|
|
413
|
+
return None, None
|
|
414
|
+
if (setting_config := self.get_setting_config(setting)) is None:
|
|
415
|
+
return setting, value
|
|
416
|
+
return setting, parse_value(setting, value, setting_config)
|
|
417
|
+
|
|
418
|
+
async def _reader_loop(self) -> None:
|
|
419
|
+
"""Reads all data sent by the device."""
|
|
420
|
+
try:
|
|
421
|
+
while True:
|
|
422
|
+
try:
|
|
423
|
+
response = await self._connection.readuntil(_LINE_ENDINGS) # type: ignore[arg-type]
|
|
424
|
+
except TimeoutError:
|
|
425
|
+
continue
|
|
426
|
+
except asyncio.IncompleteReadError as ex:
|
|
427
|
+
raise NADConnectionError("Connection closed by device") from ex
|
|
428
|
+
except asyncio.LimitOverrunError as ex:
|
|
429
|
+
logger.debug("Ignoring %d bytes", ex.consumed)
|
|
430
|
+
await self._connection.readexactly(ex.consumed)
|
|
431
|
+
continue
|
|
432
|
+
|
|
433
|
+
if not (response := response.strip(b" \t\r\n\x00")):
|
|
434
|
+
continue
|
|
435
|
+
|
|
436
|
+
logger.debug("Received %s", response)
|
|
437
|
+
setting, value = self._parse_response(response)
|
|
438
|
+
if not setting:
|
|
439
|
+
continue
|
|
440
|
+
|
|
441
|
+
setting_lc = setting.lower()
|
|
442
|
+
if setting_lc in self._device_config["settings"]:
|
|
443
|
+
self._setting_states[setting_lc] = value
|
|
444
|
+
|
|
445
|
+
if (
|
|
446
|
+
self._pending_request
|
|
447
|
+
and self._pending_request[0] == setting_lc
|
|
448
|
+
and not self._pending_request[1].done()
|
|
449
|
+
):
|
|
450
|
+
# Response to a request
|
|
451
|
+
self._pending_request[1].set_result(value)
|
|
452
|
+
continue
|
|
453
|
+
|
|
454
|
+
if not (
|
|
455
|
+
self._pending_request and self._pending_request[0] == setting_lc
|
|
456
|
+
):
|
|
457
|
+
# Device-initiated updates
|
|
458
|
+
if self._sends_updates is None:
|
|
459
|
+
logger.warning(
|
|
460
|
+
"The NAD %s reports changes on its own, but its configuration doesn't say so. %s",
|
|
461
|
+
self.model,
|
|
462
|
+
REPORT_MESSAGE,
|
|
463
|
+
)
|
|
464
|
+
self._sends_updates = True
|
|
465
|
+
|
|
466
|
+
if (
|
|
467
|
+
setting_lc not in self._device_config["settings"]
|
|
468
|
+
and setting_lc not in self._setting_states
|
|
469
|
+
):
|
|
470
|
+
self._setting_states[setting_lc] = value
|
|
471
|
+
logger.warning(
|
|
472
|
+
"The NAD %s reported a new setting %s = %s that is not in its configuration. %s",
|
|
473
|
+
self.model,
|
|
474
|
+
setting,
|
|
475
|
+
value,
|
|
476
|
+
REPORT_MESSAGE,
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
self._update_callbacks(setting, value)
|
|
480
|
+
except asyncio.CancelledError:
|
|
481
|
+
raise
|
|
482
|
+
except Exception as ex:
|
|
483
|
+
logger.exception("Connection to NAD %s lost", self.model)
|
|
484
|
+
|
|
485
|
+
if (
|
|
486
|
+
self._pending_request is not None
|
|
487
|
+
and not self._pending_request[1].done()
|
|
488
|
+
):
|
|
489
|
+
self._pending_request[1].set_exception(
|
|
490
|
+
ex if isinstance(ex, NADBaseError) else NADConnectionError(str(ex))
|
|
491
|
+
)
|
|
492
|
+
self._pending_request = None
|
|
493
|
+
|
|
494
|
+
with contextlib.suppress(OSError, SerialException):
|
|
495
|
+
await self._connection.close()
|
|
496
|
+
|
|
497
|
+
def _start_reader(self) -> None:
|
|
498
|
+
if self._reader_task is None or self._reader_task.done():
|
|
499
|
+
self._reader_task = asyncio.create_task(
|
|
500
|
+
self._reader_loop(), name=f"NAD {self.model} reader"
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
async def _async_stop_reader(self) -> None:
|
|
504
|
+
task, self._reader_task = self._reader_task, None
|
|
505
|
+
if task is not None:
|
|
506
|
+
task.cancel()
|
|
507
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
508
|
+
await task
|
|
509
|
+
|
|
510
|
+
async def _async_request(
|
|
511
|
+
self,
|
|
512
|
+
setting: str,
|
|
513
|
+
operator: str,
|
|
514
|
+
value: ValueType | None = None,
|
|
515
|
+
setting_config: dict[str, Any] | None = None,
|
|
516
|
+
) -> ValueType | None:
|
|
517
|
+
"""Sends a request and waits for the response."""
|
|
518
|
+
if not self.connected:
|
|
519
|
+
raise NADConnectionError("Not connected")
|
|
520
|
+
|
|
521
|
+
if not setting_config:
|
|
522
|
+
setting_config = self.get_setting_config(setting)
|
|
523
|
+
if not setting_config:
|
|
524
|
+
return None
|
|
525
|
+
|
|
526
|
+
command = build_command(setting, operator, value, setting_config)
|
|
527
|
+
request = f"\r{command}\r"
|
|
528
|
+
|
|
529
|
+
# The device doesn't respond to settings that can't be queried
|
|
530
|
+
wait_for_response = "?" in setting_config["operators"]
|
|
531
|
+
|
|
532
|
+
async with self._request_lock:
|
|
533
|
+
loop = asyncio.get_running_loop()
|
|
534
|
+
future = loop.create_future()
|
|
535
|
+
|
|
536
|
+
logger.debug("Sending %s", request.strip())
|
|
537
|
+
try:
|
|
538
|
+
# The connection can be lost while waiting for the lock.
|
|
539
|
+
if not self.connected:
|
|
540
|
+
raise NADConnectionError("Not connected")
|
|
541
|
+
if not wait_for_response:
|
|
542
|
+
await self._connection.write(request.encode("ascii"))
|
|
543
|
+
return None
|
|
544
|
+
self._pending_request = (setting.lower(), future)
|
|
545
|
+
await self._connection.write(request.encode("ascii"))
|
|
546
|
+
return await asyncio.wait_for(future, TIMEOUT)
|
|
547
|
+
except TimeoutError as ex:
|
|
548
|
+
raise NADTimeoutError(
|
|
549
|
+
f"No response from device on {request.strip()}"
|
|
550
|
+
) from ex
|
|
551
|
+
except (OSError, SerialException) as ex:
|
|
552
|
+
with contextlib.suppress(OSError, SerialException):
|
|
553
|
+
await self._connection.close()
|
|
554
|
+
raise NADConnectionError(f"Unable to send {request.strip()}") from ex
|
|
555
|
+
finally:
|
|
556
|
+
if (
|
|
557
|
+
self._pending_request is not None
|
|
558
|
+
and self._pending_request[1] is future
|
|
559
|
+
):
|
|
560
|
+
self._pending_request = None
|
|
561
|
+
|
|
562
|
+
async def async_request(
|
|
563
|
+
self, setting: str, operator: str, value: str | None = None
|
|
564
|
+
) -> ValueType | None:
|
|
565
|
+
"""Send a request to the device, also for settings without configuration."""
|
|
566
|
+
return await self._async_request(
|
|
567
|
+
setting,
|
|
568
|
+
operator,
|
|
569
|
+
value,
|
|
570
|
+
setting_config={"type": "string", "operators": ["=", "+", "-", "?"]},
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
async def async_request_setting(self, setting: str) -> ValueType | None:
|
|
574
|
+
"""Gets the value of a setting from the device."""
|
|
575
|
+
return await self._async_request(setting, "?")
|
|
576
|
+
|
|
577
|
+
async def async_request_settings(
|
|
578
|
+
self, settings: Iterable[str]
|
|
579
|
+
) -> dict[str, ValueType | None]:
|
|
580
|
+
"""Gets the values of the given settings from the device."""
|
|
581
|
+
values: dict[str, ValueType | None] = {}
|
|
582
|
+
consecutive_response_failures = 0
|
|
583
|
+
for setting in settings:
|
|
584
|
+
config = self.get_setting_config(setting)
|
|
585
|
+
if not config or "?" not in config["operators"]:
|
|
586
|
+
# Unknown setting, or the device doesn't support querying it
|
|
587
|
+
continue
|
|
588
|
+
|
|
589
|
+
try:
|
|
590
|
+
async with asyncio.timeout(SETUP_TIMEOUT):
|
|
591
|
+
value = await self.async_request_setting(setting)
|
|
592
|
+
values[setting] = value
|
|
593
|
+
consecutive_response_failures = 0
|
|
594
|
+
except (TimeoutError, NADTimeoutError) as ex:
|
|
595
|
+
logger.debug("No response for %s", setting)
|
|
596
|
+
consecutive_response_failures += 1
|
|
597
|
+
if consecutive_response_failures >= 5:
|
|
598
|
+
raise NADConnectionError("No response") from ex
|
|
599
|
+
|
|
600
|
+
return values
|
|
601
|
+
|
|
602
|
+
async def async_change_setting(self, setting: str, value: ValueType) -> bool:
|
|
603
|
+
"""Change a setting."""
|
|
604
|
+
if not (setting_config := self.get_setting_config(setting)):
|
|
605
|
+
raise NADCommandError(
|
|
606
|
+
f"Setting {setting} is not supported by NAD {self.model}"
|
|
607
|
+
)
|
|
608
|
+
if (
|
|
609
|
+
setting_config["type"] != "number"
|
|
610
|
+
and "=" not in setting_config["operators"]
|
|
611
|
+
):
|
|
612
|
+
raise NADCommandError(f"Changing {setting} not allowed")
|
|
613
|
+
if setting_config["type"] == "number" and setting_config["operators"] == "?":
|
|
614
|
+
raise NADCommandError(f"Changing {setting} not allowed")
|
|
615
|
+
if (
|
|
616
|
+
setting_config["type"] == "number"
|
|
617
|
+
and "=" not in setting_config["operators"]
|
|
618
|
+
and "?" not in setting_config["operators"]
|
|
619
|
+
):
|
|
620
|
+
# We can't step to the value if we can't know the current value.
|
|
621
|
+
raise NADCommandError(f"Changing {setting} not possible")
|
|
622
|
+
if setting_config["type"] == "number":
|
|
623
|
+
minimum = setting_config.get("min")
|
|
624
|
+
maximum = setting_config.get("max")
|
|
625
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
626
|
+
raise NADCommandError(f"{value} not a number")
|
|
627
|
+
number: float = value
|
|
628
|
+
if "=" not in setting_config["operators"] and (
|
|
629
|
+
(minimum is not None and number < minimum)
|
|
630
|
+
or (maximum is not None and number > maximum)
|
|
631
|
+
):
|
|
632
|
+
raise NADCommandError(f"{value} out of range {minimum} - {maximum}")
|
|
633
|
+
if setting_config["type"] == "boolean" and not isinstance(value, bool):
|
|
634
|
+
raise NADCommandError(f"{value} not a boolean")
|
|
635
|
+
|
|
636
|
+
if (
|
|
637
|
+
setting_config["type"] == "number"
|
|
638
|
+
and "=" not in setting_config["operators"]
|
|
639
|
+
):
|
|
640
|
+
# Numerical can not directly be set but needs to be stepped to.
|
|
641
|
+
current_value = self.get_setting_value(setting)
|
|
642
|
+
if isinstance(current_value, bool) or not isinstance(
|
|
643
|
+
current_value, (int, float)
|
|
644
|
+
):
|
|
645
|
+
raise NADResponseError("Invalid current value")
|
|
646
|
+
if current_value == number:
|
|
647
|
+
return True
|
|
648
|
+
|
|
649
|
+
step = setting_config.get("step", 1)
|
|
650
|
+
direction = "+" if current_value < number else "-"
|
|
651
|
+
needed_steps = math.ceil(abs(number - current_value) / step)
|
|
652
|
+
for _ in range(needed_steps + 1):
|
|
653
|
+
current_value = await self._async_request(setting, direction, None)
|
|
654
|
+
if isinstance(current_value, bool) or not isinstance(
|
|
655
|
+
current_value, (int, float)
|
|
656
|
+
):
|
|
657
|
+
raise NADResponseError("Unexpected response")
|
|
658
|
+
if current_value == number:
|
|
659
|
+
break
|
|
660
|
+
if direction == "+" and current_value > number:
|
|
661
|
+
break
|
|
662
|
+
if direction == "-" and current_value < number:
|
|
663
|
+
break
|
|
664
|
+
else:
|
|
665
|
+
current_value = await self._async_request(setting, "=", value)
|
|
666
|
+
if "?" not in setting_config["operators"]:
|
|
667
|
+
# The device doesn't respond, the change can't be verified
|
|
668
|
+
return True
|
|
669
|
+
|
|
670
|
+
if setting_config["type"] == "number":
|
|
671
|
+
return isinstance(current_value, (int, float)) and math.isclose(
|
|
672
|
+
current_value, number, abs_tol=1e-9
|
|
673
|
+
)
|
|
674
|
+
if setting_config["type"] == "enum" and isinstance(value, str):
|
|
675
|
+
return (
|
|
676
|
+
isinstance(current_value, str)
|
|
677
|
+
and current_value.lower() == value.lower()
|
|
678
|
+
)
|
|
679
|
+
return current_value == value
|
|
680
|
+
|
|
681
|
+
async def _async_step(self, setting: str, operator: str) -> bool:
|
|
682
|
+
current_value = self.get_setting_value(setting)
|
|
683
|
+
new_value = await self._async_request(setting, operator)
|
|
684
|
+
|
|
685
|
+
setting_config = self.get_setting_config(setting)
|
|
686
|
+
if setting_config and "?" not in setting_config["operators"]:
|
|
687
|
+
# The device doesn't respond, the change can't be verified
|
|
688
|
+
return True
|
|
689
|
+
|
|
690
|
+
return current_value != new_value
|
|
691
|
+
|
|
692
|
+
async def async_increment(self, setting: str) -> bool:
|
|
693
|
+
"""Increments a setting."""
|
|
694
|
+
if not (setting_config := self.get_setting_config(setting)):
|
|
695
|
+
raise NADCommandError(
|
|
696
|
+
f"Setting {setting} is not supported by NAD {self.model}"
|
|
697
|
+
)
|
|
698
|
+
if "+" not in setting_config["operators"]:
|
|
699
|
+
raise NADCommandError(f"Incrementing {setting} not allowed")
|
|
700
|
+
|
|
701
|
+
return await self._async_step(setting, "+")
|
|
702
|
+
|
|
703
|
+
async def async_decrement(self, setting: str) -> bool:
|
|
704
|
+
"""Decrements a setting."""
|
|
705
|
+
if not (setting_config := self.get_setting_config(setting)):
|
|
706
|
+
raise NADCommandError(
|
|
707
|
+
f"Setting {setting} is not supported by NAD {self.model}"
|
|
708
|
+
)
|
|
709
|
+
if "-" not in setting_config["operators"]:
|
|
710
|
+
raise NADCommandError(f"Decrementing {setting} not allowed")
|
|
711
|
+
|
|
712
|
+
return await self._async_step(setting, "-")
|
|
713
|
+
|
|
714
|
+
@property
|
|
715
|
+
def is_on(self) -> bool:
|
|
716
|
+
"""If the device is on."""
|
|
717
|
+
return self.get_setting_value(f"{self._prefix}.Power") is True
|
|
718
|
+
|
|
719
|
+
async def async_request_is_on(self) -> bool:
|
|
720
|
+
"""Gets the value of a setting from the device."""
|
|
721
|
+
return await self.async_request_setting(f"{self._prefix}.Power") is True
|
|
722
|
+
|
|
723
|
+
async def async_turn_on(self) -> bool:
|
|
724
|
+
"""Turns the device on."""
|
|
725
|
+
return await self.async_change_setting(f"{self._prefix}.Power", True)
|
|
726
|
+
|
|
727
|
+
async def async_turn_off(self) -> bool:
|
|
728
|
+
"""Turns the device off."""
|
|
729
|
+
return await self.async_change_setting(f"{self._prefix}.Power", False)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
class NADAmplifier(NADDevice):
|
|
733
|
+
"""A NAD amplifier."""
|
|
734
|
+
|
|
735
|
+
_device_type: str = "amplifier"
|
|
736
|
+
|
|
737
|
+
@override
|
|
738
|
+
async def _async_setup(self) -> None:
|
|
739
|
+
"""Setup the NAD amplifier."""
|
|
740
|
+
await super()._async_setup()
|
|
741
|
+
|
|
742
|
+
with contextlib.suppress(NADConnectionError):
|
|
743
|
+
await self.async_request_settings(
|
|
744
|
+
f"{self._prefix}.{name}"
|
|
745
|
+
for name in ("Volume", "Mute", "Source", "ListeningMode")
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
source_config = self.get_setting_config(f"{self._prefix}.Source")
|
|
749
|
+
if not source_config or source_config["type"] != "number":
|
|
750
|
+
return
|
|
751
|
+
|
|
752
|
+
if self.supports_setting("Source1.Name"):
|
|
753
|
+
# The device configuration defines the source names, request them
|
|
754
|
+
with contextlib.suppress(NADConnectionError):
|
|
755
|
+
await self.async_request_settings(
|
|
756
|
+
setting
|
|
757
|
+
for i in range(1, 11)
|
|
758
|
+
for setting in (f"Source{i}.Enabled", f"Source{i}.Name")
|
|
759
|
+
)
|
|
760
|
+
return
|
|
761
|
+
|
|
762
|
+
# Try to get the source names, even though the device does not specify the needed settings.
|
|
763
|
+
for i in range(1, 11):
|
|
764
|
+
try:
|
|
765
|
+
setting = f"Source{i}.Name"
|
|
766
|
+
name_config = {"operators": "?", "type": "string"}
|
|
767
|
+
async with asyncio.timeout(SETUP_TIMEOUT):
|
|
768
|
+
value = await self._async_request(
|
|
769
|
+
setting,
|
|
770
|
+
"?",
|
|
771
|
+
setting_config=name_config,
|
|
772
|
+
)
|
|
773
|
+
if value is None:
|
|
774
|
+
break
|
|
775
|
+
self._supported_settings.append(setting)
|
|
776
|
+
self._device_config["settings"][setting.lower()] = name_config.copy()
|
|
777
|
+
self._setting_states[setting.lower()] = value
|
|
778
|
+
|
|
779
|
+
setting = f"Source{i}.Enabled"
|
|
780
|
+
enabled_config = {
|
|
781
|
+
"operators": "?",
|
|
782
|
+
"type": "boolean",
|
|
783
|
+
"values": ["No", "Yes"],
|
|
784
|
+
}
|
|
785
|
+
if not self.supports_setting(setting):
|
|
786
|
+
with contextlib.suppress(TimeoutError, NADTimeoutError):
|
|
787
|
+
async with asyncio.timeout(SETUP_TIMEOUT):
|
|
788
|
+
value = await self._async_request(
|
|
789
|
+
setting, "?", setting_config=enabled_config
|
|
790
|
+
)
|
|
791
|
+
if value is not None:
|
|
792
|
+
self._supported_settings.append(setting)
|
|
793
|
+
self._device_config["settings"][setting.lower()] = (
|
|
794
|
+
enabled_config.copy()
|
|
795
|
+
)
|
|
796
|
+
self._setting_states[setting.lower()] = value == "Yes"
|
|
797
|
+
except TimeoutError, NADTimeoutError:
|
|
798
|
+
break
|
|
799
|
+
|
|
800
|
+
@property
|
|
801
|
+
def volume(self) -> int | None:
|
|
802
|
+
"""Gets the amplifier volume in dB."""
|
|
803
|
+
value = self.get_setting_value(f"{self._prefix}.Volume")
|
|
804
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else None
|
|
805
|
+
|
|
806
|
+
async def async_request_volume(self) -> int | None:
|
|
807
|
+
"""Gets the value of a setting from the device."""
|
|
808
|
+
value = await self.async_request_setting(f"{self._prefix}.Volume")
|
|
809
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else None
|
|
810
|
+
|
|
811
|
+
@property
|
|
812
|
+
def muted(self) -> bool | None:
|
|
813
|
+
"""Gets the amplifier mute state."""
|
|
814
|
+
value = self.get_setting_value(f"{self._prefix}.Mute")
|
|
815
|
+
return value if isinstance(value, bool) else None
|
|
816
|
+
|
|
817
|
+
async def async_request_mute(self) -> bool | None:
|
|
818
|
+
"""Gets the value of a setting from the device."""
|
|
819
|
+
value = await self.async_request_setting(f"{self._prefix}.Mute")
|
|
820
|
+
return value if isinstance(value, bool) else None
|
|
821
|
+
|
|
822
|
+
@property
|
|
823
|
+
def source_names(self) -> dict[int | str, str] | None:
|
|
824
|
+
"""The source names by source, None if they are not known."""
|
|
825
|
+
source_config = self.get_setting_config(f"{self._prefix}.Source")
|
|
826
|
+
if source_config and source_config["type"] == "enum":
|
|
827
|
+
return {source_name: source_name for source_name in source_config["values"]}
|
|
828
|
+
|
|
829
|
+
source_names: dict[int | str, str] = {}
|
|
830
|
+
for i in range(1, 11):
|
|
831
|
+
if self.get_setting_value(f"Source{i}.Enabled") is False:
|
|
832
|
+
continue
|
|
833
|
+
value = self.get_setting_value(f"Source{i}.Name")
|
|
834
|
+
if isinstance(value, str) and value:
|
|
835
|
+
source_names[i] = value
|
|
836
|
+
|
|
837
|
+
return source_names or None
|
|
838
|
+
|
|
839
|
+
@property
|
|
840
|
+
def source_name(self) -> str | None:
|
|
841
|
+
"""The name of the current source, if known."""
|
|
842
|
+
source_config = self.get_setting_config(f"{self._prefix}.Source")
|
|
843
|
+
if not source_config:
|
|
844
|
+
return None
|
|
845
|
+
|
|
846
|
+
source = self.get_setting_value(f"{self._prefix}.Source")
|
|
847
|
+
|
|
848
|
+
if (
|
|
849
|
+
isinstance(source, int)
|
|
850
|
+
and source_config["type"] == "number"
|
|
851
|
+
and self.source_names
|
|
852
|
+
):
|
|
853
|
+
return self.source_names.get(source)
|
|
854
|
+
|
|
855
|
+
if (
|
|
856
|
+
source_config["type"] == "enum"
|
|
857
|
+
and isinstance(source, str)
|
|
858
|
+
and source in source_config["values"]
|
|
859
|
+
):
|
|
860
|
+
return source
|
|
861
|
+
|
|
862
|
+
return None
|
|
863
|
+
|
|
864
|
+
async def async_request_source_name(self) -> ValueType | None:
|
|
865
|
+
"""Gets the source name from the device."""
|
|
866
|
+
source_config = self.get_setting_config(f"{self._prefix}.Source")
|
|
867
|
+
if not source_config:
|
|
868
|
+
return None
|
|
869
|
+
|
|
870
|
+
source = await self.async_request_setting(f"{self._prefix}.Source")
|
|
871
|
+
|
|
872
|
+
if (
|
|
873
|
+
isinstance(source, int)
|
|
874
|
+
and source_config["type"] == "number"
|
|
875
|
+
and self.source_names
|
|
876
|
+
):
|
|
877
|
+
return self.source_names.get(source)
|
|
878
|
+
|
|
879
|
+
if source_config["type"] == "enum" and source in source_config["values"]:
|
|
880
|
+
return source
|
|
881
|
+
|
|
882
|
+
return None
|
|
883
|
+
|
|
884
|
+
async def async_set_volume(self, volume: int) -> bool:
|
|
885
|
+
"""Sets the amplifier volume."""
|
|
886
|
+
return await self.async_change_setting(f"{self._prefix}.Volume", volume)
|
|
887
|
+
|
|
888
|
+
async def async_mute(self) -> bool:
|
|
889
|
+
"""Mutes the amplifier."""
|
|
890
|
+
return await self.async_change_setting(f"{self._prefix}.Mute", True)
|
|
891
|
+
|
|
892
|
+
async def async_unmute(self) -> bool:
|
|
893
|
+
"""Unmutes the amplifier."""
|
|
894
|
+
return await self.async_change_setting(f"{self._prefix}.Mute", False)
|
|
895
|
+
|
|
896
|
+
async def async_set_source(self, source: int | str) -> bool:
|
|
897
|
+
"""Sets the source."""
|
|
898
|
+
return await self.async_change_setting(f"{self._prefix}.Source", source)
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
class NADMultiZoneAmplifier(NADAmplifier):
|
|
902
|
+
"""A multi-zone NAD amplifier."""
|
|
903
|
+
|
|
904
|
+
_zones: list[NADZone] | None = None
|
|
905
|
+
|
|
906
|
+
@override
|
|
907
|
+
async def _async_setup(self) -> None:
|
|
908
|
+
"""Setup the multi-zone NAD amplifier."""
|
|
909
|
+
await super()._async_setup()
|
|
910
|
+
|
|
911
|
+
zones = []
|
|
912
|
+
for i in range(2, 5):
|
|
913
|
+
setting_config = self.get_setting_config(f"zone{i}.power")
|
|
914
|
+
if setting_config is not None:
|
|
915
|
+
zones.append(NADZone(self, i))
|
|
916
|
+
|
|
917
|
+
if zones:
|
|
918
|
+
self._zones = zones
|
|
919
|
+
|
|
920
|
+
with contextlib.suppress(NADConnectionError):
|
|
921
|
+
await self.async_request_settings(
|
|
922
|
+
f"Zone{zone.zone_number}.{name}"
|
|
923
|
+
for zone in zones
|
|
924
|
+
for name in ("Power", "Volume", "Mute", "Source")
|
|
925
|
+
)
|
|
926
|
+
|
|
927
|
+
@property
|
|
928
|
+
def zones(self) -> list[NADZone] | None:
|
|
929
|
+
"""Returns the zones of the amplifier."""
|
|
930
|
+
return self._zones
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
class NADZone(NADAmplifier):
|
|
934
|
+
"""A zone."""
|
|
935
|
+
|
|
936
|
+
_parent_device: NADMultiZoneAmplifier
|
|
937
|
+
_zone_number: int
|
|
938
|
+
|
|
939
|
+
def __init__(self, parent_device: NADMultiZoneAmplifier, zone_number: int): # pylint: disable=super-init-not-called
|
|
940
|
+
"""Initializes an amplifier zone."""
|
|
941
|
+
self._parent_device = parent_device
|
|
942
|
+
self._zone_number = zone_number
|
|
943
|
+
self._prefix = f"Zone{zone_number}"
|
|
944
|
+
|
|
945
|
+
@property
|
|
946
|
+
@override
|
|
947
|
+
def connected(self) -> bool:
|
|
948
|
+
"""If there is a connection to the zone."""
|
|
949
|
+
return self._parent_device.connected
|
|
950
|
+
|
|
951
|
+
@property
|
|
952
|
+
@override
|
|
953
|
+
def model(self) -> str | None:
|
|
954
|
+
"""The device model."""
|
|
955
|
+
return self._parent_device.model
|
|
956
|
+
|
|
957
|
+
@property
|
|
958
|
+
def zone_number(self) -> int:
|
|
959
|
+
"""The zone number."""
|
|
960
|
+
return self._zone_number
|
|
961
|
+
|
|
962
|
+
@property
|
|
963
|
+
@override
|
|
964
|
+
def name(self) -> str:
|
|
965
|
+
"""The zone name."""
|
|
966
|
+
return f"NAD {self.model} Zone {self.zone_number}"
|
|
967
|
+
|
|
968
|
+
@property
|
|
969
|
+
@override
|
|
970
|
+
def supported_settings(self) -> list[str]:
|
|
971
|
+
"""The by the device supported settings."""
|
|
972
|
+
return [
|
|
973
|
+
setting
|
|
974
|
+
for setting in self._parent_device._supported_settings # noqa: SLF001
|
|
975
|
+
if setting.lower().startswith(f"{self._prefix.lower()}.")
|
|
976
|
+
]
|
|
977
|
+
|
|
978
|
+
@property
|
|
979
|
+
@override
|
|
980
|
+
def source_names(self) -> dict[int | str, str] | None:
|
|
981
|
+
"""The source names by source, None if they are not known."""
|
|
982
|
+
return self._parent_device.source_names
|
|
983
|
+
|
|
984
|
+
@override
|
|
985
|
+
def add_callback(
|
|
986
|
+
self, callback: Callable[[str, ValueType | None], None]
|
|
987
|
+
) -> Callable[[], None]:
|
|
988
|
+
"""Adds a callback."""
|
|
989
|
+
|
|
990
|
+
def zone_callback(setting: str, value: ValueType | None) -> None:
|
|
991
|
+
if setting.lower().startswith((f"{self._prefix.lower()}.", "source")):
|
|
992
|
+
callback(setting, value)
|
|
993
|
+
|
|
994
|
+
return self._parent_device.add_callback(zone_callback)
|
|
995
|
+
|
|
996
|
+
@override
|
|
997
|
+
def get_setting_config(self, setting: str) -> dict[str, Any] | None:
|
|
998
|
+
"""Gets the configuration for a setting."""
|
|
999
|
+
if not setting.lower().startswith(f"{self._prefix.lower()}."):
|
|
1000
|
+
return None
|
|
1001
|
+
return self._parent_device.get_setting_config(setting)
|
|
1002
|
+
|
|
1003
|
+
@override
|
|
1004
|
+
def get_setting_value(self, setting: str) -> ValueType | None:
|
|
1005
|
+
"""Gets the state of a setting."""
|
|
1006
|
+
if not setting.lower().startswith(f"{self._prefix.lower()}."):
|
|
1007
|
+
return None
|
|
1008
|
+
return self._parent_device.get_setting_value(setting)
|
|
1009
|
+
|
|
1010
|
+
@override
|
|
1011
|
+
async def _async_request(
|
|
1012
|
+
self,
|
|
1013
|
+
setting: str,
|
|
1014
|
+
operator: str,
|
|
1015
|
+
value: ValueType | None = None,
|
|
1016
|
+
setting_config: dict[str, Any] | None = None,
|
|
1017
|
+
) -> ValueType | None:
|
|
1018
|
+
"""Sends a request and waits for the response."""
|
|
1019
|
+
return await self._parent_device._async_request( # noqa: SLF001
|
|
1020
|
+
setting, operator, value, setting_config
|
|
1021
|
+
)
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
class NADTuner(NADDevice):
|
|
1025
|
+
"""A NAD tuner."""
|
|
1026
|
+
|
|
1027
|
+
_device_type: str = "tuner"
|
|
1028
|
+
|
|
1029
|
+
def get_band(self) -> str | None:
|
|
1030
|
+
"""Gets the tuner band."""
|
|
1031
|
+
value = self.get_setting_value("Tuner.Band")
|
|
1032
|
+
return str(value) if value else None
|
|
1033
|
+
|
|
1034
|
+
async def async_set_band(self, band: str) -> bool:
|
|
1035
|
+
"""Selects the tuner band."""
|
|
1036
|
+
return await self.async_change_setting("Tuner.Band", band)
|
|
1037
|
+
|
|
1038
|
+
def get_am_frequency(self) -> int | None:
|
|
1039
|
+
"""Gets the AM frequency."""
|
|
1040
|
+
value = self.get_setting_value("Tuner.AM.Frequency")
|
|
1041
|
+
return int(value) if value is not None else None
|
|
1042
|
+
|
|
1043
|
+
async def async_set_am_frequency(self, frequency: int) -> bool:
|
|
1044
|
+
"""Tunes to an AM frequency."""
|
|
1045
|
+
return await self.async_change_setting("Tuner.AM.Frequency", frequency)
|
|
1046
|
+
|
|
1047
|
+
def get_fm_frequency(self) -> float | None:
|
|
1048
|
+
"""Gets the FM frequency."""
|
|
1049
|
+
value = self.get_setting_value("Tuner.FM.Frequency")
|
|
1050
|
+
return float(value) if value is not None else None
|
|
1051
|
+
|
|
1052
|
+
async def async_set_fm_frequency(self, frequency: float) -> bool:
|
|
1053
|
+
"""Tunes to an FM frequency."""
|
|
1054
|
+
return await self.async_change_setting("Tuner.FM.Frequency", frequency)
|
|
1055
|
+
|
|
1056
|
+
def get_preset(self) -> int | None:
|
|
1057
|
+
"""Gets the current preset."""
|
|
1058
|
+
value = self.get_setting_value("Tuner.Preset")
|
|
1059
|
+
return int(value) if value is not None else None
|
|
1060
|
+
|
|
1061
|
+
async def async_set_preset(self, preset: int) -> bool:
|
|
1062
|
+
"""Selects a tuner preset."""
|
|
1063
|
+
return await self.async_change_setting("Tuner.Preset", preset)
|
|
1064
|
+
|
|
1065
|
+
def get_fm_rdsname(self) -> str | None:
|
|
1066
|
+
"""Gets the RDS name."""
|
|
1067
|
+
value = self.get_setting_value("Tuner.FM.RDSName")
|
|
1068
|
+
return str(value) if value else None
|
|
1069
|
+
|
|
1070
|
+
def get_fm_rdstext(self) -> str | None:
|
|
1071
|
+
"""Gets the RDS text."""
|
|
1072
|
+
value = self.get_setting_value("Tuner.FM.RDSText")
|
|
1073
|
+
return str(value) if value else None
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
class NADReceiver(NADAmplifier, NADTuner):
|
|
1077
|
+
"""A NAD device with an amplifier and a tuner."""
|
|
1078
|
+
|
|
1079
|
+
_device_type: str = "receiver"
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
class NADMultiZoneReceiver(NADMultiZoneAmplifier, NADTuner):
|
|
1083
|
+
"""A NAD device with a multi-zone amplifier and a tuner."""
|
|
1084
|
+
|
|
1085
|
+
_device_type: str = "receiver"
|