mcintosh-serial 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ dist/
5
+ .coverage
6
+ coverage.xml
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ mcintosh-probe-*.log
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0](https://github.com/KB1RMA/mcintosh-serial/releases/tag/v0.1.0) (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * the zoned dialect, verified on a McIntosh MX119: power, volume, mute and input selection, with changes made on the unit pushed to the client
9
+ * an async `ZonedClient` that paces commands, retries a query rejected just after power-up and reports connection loss
10
+ * `open_serial` for device paths and pyserial URLs such as `socket://host:port`
11
+ * `mcintosh_serial.testing.FakeMX119`, an in-process emulation of the unit built from traffic captured on real hardware
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christopher Snyder
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.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.5
2
+ Name: mcintosh-serial
3
+ Version: 0.1.0
4
+ Summary: Async Python library for controlling McIntosh receivers, preamps and amplifiers over RS232.
5
+ Project-URL: Homepage, https://github.com/KB1RMA/mcintosh-serial
6
+ Project-URL: Repository, https://github.com/KB1RMA/mcintosh-serial
7
+ Project-URL: Issues, https://github.com/KB1RMA/mcintosh-serial/issues
8
+ Project-URL: Changelog, https://github.com/KB1RMA/mcintosh-serial/blob/main/CHANGELOG.md
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: audio,home-assistant,mcintosh,rs232,serial
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Home Automation
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14.2
19
+ Requires-Dist: pyserial-asyncio-fast>=0.16
20
+ Description-Content-Type: text/markdown
21
+
22
+ # mcintosh-serial
23
+
24
+ [![PyPI](https://img.shields.io/pypi/v/mcintosh-serial)](https://pypi.org/project/mcintosh-serial/)
25
+ [![CI](https://github.com/KB1RMA/mcintosh-serial/actions/workflows/ci.yml/badge.svg)](https://github.com/KB1RMA/mcintosh-serial/actions/workflows/ci.yml)
26
+ [![Coverage](https://codecov.io/gh/KB1RMA/mcintosh-serial/graph/badge.svg)](https://codecov.io/gh/KB1RMA/mcintosh-serial)
27
+ [![License: MIT](https://img.shields.io/github/license/KB1RMA/mcintosh-serial)](LICENSE)
28
+
29
+ Async Python library for controlling McIntosh receivers, preamps and amplifiers over their RS232 port.
30
+ It is the protocol layer behind [ha-mcintosh-serial](https://github.com/KB1RMA/ha-mcintosh-serial), a Home
31
+ Assistant integration, but has no Home Assistant dependency.
32
+
33
+ This project is independent. It is not affiliated with or endorsed by McIntosh Laboratory.
34
+
35
+ > **Status:** early. Only the *zoned* command style is implemented, and it has been verified on one unit, a
36
+ > McIntosh MX119. Other models are listed below as planned, not supported.
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ import asyncio
42
+
43
+ from mcintosh_serial import ZonedClient, open_serial
44
+
45
+
46
+ async def main() -> None:
47
+ client = ZonedClient(await open_serial("/dev/ttyUSB0", 9600))
48
+ await client.start() # enables RS232 control if needed and loads full state
49
+ print(client.state.zone(1))
50
+
51
+ await client.set_volume(1, 12)
52
+ await client.select_input(1, 4)
53
+ await client.set_mute(1, muted=True)
54
+
55
+ client.add_listener(print) # changes made on the unit are pushed to you
56
+ await asyncio.sleep(60)
57
+ await client.stop()
58
+
59
+
60
+ asyncio.run(main())
61
+ ```
62
+
63
+ `open_serial` takes a device path or a pyserial URL such as `socket://host:port` for a network serial server.
64
+ Volume is the unit's own step number; input numbers are the unit's own too (on an MX119, 0 Tuner, 1 PH/AUX,
65
+ 2 CD 2, 3 SAT, 4 TV, 5 DVD, 6 VCR 1, 7 Tape 1, unless relabeled in its menu).
66
+
67
+ The client sends one command at a time and waits for the unit to finish talking before the next, because the
68
+ unit drops commands that arrive while it is still replying. Commands raise `McIntoshTimeoutError`,
69
+ `McIntoshCommandError` (the unit answered `(ERR n)`) or `McIntoshConnectionError`.
70
+
71
+ ### Testing code that uses the library
72
+
73
+ `mcintosh_serial.testing.FakeMX119` is an in-process emulation of the unit, built from captured traffic. It
74
+ implements the transport interface, so you can hand it straight to `ZonedClient`.
75
+
76
+ ## Command styles
77
+
78
+ McIntosh has used three different serial command styles. They are not interchangeable.
79
+
80
+ | Style | Looks like | Models | Status |
81
+ |---|---|---|---|
82
+ | zoned | `(PON Z1)`, `(VST Z1 8)`, `(CTL 1)` | MX119 (verified); C47, C2500, MA5200 per McIntosh's application note | implemented, MX119 only |
83
+ | simple | `(PWR 1)`, `(VOL 65)`, `(STA 1)` | MA352, MA5300 | planned, untested |
84
+ | bang | `!POWER?`, `!VOL(n)`, `!SRC(n)` | MX160, MX170, MX180 | planned, untested |
85
+
86
+ What was observed on a real MX119 (wiring, baud rate, timing, quirks) is in
87
+ [docs/protocols/zoned.md](docs/protocols/zoned.md). If you have a McIntosh unit and can help test or have
88
+ protocol documents, please open an issue.
89
+
90
+ ## Development
91
+
92
+ ```bash
93
+ uv sync
94
+ uv run ruff check . && uv run ruff format --check .
95
+ uv run pyright
96
+ uv run pytest # 100% branch coverage is required
97
+ ```
98
+
99
+ `tests/acceptance/` runs against the built wheel in CI. See [AGENTS.md](AGENTS.md) for the project rules.
100
+
101
+ ## Credits
102
+
103
+ Protocol knowledge comes from McIntosh's RS-232 application note and from reading
104
+ [node-mcintosh](https://github.com/stefan747/node-mcintosh),
105
+ [hass-mcintosh](https://github.com/homeassistant-projects/hass-mcintosh),
106
+ [mcintosh-ma352-hass](https://github.com/felix920506/mcintosh-ma352-hass) and
107
+ [esphome-mcintosh-ma5300](https://github.com/The-sultan/esphome-mcintosh-ma5300). No code was copied from them.
108
+
109
+ ## Licence
110
+
111
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,90 @@
1
+ # mcintosh-serial
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/mcintosh-serial)](https://pypi.org/project/mcintosh-serial/)
4
+ [![CI](https://github.com/KB1RMA/mcintosh-serial/actions/workflows/ci.yml/badge.svg)](https://github.com/KB1RMA/mcintosh-serial/actions/workflows/ci.yml)
5
+ [![Coverage](https://codecov.io/gh/KB1RMA/mcintosh-serial/graph/badge.svg)](https://codecov.io/gh/KB1RMA/mcintosh-serial)
6
+ [![License: MIT](https://img.shields.io/github/license/KB1RMA/mcintosh-serial)](LICENSE)
7
+
8
+ Async Python library for controlling McIntosh receivers, preamps and amplifiers over their RS232 port.
9
+ It is the protocol layer behind [ha-mcintosh-serial](https://github.com/KB1RMA/ha-mcintosh-serial), a Home
10
+ Assistant integration, but has no Home Assistant dependency.
11
+
12
+ This project is independent. It is not affiliated with or endorsed by McIntosh Laboratory.
13
+
14
+ > **Status:** early. Only the *zoned* command style is implemented, and it has been verified on one unit, a
15
+ > McIntosh MX119. Other models are listed below as planned, not supported.
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ import asyncio
21
+
22
+ from mcintosh_serial import ZonedClient, open_serial
23
+
24
+
25
+ async def main() -> None:
26
+ client = ZonedClient(await open_serial("/dev/ttyUSB0", 9600))
27
+ await client.start() # enables RS232 control if needed and loads full state
28
+ print(client.state.zone(1))
29
+
30
+ await client.set_volume(1, 12)
31
+ await client.select_input(1, 4)
32
+ await client.set_mute(1, muted=True)
33
+
34
+ client.add_listener(print) # changes made on the unit are pushed to you
35
+ await asyncio.sleep(60)
36
+ await client.stop()
37
+
38
+
39
+ asyncio.run(main())
40
+ ```
41
+
42
+ `open_serial` takes a device path or a pyserial URL such as `socket://host:port` for a network serial server.
43
+ Volume is the unit's own step number; input numbers are the unit's own too (on an MX119, 0 Tuner, 1 PH/AUX,
44
+ 2 CD 2, 3 SAT, 4 TV, 5 DVD, 6 VCR 1, 7 Tape 1, unless relabeled in its menu).
45
+
46
+ The client sends one command at a time and waits for the unit to finish talking before the next, because the
47
+ unit drops commands that arrive while it is still replying. Commands raise `McIntoshTimeoutError`,
48
+ `McIntoshCommandError` (the unit answered `(ERR n)`) or `McIntoshConnectionError`.
49
+
50
+ ### Testing code that uses the library
51
+
52
+ `mcintosh_serial.testing.FakeMX119` is an in-process emulation of the unit, built from captured traffic. It
53
+ implements the transport interface, so you can hand it straight to `ZonedClient`.
54
+
55
+ ## Command styles
56
+
57
+ McIntosh has used three different serial command styles. They are not interchangeable.
58
+
59
+ | Style | Looks like | Models | Status |
60
+ |---|---|---|---|
61
+ | zoned | `(PON Z1)`, `(VST Z1 8)`, `(CTL 1)` | MX119 (verified); C47, C2500, MA5200 per McIntosh's application note | implemented, MX119 only |
62
+ | simple | `(PWR 1)`, `(VOL 65)`, `(STA 1)` | MA352, MA5300 | planned, untested |
63
+ | bang | `!POWER?`, `!VOL(n)`, `!SRC(n)` | MX160, MX170, MX180 | planned, untested |
64
+
65
+ What was observed on a real MX119 (wiring, baud rate, timing, quirks) is in
66
+ [docs/protocols/zoned.md](docs/protocols/zoned.md). If you have a McIntosh unit and can help test or have
67
+ protocol documents, please open an issue.
68
+
69
+ ## Development
70
+
71
+ ```bash
72
+ uv sync
73
+ uv run ruff check . && uv run ruff format --check .
74
+ uv run pyright
75
+ uv run pytest # 100% branch coverage is required
76
+ ```
77
+
78
+ `tests/acceptance/` runs against the built wheel in CI. See [AGENTS.md](AGENTS.md) for the project rules.
79
+
80
+ ## Credits
81
+
82
+ Protocol knowledge comes from McIntosh's RS-232 application note and from reading
83
+ [node-mcintosh](https://github.com/stefan747/node-mcintosh),
84
+ [hass-mcintosh](https://github.com/homeassistant-projects/hass-mcintosh),
85
+ [mcintosh-ma352-hass](https://github.com/felix920506/mcintosh-ma352-hass) and
86
+ [esphome-mcintosh-ma5300](https://github.com/The-sultan/esphome-mcintosh-ma5300). No code was copied from them.
87
+
88
+ ## Licence
89
+
90
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,105 @@
1
+ [project]
2
+ name = "mcintosh-serial"
3
+ version = "0.1.0"
4
+ description = "Async Python library for controlling McIntosh receivers, preamps and amplifiers over RS232."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.14.2"
9
+ keywords = ["mcintosh", "rs232", "serial", "home-assistant", "audio"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Framework :: AsyncIO",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3.14",
15
+ "Topic :: Home Automation",
16
+ "Typing :: Typed",
17
+ ]
18
+ dependencies = ["pyserial-asyncio-fast>=0.16"]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/KB1RMA/mcintosh-serial"
22
+ Repository = "https://github.com/KB1RMA/mcintosh-serial"
23
+ Issues = "https://github.com/KB1RMA/mcintosh-serial/issues"
24
+ Changelog = "https://github.com/KB1RMA/mcintosh-serial/blob/main/CHANGELOG.md"
25
+
26
+ [dependency-groups]
27
+ dev = [
28
+ "pytest==9.0.3",
29
+ "pytest-asyncio==1.4.0",
30
+ "pytest-cov==7.1.0",
31
+ "pyright==1.1.414",
32
+ "ruff==0.17.5",
33
+ ]
34
+
35
+ [build-system]
36
+ requires = ["hatchling"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/mcintosh_serial"]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ include = ["src", "tests", "LICENSE", "README.md", "CHANGELOG.md"]
44
+
45
+ [tool.pytest.ini_options]
46
+ asyncio_mode = "auto"
47
+ asyncio_default_fixture_loop_scope = "function"
48
+ testpaths = ["tests"]
49
+ addopts = "--cov=mcintosh_serial --cov-report=term-missing --cov-fail-under=100"
50
+
51
+ [tool.coverage.run]
52
+ branch = true
53
+
54
+ [tool.ruff]
55
+ target-version = "py314"
56
+ line-length = 88
57
+
58
+ [tool.ruff.lint]
59
+ select = ["ALL"]
60
+ ignore = [
61
+ "CPY001", # the licence is in LICENSE
62
+ "D107", # __init__ is documented on the class
63
+ "E501", # the formatter handles line length
64
+ "COM812", # conflicts with the formatter
65
+ "D203", # conflicts with D211
66
+ "D213", # conflicts with D212
67
+ "ISC001", # conflicts with the formatter
68
+ ]
69
+
70
+ [tool.ruff.lint.per-file-ignores]
71
+ "tests/**" = [
72
+ "S101", # pytest asserts
73
+ "PLR2004", # literal values in asserts
74
+ "SLF001",
75
+ "D",
76
+ "ANN401",
77
+ "PLR0913", # pytest fixtures are arguments
78
+ "PLR0917",
79
+ "FBT001", # parametrized flags
80
+ "INP001", # tests are not a package
81
+ ]
82
+
83
+ [tool.ruff.lint.isort]
84
+ combine-as-imports = true
85
+ force-sort-within-sections = true
86
+
87
+ [tool.pyright]
88
+ include = ["src", "tests"]
89
+ venvPath = "."
90
+ venv = ".venv"
91
+ pythonVersion = "3.14"
92
+ typeCheckingMode = "strict"
93
+ reportMissingTypeStubs = "none"
94
+ reportPrivateUsage = "error"
95
+ reportUnnecessaryTypeIgnoreComment = "error"
96
+ reportImplicitOverride = "error"
97
+ reportUninitializedInstanceVariable = "error"
98
+
99
+ [[tool.pyright.executionEnvironments]]
100
+ root = "tests"
101
+ extraPaths = ["src"]
102
+ reportPrivateUsage = "none"
103
+
104
+ [[tool.pyright.executionEnvironments]]
105
+ root = "src"
@@ -0,0 +1,28 @@
1
+ """Async control of McIntosh equipment over RS232."""
2
+
3
+ from mcintosh_serial.client import Timing, ZonedClient
4
+ from mcintosh_serial.dialects.zoned import DeviceState, ZoneState
5
+ from mcintosh_serial.errors import (
6
+ McIntoshCommandError,
7
+ McIntoshConnectionError,
8
+ McIntoshError,
9
+ McIntoshTimeoutError,
10
+ )
11
+ from mcintosh_serial.frames import Frame, parse_frames
12
+ from mcintosh_serial.transport import StreamTransport, Transport, open_serial
13
+
14
+ __all__ = [
15
+ "DeviceState",
16
+ "Frame",
17
+ "McIntoshCommandError",
18
+ "McIntoshConnectionError",
19
+ "McIntoshError",
20
+ "McIntoshTimeoutError",
21
+ "StreamTransport",
22
+ "Timing",
23
+ "Transport",
24
+ "ZoneState",
25
+ "ZonedClient",
26
+ "open_serial",
27
+ "parse_frames",
28
+ ]
@@ -0,0 +1,242 @@
1
+ """Async client for the zoned dialect.
2
+
3
+ One command is in flight at a time. After the expected reply arrives the client
4
+ waits for the line to go quiet before releasing the next command, because the
5
+ unit drops commands that arrive while it is still sending a reply.
6
+ """
7
+
8
+ import asyncio
9
+ from collections.abc import Callable
10
+ import contextlib
11
+ from dataclasses import dataclass
12
+ import logging
13
+ from time import monotonic
14
+ from typing import TYPE_CHECKING
15
+
16
+ from mcintosh_serial.dialects import zoned
17
+ from mcintosh_serial.errors import (
18
+ McIntoshCommandError,
19
+ McIntoshConnectionError,
20
+ McIntoshTimeoutError,
21
+ )
22
+ from mcintosh_serial.frames import Frame, parse_frames
23
+
24
+ if TYPE_CHECKING:
25
+ from mcintosh_serial.transport import Transport
26
+
27
+ _LOGGER = logging.getLogger(__name__)
28
+
29
+ Listener = Callable[[zoned.DeviceState], None]
30
+ ConnectionListener = Callable[[bool], None]
31
+ Matcher = Callable[[Frame], bool]
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class Timing:
36
+ """Seconds. Defaults come from the MX119; override in tests."""
37
+
38
+ command: float = 2.0
39
+ query: float = 4.0
40
+ power: float = 12.0
41
+ settle: float = 0.3 # quiet time after a reply before the next command
42
+ settle_max: float = 3.0
43
+ retry_delay: float = 1.0 # wait before retrying a (QRY) rejected after power-up
44
+
45
+
46
+ @dataclass(slots=True)
47
+ class _Pending:
48
+ command: str
49
+ matches: Matcher
50
+ future: asyncio.Future[Frame]
51
+
52
+
53
+ def _reply(name: str, zone: int, value: str | None = None) -> Matcher:
54
+ wanted = (f"Z{zone}",) if value is None else (f"Z{zone}", value)
55
+ return lambda frame: frame.name == name and frame.args[: len(wanted)] == wanted
56
+
57
+
58
+ def _is_status_start(frame: Frame) -> bool:
59
+ return frame.name in ("PON", "POF")
60
+
61
+
62
+ def _is_ctl_echo(frame: Frame) -> bool:
63
+ return frame.name == "CTL"
64
+
65
+
66
+ class ZonedClient:
67
+ """Talk to one McIntosh unit that speaks the zoned dialect."""
68
+
69
+ def __init__(self, transport: Transport, timing: Timing | None = None) -> None:
70
+ self._transport = transport
71
+ self._timing = timing or Timing()
72
+ self._state = zoned.DeviceState()
73
+ self._listeners: list[Listener] = []
74
+ self._connection_listeners: list[ConnectionListener] = []
75
+ self._connected = False
76
+ self._lock = asyncio.Lock()
77
+ self._pending: _Pending | None = None
78
+ self._read_task: asyncio.Task[None] | None = None
79
+ self._last_rx = monotonic()
80
+ self._rx = asyncio.Event()
81
+
82
+ # ------------------------------------------------------------ lifecycle
83
+ @property
84
+ def state(self) -> zoned.DeviceState:
85
+ """The last state the unit reported."""
86
+ return self._state
87
+
88
+ @property
89
+ def connected(self) -> bool:
90
+ """True from a successful start() until the transport closes or stop()."""
91
+ return self._connected
92
+
93
+ def add_listener(self, listener: Listener) -> Callable[[], None]:
94
+ """Call ``listener`` with the new state whenever it changes."""
95
+ self._listeners.append(listener)
96
+ return lambda: self._listeners.remove(listener)
97
+
98
+ def add_connection_listener(
99
+ self, listener: ConnectionListener
100
+ ) -> Callable[[], None]:
101
+ """Call ``listener(False)`` when the link drops, ``listener(True)`` on start."""
102
+ self._connection_listeners.append(listener)
103
+ return lambda: self._connection_listeners.remove(listener)
104
+
105
+ def _set_connected(self, *, connected: bool) -> None:
106
+ if connected != self._connected:
107
+ self._connected = connected
108
+ for listener in tuple(self._connection_listeners):
109
+ listener(connected)
110
+
111
+ async def start(self) -> None:
112
+ """Begin reading, make sure RS232 control is enabled, then load full state."""
113
+ self._read_task = asyncio.get_running_loop().create_task(self._read_loop())
114
+ try:
115
+ await self.query()
116
+ except McIntoshCommandError, McIntoshTimeoutError:
117
+ await self._exchange(
118
+ zoned.enable_rs232(), _is_ctl_echo, self._timing.command
119
+ )
120
+ await self.query()
121
+ self._set_connected(connected=True)
122
+
123
+ async def stop(self) -> None:
124
+ """Stop reading and close the transport."""
125
+ task, self._read_task = self._read_task, None
126
+ self._connected = False
127
+ if task is not None:
128
+ task.cancel()
129
+ await asyncio.gather(task, return_exceptions=True)
130
+ await self._transport.close()
131
+
132
+ # ------------------------------------------------------------- commands
133
+ async def query(self) -> zoned.DeviceState:
134
+ """Request full status; retry once if rejected just after power-up."""
135
+ try:
136
+ await self._exchange(zoned.query(), _is_status_start, self._timing.query)
137
+ except McIntoshCommandError as err:
138
+ if err.code != "1":
139
+ raise
140
+ await asyncio.sleep(self._timing.retry_delay)
141
+ await self._exchange(zoned.query(), _is_status_start, self._timing.query)
142
+ return self._state
143
+
144
+ async def set_power(self, zone: int, *, on: bool) -> None:
145
+ """Turn a zone on or off and wait for the unit to confirm."""
146
+ await self._exchange(
147
+ zoned.power(zone, on=on),
148
+ _reply("PON" if on else "POF", zone),
149
+ self._timing.power,
150
+ )
151
+
152
+ async def set_volume(self, zone: int, level: int) -> None:
153
+ """Set a zone's volume to the unit's own step number."""
154
+ await self._exchange(
155
+ zoned.volume_set(zone, level),
156
+ _reply("VST", zone, str(level)),
157
+ self._timing.command,
158
+ )
159
+
160
+ async def volume_step(self, zone: int, *, up: bool) -> None:
161
+ """Raise or lower a zone's volume by one step."""
162
+ await self._exchange(
163
+ zoned.volume_step(zone, up=up), _reply("VST", zone), self._timing.command
164
+ )
165
+
166
+ async def set_mute(self, zone: int, *, muted: bool) -> None:
167
+ """Mute or unmute a zone."""
168
+ await self._exchange(
169
+ zoned.mute(zone, muted=muted),
170
+ _reply("MUT", zone, str(int(muted))),
171
+ self._timing.command,
172
+ )
173
+
174
+ async def select_input(self, zone: int, number: int) -> None:
175
+ """Select an input for a zone."""
176
+ await self._exchange(
177
+ zoned.select_input(zone, number),
178
+ _reply("INP", zone, str(number)),
179
+ self._timing.power,
180
+ )
181
+
182
+ # -------------------------------------------------------------- plumbing
183
+ async def _exchange(self, command: str, matches: Matcher, wait: float) -> Frame:
184
+ async with self._lock:
185
+ future: asyncio.Future[Frame] = asyncio.get_running_loop().create_future()
186
+ self._pending = _Pending(command, matches, future)
187
+ try:
188
+ await self._transport.write(command.encode("ascii"))
189
+ frame = await asyncio.wait_for(future, wait)
190
+ except TimeoutError as err:
191
+ raise McIntoshTimeoutError(command) from err
192
+ except OSError as err:
193
+ raise McIntoshConnectionError(str(err)) from err
194
+ finally:
195
+ self._pending = None
196
+ await self._settle()
197
+ return frame
198
+
199
+ async def _settle(self) -> None:
200
+ """Wait until the unit has been quiet for ``settle`` seconds."""
201
+ deadline = monotonic() + self._timing.settle_max
202
+ with contextlib.suppress(TimeoutError):
203
+ while True:
204
+ quiet_for = self._timing.settle - (monotonic() - self._last_rx)
205
+ remaining = deadline - monotonic()
206
+ if quiet_for <= 0 or remaining <= 0:
207
+ return
208
+ self._rx.clear()
209
+ await asyncio.wait_for(self._rx.wait(), min(quiet_for, remaining))
210
+
211
+ async def _read_loop(self) -> None:
212
+ buffer = ""
213
+ while data := await self._transport.read():
214
+ self._last_rx = monotonic()
215
+ self._rx.set()
216
+ frames, buffer = parse_frames(
217
+ buffer + data.decode("ascii", errors="ignore")
218
+ )
219
+ for frame in frames:
220
+ self._handle(frame)
221
+ _LOGGER.debug("transport closed")
222
+ pending = self._pending
223
+ if pending is not None and not pending.future.done():
224
+ pending.future.set_exception(McIntoshConnectionError("connection closed"))
225
+ self._set_connected(connected=False)
226
+
227
+ def _handle(self, frame: Frame) -> None:
228
+ pending = self._pending
229
+ if zoned.is_error(frame):
230
+ code = frame.args[0] if frame.args else "?"
231
+ if pending is not None and not pending.future.done():
232
+ pending.future.set_exception(
233
+ McIntoshCommandError(code, pending.command)
234
+ )
235
+ return
236
+ before = self._state
237
+ self._state = zoned.apply_frame(before, frame)
238
+ if pending is not None and not pending.future.done() and pending.matches(frame):
239
+ pending.future.set_result(frame)
240
+ if self._state != before:
241
+ for listener in tuple(self._listeners):
242
+ listener(self._state)
@@ -0,0 +1 @@
1
+ """Protocol dialects (one module per McIntosh command style)."""