pyosd-audio 0.2.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.
- pyosd/__init__.py +80 -0
- pyosd/devices/__init__.py +5 -0
- pyosd/devices/pam1270/__init__.py +50 -0
- pyosd/devices/pam1270/client.py +529 -0
- pyosd/devices/pam1270/codec.py +247 -0
- pyosd/devices/pam1270/service.py +947 -0
- pyosd/devices/pam1270/simulator.py +214 -0
- pyosd/devices/pam1270/tables.py +31 -0
- pyosd/domain/__init__.py +18 -0
- pyosd/domain/enums.py +31 -0
- pyosd/domain/state.py +46 -0
- pyosd/domain/values.py +160 -0
- pyosd/exceptions.py +65 -0
- pyosd/protocol/__init__.py +5 -0
- pyosd/protocol/framing.py +51 -0
- pyosd/py.typed +0 -0
- pyosd/transport/__init__.py +8 -0
- pyosd/transport/base.py +46 -0
- pyosd/transport/fake.py +61 -0
- pyosd/transport/serial.py +81 -0
- pyosd/transport/tcp.py +61 -0
- pyosd_audio-0.2.0.dist-info/METADATA +124 -0
- pyosd_audio-0.2.0.dist-info/RECORD +25 -0
- pyosd_audio-0.2.0.dist-info/WHEEL +4 -0
- pyosd_audio-0.2.0.dist-info/licenses/LICENSE +21 -0
pyosd/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""pyosd -- control OSD Audio devices from Python.
|
|
2
|
+
|
|
3
|
+
The library is split in two: a device-agnostic domain model
|
|
4
|
+
(:mod:`pyosd.domain`) describing zones, volumes and tone, and per-device clients
|
|
5
|
+
(:mod:`pyosd.devices`) that speak a given amplifier's wire protocol.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from importlib import metadata as _metadata
|
|
9
|
+
|
|
10
|
+
from pyosd.devices.pam1270 import (
|
|
11
|
+
PAM1270,
|
|
12
|
+
AmpService,
|
|
13
|
+
ConnectionState,
|
|
14
|
+
EventKind,
|
|
15
|
+
Outcome,
|
|
16
|
+
PAM1270Simulator,
|
|
17
|
+
SafetyPolicy,
|
|
18
|
+
UpdateFailed,
|
|
19
|
+
UpdateSource,
|
|
20
|
+
ZoneUpdate,
|
|
21
|
+
)
|
|
22
|
+
from pyosd.domain import Balance, ChannelState, InputSource, Tone, Volume, ZoneState
|
|
23
|
+
from pyosd.exceptions import (
|
|
24
|
+
CommandNotAcknowledged,
|
|
25
|
+
OutcomeUncertain,
|
|
26
|
+
ProtocolError,
|
|
27
|
+
PyOSDError,
|
|
28
|
+
RequestCancelled,
|
|
29
|
+
RequestTimeout,
|
|
30
|
+
ResponseTimeout,
|
|
31
|
+
ServiceBusy,
|
|
32
|
+
ServiceError,
|
|
33
|
+
ServiceTimeout,
|
|
34
|
+
ServiceUnavailable,
|
|
35
|
+
TransportError,
|
|
36
|
+
ValidationError,
|
|
37
|
+
)
|
|
38
|
+
from pyosd.transport import FakeTransport, SerialTransport, TcpTransport, Transport
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
__version__ = _metadata.version("pyosd-audio")
|
|
42
|
+
except _metadata.PackageNotFoundError: # pragma: no cover - running from a bare source tree
|
|
43
|
+
__version__ = "0.0.0"
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"PAM1270",
|
|
47
|
+
"AmpService",
|
|
48
|
+
"Balance",
|
|
49
|
+
"ChannelState",
|
|
50
|
+
"CommandNotAcknowledged",
|
|
51
|
+
"ConnectionState",
|
|
52
|
+
"EventKind",
|
|
53
|
+
"FakeTransport",
|
|
54
|
+
"InputSource",
|
|
55
|
+
"Outcome",
|
|
56
|
+
"OutcomeUncertain",
|
|
57
|
+
"PAM1270Simulator",
|
|
58
|
+
"ProtocolError",
|
|
59
|
+
"PyOSDError",
|
|
60
|
+
"RequestCancelled",
|
|
61
|
+
"RequestTimeout",
|
|
62
|
+
"ResponseTimeout",
|
|
63
|
+
"SafetyPolicy",
|
|
64
|
+
"SerialTransport",
|
|
65
|
+
"ServiceBusy",
|
|
66
|
+
"ServiceError",
|
|
67
|
+
"ServiceTimeout",
|
|
68
|
+
"ServiceUnavailable",
|
|
69
|
+
"TcpTransport",
|
|
70
|
+
"Tone",
|
|
71
|
+
"Transport",
|
|
72
|
+
"TransportError",
|
|
73
|
+
"UpdateFailed",
|
|
74
|
+
"UpdateSource",
|
|
75
|
+
"ValidationError",
|
|
76
|
+
"Volume",
|
|
77
|
+
"ZoneState",
|
|
78
|
+
"ZoneUpdate",
|
|
79
|
+
"__version__",
|
|
80
|
+
]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""OSD PAM1270: 12-channel / 6-zone commercial multi-zone amplifier."""
|
|
2
|
+
|
|
3
|
+
from pyosd.devices.pam1270.client import PAM1270, Channel, UpdateSource, Zone
|
|
4
|
+
from pyosd.devices.pam1270.service import (
|
|
5
|
+
AmpService,
|
|
6
|
+
CommandFailure,
|
|
7
|
+
ConnectionState,
|
|
8
|
+
EventKind,
|
|
9
|
+
Outcome,
|
|
10
|
+
RefreshResult,
|
|
11
|
+
SafetyPolicy,
|
|
12
|
+
ServiceEvent,
|
|
13
|
+
Snapshot,
|
|
14
|
+
Subscription,
|
|
15
|
+
SuspectedCause,
|
|
16
|
+
UpdateFailed,
|
|
17
|
+
UpdateFailure,
|
|
18
|
+
UpdateResult,
|
|
19
|
+
ZoneSnapshot,
|
|
20
|
+
ZoneUpdate,
|
|
21
|
+
)
|
|
22
|
+
from pyosd.devices.pam1270.simulator import PAM1270Simulator
|
|
23
|
+
from pyosd.devices.pam1270.tables import CHANNEL_COUNT, SERIAL_SETTINGS, ZONE_COUNT
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"CHANNEL_COUNT",
|
|
27
|
+
"PAM1270",
|
|
28
|
+
"SERIAL_SETTINGS",
|
|
29
|
+
"ZONE_COUNT",
|
|
30
|
+
"AmpService",
|
|
31
|
+
"Channel",
|
|
32
|
+
"CommandFailure",
|
|
33
|
+
"ConnectionState",
|
|
34
|
+
"EventKind",
|
|
35
|
+
"Outcome",
|
|
36
|
+
"PAM1270Simulator",
|
|
37
|
+
"RefreshResult",
|
|
38
|
+
"SafetyPolicy",
|
|
39
|
+
"ServiceEvent",
|
|
40
|
+
"Snapshot",
|
|
41
|
+
"Subscription",
|
|
42
|
+
"SuspectedCause",
|
|
43
|
+
"UpdateFailed",
|
|
44
|
+
"UpdateFailure",
|
|
45
|
+
"UpdateResult",
|
|
46
|
+
"UpdateSource",
|
|
47
|
+
"Zone",
|
|
48
|
+
"ZoneSnapshot",
|
|
49
|
+
"ZoneUpdate",
|
|
50
|
+
]
|
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""Device-oriented wrapper around the PAM1270's RS232 protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from types import TracebackType
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from pyosd.devices.pam1270 import codec
|
|
13
|
+
from pyosd.devices.pam1270.tables import (
|
|
14
|
+
CHANNEL_COUNT,
|
|
15
|
+
MISLABELLED_ANSWERS,
|
|
16
|
+
SERIAL_SETTINGS,
|
|
17
|
+
ZONE_COUNT,
|
|
18
|
+
)
|
|
19
|
+
from pyosd.domain.enums import InputSource
|
|
20
|
+
from pyosd.domain.state import ZoneState
|
|
21
|
+
from pyosd.domain.values import Balance, Tone, Volume
|
|
22
|
+
from pyosd.exceptions import CommandNotAcknowledged, ProtocolError, ResponseTimeout
|
|
23
|
+
from pyosd.protocol.framing import FrameBuffer
|
|
24
|
+
from pyosd.transport.base import Transport
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class UpdateSource(Enum):
|
|
28
|
+
"""Why a zone update arrived."""
|
|
29
|
+
|
|
30
|
+
QUERY = "query" # the answer to a query this client sent
|
|
31
|
+
COMMAND_ACK = "command_ack" # the acknowledgement of a command this client sent
|
|
32
|
+
BROADCAST = "broadcast" # a `#` status line: IR remote, trigger, or activity auto update
|
|
33
|
+
UNSOLICITED = "unsolicited" # a value line nobody asked for, e.g. power reports at boot
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
Listener = Callable[[ZoneState], None]
|
|
37
|
+
SourcedListener = Callable[[ZoneState, UpdateSource], None]
|
|
38
|
+
|
|
39
|
+
DEFAULT_TIMEOUT = 1.0
|
|
40
|
+
# Measured on hardware: an input change within ~2.1s of the previous one is silently dropped.
|
|
41
|
+
INPUT_LOCKOUT = 2.5
|
|
42
|
+
_READ_SLICE = 0.05
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Zone:
|
|
46
|
+
"""One of the amplifier's six zones.
|
|
47
|
+
|
|
48
|
+
Reading a property queries the device and blocks until it answers; assigning
|
|
49
|
+
one sends a command and blocks until the device acknowledges it, raising
|
|
50
|
+
:class:`~pyosd.CommandNotAcknowledged` if it does not. A powered-off zone
|
|
51
|
+
acknowledges only power commands. Use :attr:`state` for the cached view when
|
|
52
|
+
a round trip is not wanted.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, amplifier: PAM1270, number: int) -> None:
|
|
56
|
+
self._amp = amplifier
|
|
57
|
+
self.number = codec.check_zone(number)
|
|
58
|
+
|
|
59
|
+
def __repr__(self) -> str:
|
|
60
|
+
return f"<Zone {self.number} of PAM1270>"
|
|
61
|
+
|
|
62
|
+
def _command(self, line: str, key: str) -> None:
|
|
63
|
+
self._amp.command(line, key, self.number)
|
|
64
|
+
|
|
65
|
+
# -- cached view ---------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def state(self) -> ZoneState:
|
|
69
|
+
"""The last known state, without talking to the device."""
|
|
70
|
+
return self._amp.cached_state(self.number)
|
|
71
|
+
|
|
72
|
+
def refresh(self) -> ZoneState:
|
|
73
|
+
"""Ask the device for this zone's full status and update the cache."""
|
|
74
|
+
frame = self._amp.exchange(
|
|
75
|
+
codec.query_zone_status(self.number),
|
|
76
|
+
lambda f: isinstance(f, codec.StatusUpdate) and f.state.zone == self.number,
|
|
77
|
+
)
|
|
78
|
+
assert isinstance(frame, codec.StatusUpdate)
|
|
79
|
+
return self._amp.cached_state(self.number)
|
|
80
|
+
|
|
81
|
+
# -- power ---------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def power(self) -> bool:
|
|
85
|
+
return bool(self._amp.query_value(codec.query_power(self.number), "PR", self.number))
|
|
86
|
+
|
|
87
|
+
@power.setter
|
|
88
|
+
def power(self, on: bool) -> None:
|
|
89
|
+
# The device stays silent on a power command matching the current state, so
|
|
90
|
+
# only send one that changes it.
|
|
91
|
+
if self.power != on:
|
|
92
|
+
self._command(codec.set_power(self.number, on), "PR")
|
|
93
|
+
|
|
94
|
+
def toggle_power(self) -> None:
|
|
95
|
+
self._command(codec.toggle_power(self.number), "PR")
|
|
96
|
+
|
|
97
|
+
# -- volume --------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def volume(self) -> Volume:
|
|
101
|
+
return Volume(self._amp.query_value(codec.query_volume(self.number), "VO", self.number))
|
|
102
|
+
|
|
103
|
+
@volume.setter
|
|
104
|
+
def volume(self, volume: Volume | int) -> None:
|
|
105
|
+
self._command(codec.set_volume(self.number, _as_volume(volume)), "VO")
|
|
106
|
+
|
|
107
|
+
def volume_up(self) -> None:
|
|
108
|
+
self._command(codec.volume_up(self.number), "VO")
|
|
109
|
+
|
|
110
|
+
def volume_down(self) -> None:
|
|
111
|
+
self._command(codec.volume_down(self.number), "VO")
|
|
112
|
+
|
|
113
|
+
def lock_max_volume(self) -> None:
|
|
114
|
+
"""Latch the zone's current volume as its ceiling for every control path.
|
|
115
|
+
|
|
116
|
+
Sent without waiting: this command's acknowledgement has not been observed.
|
|
117
|
+
"""
|
|
118
|
+
self._amp.send(codec.lock_max_volume(self.number))
|
|
119
|
+
|
|
120
|
+
# -- mute ----------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def mute(self) -> bool:
|
|
124
|
+
return bool(self._amp.query_value(codec.query_mute(self.number), "MU", self.number))
|
|
125
|
+
|
|
126
|
+
@mute.setter
|
|
127
|
+
def mute(self, muted: bool) -> None:
|
|
128
|
+
self._command(codec.set_mute(self.number, muted), "MU")
|
|
129
|
+
|
|
130
|
+
def toggle_mute(self) -> None:
|
|
131
|
+
self._command(codec.toggle_mute(self.number), "MU")
|
|
132
|
+
|
|
133
|
+
# -- input ---------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def input_source(self) -> InputSource:
|
|
137
|
+
raw = self._amp.query_value(codec.query_input(self.number), "IS", self.number)
|
|
138
|
+
return InputSource.from_wire(raw)
|
|
139
|
+
|
|
140
|
+
@input_source.setter
|
|
141
|
+
def input_source(self, source: InputSource) -> None:
|
|
142
|
+
self._amp.input_command(self.number, codec.set_zone_input(self.number, source))
|
|
143
|
+
|
|
144
|
+
def toggle_input(self) -> None:
|
|
145
|
+
self._amp.input_command(self.number, codec.toggle_zone_input(self.number))
|
|
146
|
+
|
|
147
|
+
# -- tone and balance ----------------------------------------------------
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def treble(self) -> Tone:
|
|
151
|
+
return Tone(self._amp.query_value(codec.query_treble(self.number), "TR", self.number))
|
|
152
|
+
|
|
153
|
+
@treble.setter
|
|
154
|
+
def treble(self, tone: Tone | int) -> None:
|
|
155
|
+
self._command(codec.set_treble(self.number, _as_tone(tone)), "TR")
|
|
156
|
+
|
|
157
|
+
def treble_up(self) -> None:
|
|
158
|
+
self._command(codec.treble_up(self.number), "TR")
|
|
159
|
+
|
|
160
|
+
def treble_down(self) -> None:
|
|
161
|
+
self._command(codec.treble_down(self.number), "TR")
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def bass(self) -> Tone:
|
|
165
|
+
return Tone(self._amp.query_value(codec.query_bass(self.number), "BS", self.number))
|
|
166
|
+
|
|
167
|
+
@bass.setter
|
|
168
|
+
def bass(self, tone: Tone | int) -> None:
|
|
169
|
+
self._command(codec.set_bass(self.number, _as_tone(tone)), "BS")
|
|
170
|
+
|
|
171
|
+
def bass_up(self) -> None:
|
|
172
|
+
self._command(codec.bass_up(self.number), "BS")
|
|
173
|
+
|
|
174
|
+
def bass_down(self) -> None:
|
|
175
|
+
self._command(codec.bass_down(self.number), "BS")
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def balance(self) -> Balance:
|
|
179
|
+
return Balance(self._amp.query_value(codec.query_balance(self.number), "BA", self.number))
|
|
180
|
+
|
|
181
|
+
@balance.setter
|
|
182
|
+
def balance(self, balance: Balance | int) -> None:
|
|
183
|
+
self._command(codec.set_balance(self.number, _as_balance(balance)), "BA")
|
|
184
|
+
|
|
185
|
+
def balance_left(self) -> None:
|
|
186
|
+
self._command(codec.balance_left(self.number), "BA")
|
|
187
|
+
|
|
188
|
+
def balance_right(self) -> None:
|
|
189
|
+
self._command(codec.balance_right(self.number), "BA")
|
|
190
|
+
|
|
191
|
+
def flatten_tone(self) -> None:
|
|
192
|
+
"""Reset bass and treble to flat -- only RS232 can do this exactly."""
|
|
193
|
+
self.bass = Tone.flat()
|
|
194
|
+
self.treble = Tone.flat()
|
|
195
|
+
|
|
196
|
+
def center_balance(self) -> None:
|
|
197
|
+
"""Reset balance to centre -- only RS232 can do this exactly."""
|
|
198
|
+
self.balance = Balance.centered()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class Channel:
|
|
202
|
+
"""One of the twelve mono amplifier channels."""
|
|
203
|
+
|
|
204
|
+
def __init__(self, amplifier: PAM1270, number: int) -> None:
|
|
205
|
+
self._amp = amplifier
|
|
206
|
+
self.number = codec.check_channel(number)
|
|
207
|
+
|
|
208
|
+
def __repr__(self) -> str:
|
|
209
|
+
return f"<Channel {self.number} of PAM1270>"
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def volume(self) -> Volume:
|
|
213
|
+
"""Not answered by the device; read the owning zone's volume instead.
|
|
214
|
+
|
|
215
|
+
The manual lists ``?{c#}CH+``, but real hardware never replies to it.
|
|
216
|
+
"""
|
|
217
|
+
raise NotImplementedError(
|
|
218
|
+
"the PAM1270 does not answer the channel volume query; read the zone's volume"
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def input_source(self) -> InputSource:
|
|
223
|
+
"""Not queryable on this device; read the owning zone instead."""
|
|
224
|
+
raise NotImplementedError(
|
|
225
|
+
"the PAM1270 has no channel input query; query the zone's input instead"
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
@input_source.setter
|
|
229
|
+
def input_source(self, source: InputSource) -> None:
|
|
230
|
+
self._amp.send(codec.set_channel_input(self.number, source))
|
|
231
|
+
|
|
232
|
+
def toggle_input(self) -> None:
|
|
233
|
+
self._amp.send(codec.toggle_channel_input(self.number))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class PAM1270:
|
|
237
|
+
"""A PAM1270 amplifier reachable over some :class:`~pyosd.transport.Transport`.
|
|
238
|
+
|
|
239
|
+
The device also talks unprompted: with activity auto update enabled it
|
|
240
|
+
broadcasts a zone's state about a second after a change made from the IR
|
|
241
|
+
remote or a voltage trigger, and it reports power at boot. RS232 commands are
|
|
242
|
+
not broadcast; the device acknowledges each one by echoing the resulting value
|
|
243
|
+
as a query response. Every read therefore demultiplexes unsolicited lines from
|
|
244
|
+
the answer it waits for, feeding all of them to the cache and to subscribers.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
zone_count = ZONE_COUNT
|
|
248
|
+
channel_count = CHANNEL_COUNT
|
|
249
|
+
|
|
250
|
+
def __init__(
|
|
251
|
+
self,
|
|
252
|
+
transport: Transport,
|
|
253
|
+
*,
|
|
254
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
255
|
+
input_lockout: float = INPUT_LOCKOUT,
|
|
256
|
+
) -> None:
|
|
257
|
+
self.transport = transport
|
|
258
|
+
self.timeout = timeout
|
|
259
|
+
self.input_lockout = input_lockout
|
|
260
|
+
#: Monotonic time of the last accepted input change per zone. Public so that a successor
|
|
261
|
+
#: client (after a reconnect) can inherit it and keep honouring the device's lockout.
|
|
262
|
+
self.input_change_times: dict[int, float] = {}
|
|
263
|
+
self._frames = FrameBuffer()
|
|
264
|
+
self._cache: dict[int, ZoneState] = {z: ZoneState(zone=z) for z in range(1, ZONE_COUNT + 1)}
|
|
265
|
+
self._listeners: list[SourcedListener] = []
|
|
266
|
+
self._zones = {n: Zone(self, n) for n in range(1, ZONE_COUNT + 1)}
|
|
267
|
+
self._channels = {n: Channel(self, n) for n in range(1, CHANNEL_COUNT + 1)}
|
|
268
|
+
|
|
269
|
+
# -- construction --------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
@classmethod
|
|
272
|
+
def from_serial(cls, port: str, *, timeout: float = DEFAULT_TIMEOUT, **kwargs: Any) -> PAM1270:
|
|
273
|
+
"""Connect over a serial port using the device's documented settings."""
|
|
274
|
+
from pyosd.transport.serial import SerialTransport
|
|
275
|
+
|
|
276
|
+
settings: dict[str, Any] = {**SERIAL_SETTINGS, **kwargs}
|
|
277
|
+
return cls(SerialTransport(port, **settings), timeout=timeout)
|
|
278
|
+
|
|
279
|
+
@classmethod
|
|
280
|
+
def from_tcp(
|
|
281
|
+
cls, host: str, port: int, *, timeout: float = DEFAULT_TIMEOUT, **kwargs: Any
|
|
282
|
+
) -> PAM1270:
|
|
283
|
+
"""Connect through an IP-to-serial gateway."""
|
|
284
|
+
from pyosd.transport.tcp import TcpTransport
|
|
285
|
+
|
|
286
|
+
return cls(TcpTransport(host, port, **kwargs), timeout=timeout)
|
|
287
|
+
|
|
288
|
+
# -- lifecycle -----------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
def open(self) -> PAM1270:
|
|
291
|
+
self.transport.open()
|
|
292
|
+
return self
|
|
293
|
+
|
|
294
|
+
def close(self) -> None:
|
|
295
|
+
self.transport.close()
|
|
296
|
+
|
|
297
|
+
def __enter__(self) -> PAM1270:
|
|
298
|
+
return self.open()
|
|
299
|
+
|
|
300
|
+
def __exit__(
|
|
301
|
+
self,
|
|
302
|
+
exc_type: type[BaseException] | None,
|
|
303
|
+
exc: BaseException | None,
|
|
304
|
+
tb: TracebackType | None,
|
|
305
|
+
) -> None:
|
|
306
|
+
self.close()
|
|
307
|
+
|
|
308
|
+
def __repr__(self) -> str:
|
|
309
|
+
return f"<PAM1270 via {self.transport.__class__.__name__}>"
|
|
310
|
+
|
|
311
|
+
# -- addressing ----------------------------------------------------------
|
|
312
|
+
|
|
313
|
+
@property
|
|
314
|
+
def zones(self) -> Mapping[int, Zone]:
|
|
315
|
+
"""Zones 1..6, addressable as ``amp.zones[3]``."""
|
|
316
|
+
return self._zones
|
|
317
|
+
|
|
318
|
+
@property
|
|
319
|
+
def channels(self) -> Mapping[int, Channel]:
|
|
320
|
+
"""Channels 1..12, addressable as ``amp.channels[7]``."""
|
|
321
|
+
return self._channels
|
|
322
|
+
|
|
323
|
+
def __iter__(self) -> Iterator[Zone]:
|
|
324
|
+
return iter(self._zones.values())
|
|
325
|
+
|
|
326
|
+
# -- global settings -----------------------------------------------------
|
|
327
|
+
|
|
328
|
+
def set_auto_update(self, enabled: bool) -> None:
|
|
329
|
+
"""Turn the device's zone-activity broadcasts on or off (global setting).
|
|
330
|
+
|
|
331
|
+
Sent without waiting: the device does not acknowledge this command.
|
|
332
|
+
"""
|
|
333
|
+
self.send(codec.set_auto_update(enabled))
|
|
334
|
+
|
|
335
|
+
@property
|
|
336
|
+
def auto_update(self) -> bool:
|
|
337
|
+
frame = self.exchange(
|
|
338
|
+
codec.query_auto_update(), lambda f: isinstance(f, codec.AutoUpdateResponse)
|
|
339
|
+
)
|
|
340
|
+
assert isinstance(frame, codec.AutoUpdateResponse)
|
|
341
|
+
return frame.enabled
|
|
342
|
+
|
|
343
|
+
def refresh(self) -> dict[int, ZoneState]:
|
|
344
|
+
"""Query every zone's status and return the refreshed cache."""
|
|
345
|
+
for zone in self._zones.values():
|
|
346
|
+
zone.refresh()
|
|
347
|
+
return dict(self._cache)
|
|
348
|
+
|
|
349
|
+
# -- events --------------------------------------------------------------
|
|
350
|
+
|
|
351
|
+
def subscribe(self, listener: Listener) -> Callable[[], None]:
|
|
352
|
+
"""Register a callback for zone updates; returns an unsubscribe function.
|
|
353
|
+
|
|
354
|
+
The callback receives the zone's full cached state after the update was merged in.
|
|
355
|
+
"""
|
|
356
|
+
return self.subscribe_sourced(lambda state, _source: listener(self._cache[state.zone]))
|
|
357
|
+
|
|
358
|
+
def subscribe_sourced(self, listener: SourcedListener) -> Callable[[], None]:
|
|
359
|
+
"""Register a callback that receives each update as observed, plus its source.
|
|
360
|
+
|
|
361
|
+
Unlike :meth:`subscribe`, the state holds only the fields this update carried (the rest
|
|
362
|
+
are ``None``), so a consumer can tell exactly what was observed.
|
|
363
|
+
"""
|
|
364
|
+
self._listeners.append(listener)
|
|
365
|
+
return lambda: self._listeners.remove(listener)
|
|
366
|
+
|
|
367
|
+
def poll(self, timeout: float = 0.0) -> list[ZoneState]:
|
|
368
|
+
"""Read pending broadcasts, update the cache, and return what changed."""
|
|
369
|
+
updates: list[ZoneState] = []
|
|
370
|
+
for frame in self._read_frames(timeout):
|
|
371
|
+
handled = self._handle(frame, _unasked_source(frame))
|
|
372
|
+
if handled is not None:
|
|
373
|
+
updates.append(handled)
|
|
374
|
+
return updates
|
|
375
|
+
|
|
376
|
+
def cached_state(self, zone: int) -> ZoneState:
|
|
377
|
+
return self._cache[codec.check_zone(zone)]
|
|
378
|
+
|
|
379
|
+
# -- plumbing ------------------------------------------------------------
|
|
380
|
+
|
|
381
|
+
def send(self, line: str) -> None:
|
|
382
|
+
"""Write one line without waiting for anything back."""
|
|
383
|
+
self.transport.write(line.encode("ascii"))
|
|
384
|
+
|
|
385
|
+
def command(self, line: str, key: str, index: int) -> int:
|
|
386
|
+
"""Send a command and return the value the device acknowledges it with.
|
|
387
|
+
|
|
388
|
+
Waiting for the acknowledgement also paces the link: a line sent while the
|
|
389
|
+
device is still transmitting one can lose its terminator.
|
|
390
|
+
"""
|
|
391
|
+
try:
|
|
392
|
+
return self.query_value(line, key, index)
|
|
393
|
+
except ResponseTimeout as exc:
|
|
394
|
+
raise CommandNotAcknowledged(
|
|
395
|
+
f"{line!r} was not acknowledged within {self.timeout}s; the zone may be"
|
|
396
|
+
" powered off or have its Remote Bypass switch ON"
|
|
397
|
+
) from exc
|
|
398
|
+
|
|
399
|
+
def input_command(self, zone: int, line: str) -> int:
|
|
400
|
+
"""Send a zone input command, first waiting out the device's input lockout."""
|
|
401
|
+
last = self.input_change_times.get(zone)
|
|
402
|
+
if last is not None:
|
|
403
|
+
wait = last + self.input_lockout - time.monotonic()
|
|
404
|
+
if wait > 0:
|
|
405
|
+
time.sleep(wait)
|
|
406
|
+
value = self.command(line, "IS", zone)
|
|
407
|
+
self.input_change_times[zone] = time.monotonic()
|
|
408
|
+
return value
|
|
409
|
+
|
|
410
|
+
def query_value(self, line: str, key: str, index: int) -> int:
|
|
411
|
+
"""Send a query (or command) and return the integer the device answers with."""
|
|
412
|
+
alias = MISLABELLED_ANSWERS.get((key, index))
|
|
413
|
+
|
|
414
|
+
def relabel(frame: codec.Frame) -> codec.Frame:
|
|
415
|
+
if (
|
|
416
|
+
alias is not None
|
|
417
|
+
and isinstance(frame, codec.ValueResponse)
|
|
418
|
+
and (frame.key, frame.index) == (key, alias)
|
|
419
|
+
):
|
|
420
|
+
return replace(frame, index=index)
|
|
421
|
+
return frame
|
|
422
|
+
|
|
423
|
+
frame = self.exchange(
|
|
424
|
+
line,
|
|
425
|
+
lambda f: isinstance(f, codec.ValueResponse) and f.key == key and f.index == index,
|
|
426
|
+
relabel=relabel if alias is not None else None,
|
|
427
|
+
)
|
|
428
|
+
assert isinstance(frame, codec.ValueResponse)
|
|
429
|
+
return frame.value
|
|
430
|
+
|
|
431
|
+
def exchange(
|
|
432
|
+
self,
|
|
433
|
+
line: str,
|
|
434
|
+
want: Callable[[codec.Frame], bool],
|
|
435
|
+
*,
|
|
436
|
+
relabel: Callable[[codec.Frame], codec.Frame] | None = None,
|
|
437
|
+
) -> codec.Frame:
|
|
438
|
+
"""Send ``line`` and wait for the first frame ``want`` accepts.
|
|
439
|
+
|
|
440
|
+
Frames arriving in the meantime -- typically activity broadcasts -- are
|
|
441
|
+
handled rather than discarded, because they can interleave with answers.
|
|
442
|
+
``relabel`` corrects frames the firmware is known to mislabel before anything sees them.
|
|
443
|
+
"""
|
|
444
|
+
self.send(line)
|
|
445
|
+
answer = UpdateSource.COMMAND_ACK if line.startswith("!") else UpdateSource.QUERY
|
|
446
|
+
deadline = time.monotonic() + self.timeout
|
|
447
|
+
while True:
|
|
448
|
+
remaining = deadline - time.monotonic()
|
|
449
|
+
if remaining <= 0:
|
|
450
|
+
raise ResponseTimeout(f"no response to {line!r} within {self.timeout}s")
|
|
451
|
+
for received in self._read_frames(min(remaining, _READ_SLICE)):
|
|
452
|
+
frame = relabel(received) if relabel is not None else received
|
|
453
|
+
wanted = want(frame)
|
|
454
|
+
self._handle(frame, answer if wanted else _unasked_source(frame))
|
|
455
|
+
if wanted:
|
|
456
|
+
return frame
|
|
457
|
+
|
|
458
|
+
def _read_frames(self, timeout: float) -> list[codec.Frame]:
|
|
459
|
+
data = self.transport.read(max(timeout, 0.0))
|
|
460
|
+
frames: list[codec.Frame] = []
|
|
461
|
+
for text in self._frames.push(data):
|
|
462
|
+
try:
|
|
463
|
+
frames.append(codec.parse_frame(text))
|
|
464
|
+
except ProtocolError:
|
|
465
|
+
# Devices echo assorted noise; ignoring it keeps the link usable.
|
|
466
|
+
continue
|
|
467
|
+
return frames
|
|
468
|
+
|
|
469
|
+
def _handle(self, frame: codec.Frame, source: UpdateSource) -> ZoneState | None:
|
|
470
|
+
"""Fold a frame into the cache, notifying listeners about zone changes."""
|
|
471
|
+
state: ZoneState | None = None
|
|
472
|
+
if isinstance(frame, codec.StatusUpdate):
|
|
473
|
+
state = frame.state
|
|
474
|
+
elif isinstance(frame, codec.ValueResponse):
|
|
475
|
+
state = _state_from_value(frame)
|
|
476
|
+
if state is None:
|
|
477
|
+
return None
|
|
478
|
+
|
|
479
|
+
merged = self._cache[state.zone].merged(state)
|
|
480
|
+
self._cache[state.zone] = merged
|
|
481
|
+
for listener in list(self._listeners):
|
|
482
|
+
listener(state, source)
|
|
483
|
+
return merged
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _unasked_source(frame: codec.Frame) -> UpdateSource:
|
|
487
|
+
"""The source of a frame that arrived without being the answer anyone was waiting for."""
|
|
488
|
+
if isinstance(frame, codec.StatusUpdate):
|
|
489
|
+
return UpdateSource.BROADCAST
|
|
490
|
+
return UpdateSource.UNSOLICITED
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _state_from_value(frame: codec.ValueResponse) -> ZoneState | None:
|
|
494
|
+
"""Map a single-value response onto the zone state it describes.
|
|
495
|
+
|
|
496
|
+
``CH`` is deliberately absent: it is indexed by channel, not by zone.
|
|
497
|
+
"""
|
|
498
|
+
if not 1 <= frame.index <= ZONE_COUNT:
|
|
499
|
+
return None
|
|
500
|
+
zone = frame.index
|
|
501
|
+
match frame.key:
|
|
502
|
+
case "VO":
|
|
503
|
+
return ZoneState(zone=zone, volume=Volume(frame.value))
|
|
504
|
+
case "PR":
|
|
505
|
+
return ZoneState(zone=zone, power=bool(frame.value))
|
|
506
|
+
case "MU":
|
|
507
|
+
return ZoneState(zone=zone, mute=bool(frame.value))
|
|
508
|
+
case "IS":
|
|
509
|
+
return ZoneState(zone=zone, input_source=InputSource.from_wire(frame.value))
|
|
510
|
+
case "TR":
|
|
511
|
+
return ZoneState(zone=zone, treble=Tone(frame.value))
|
|
512
|
+
case "BS":
|
|
513
|
+
return ZoneState(zone=zone, bass=Tone(frame.value))
|
|
514
|
+
case "BA":
|
|
515
|
+
return ZoneState(zone=zone, balance=Balance(frame.value))
|
|
516
|
+
case _:
|
|
517
|
+
return None
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _as_volume(value: Volume | int) -> Volume:
|
|
521
|
+
return value if isinstance(value, Volume) else Volume(value)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _as_tone(value: Tone | int) -> Tone:
|
|
525
|
+
return value if isinstance(value, Tone) else Tone(value)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _as_balance(value: Balance | int) -> Balance:
|
|
529
|
+
return value if isinstance(value, Balance) else Balance(value)
|