pjlink-advance 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,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .coverage
10
+ htmlcov/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Josue
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,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: pjlink-advance
3
+ Version: 0.1.0
4
+ Summary: Asyncio PJLink Class 1 and Class 2 client with search, status notifications and a projector emulator
5
+ Author: Josue
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: asyncio,home-assistant,pjlink,projector
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Home Automation
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.13
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
20
+ Requires-Dist: pytest>=8; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # pjlink-advance
24
+
25
+ Asyncio PJLink Class 1 and Class 2 library with network search, status
26
+ notifications and a projector emulator. No runtime dependencies.
27
+
28
+ ## Client
29
+
30
+ ```python
31
+ import asyncio
32
+ from pjlink_advance import PJLinkClient, MuteTarget
33
+
34
+
35
+ async def main() -> None:
36
+ async with PJLinkClient("192.168.1.50", password="secret") as projector:
37
+ info = await projector.fetch_static()
38
+ print(info.manufacturer, info.model, info.serial)
39
+ await projector.set_power(True)
40
+ await projector.set_av_mute(MuteTarget.VIDEO, True)
41
+ state = await projector.fetch_state(full=True, pj_class=info.pj_class)
42
+ print(state.power, state.lamps, state.errors)
43
+
44
+
45
+ asyncio.run(main())
46
+ ```
47
+
48
+ One TCP session is kept open and shared by all commands (serialized with a
49
+ lock). It reconnects on its own when the projector drops idle sessions.
50
+
51
+ Errors: `PJLinkConnectionError`, `PJLinkAuthError`, `PJLinkProtocolError`, and
52
+ `PJLinkCommandError` subclasses for `ERR1`–`ERR4`
53
+ (`PJLinkUndefinedCommand`, `PJLinkOutOfParameter`, `PJLinkUnavailableTime`,
54
+ `PJLinkProjectorFailure`).
55
+
56
+ ## Search and notifications (Class 2)
57
+
58
+ ```python
59
+ from pjlink_advance import PJLinkListener
60
+
61
+ listener = PJLinkListener() # UDP port 4352
62
+ await listener.start()
63
+ print(await listener.discover(duration=3)) # [(ip, mac), ...]
64
+ listener.register("192.168.1.50", lambda command, value: print(command, value))
65
+ ```
66
+
67
+ ## Emulator
68
+
69
+ ```bash
70
+ python -m pjlink_advance.emulator --port 4352 --password secret --pj-class 2
71
+ ```
72
+
73
+ In tests:
74
+
75
+ ```python
76
+ from pjlink_advance.emulator import PJLinkEmulator
77
+
78
+ async with PJLinkEmulator(password="secret") as emulator:
79
+ emulator.unavailable.add("INPT") # answer ERR3
80
+ emulator.fail_next = "ERR4"
81
+ ...
82
+ ```
83
+
84
+ ## License
85
+
86
+ MIT
@@ -0,0 +1,64 @@
1
+ # pjlink-advance
2
+
3
+ Asyncio PJLink Class 1 and Class 2 library with network search, status
4
+ notifications and a projector emulator. No runtime dependencies.
5
+
6
+ ## Client
7
+
8
+ ```python
9
+ import asyncio
10
+ from pjlink_advance import PJLinkClient, MuteTarget
11
+
12
+
13
+ async def main() -> None:
14
+ async with PJLinkClient("192.168.1.50", password="secret") as projector:
15
+ info = await projector.fetch_static()
16
+ print(info.manufacturer, info.model, info.serial)
17
+ await projector.set_power(True)
18
+ await projector.set_av_mute(MuteTarget.VIDEO, True)
19
+ state = await projector.fetch_state(full=True, pj_class=info.pj_class)
20
+ print(state.power, state.lamps, state.errors)
21
+
22
+
23
+ asyncio.run(main())
24
+ ```
25
+
26
+ One TCP session is kept open and shared by all commands (serialized with a
27
+ lock). It reconnects on its own when the projector drops idle sessions.
28
+
29
+ Errors: `PJLinkConnectionError`, `PJLinkAuthError`, `PJLinkProtocolError`, and
30
+ `PJLinkCommandError` subclasses for `ERR1`–`ERR4`
31
+ (`PJLinkUndefinedCommand`, `PJLinkOutOfParameter`, `PJLinkUnavailableTime`,
32
+ `PJLinkProjectorFailure`).
33
+
34
+ ## Search and notifications (Class 2)
35
+
36
+ ```python
37
+ from pjlink_advance import PJLinkListener
38
+
39
+ listener = PJLinkListener() # UDP port 4352
40
+ await listener.start()
41
+ print(await listener.discover(duration=3)) # [(ip, mac), ...]
42
+ listener.register("192.168.1.50", lambda command, value: print(command, value))
43
+ ```
44
+
45
+ ## Emulator
46
+
47
+ ```bash
48
+ python -m pjlink_advance.emulator --port 4352 --password secret --pj-class 2
49
+ ```
50
+
51
+ In tests:
52
+
53
+ ```python
54
+ from pjlink_advance.emulator import PJLinkEmulator
55
+
56
+ async with PJLinkEmulator(password="secret") as emulator:
57
+ emulator.unavailable.add("INPT") # answer ERR3
58
+ emulator.fail_next = "ERR4"
59
+ ...
60
+ ```
61
+
62
+ ## License
63
+
64
+ MIT
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pjlink-advance"
7
+ version = "0.1.0"
8
+ description = "Asyncio PJLink Class 1 and Class 2 client with search, status notifications and a projector emulator"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.13"
12
+ authors = [{ name = "Josue" }]
13
+ keywords = ["pjlink", "projector", "asyncio", "home-assistant"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Framework :: AsyncIO",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Topic :: Home Automation",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = []
25
+
26
+ [project.optional-dependencies]
27
+ test = ["pytest>=8", "pytest-asyncio>=0.24"]
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ packages = ["src/pjlink_advance"]
31
+
32
+ [tool.pytest.ini_options]
33
+ asyncio_mode = "auto"
34
+ asyncio_default_fixture_loop_scope = "function"
35
+ testpaths = ["tests"]
36
+
37
+ [tool.ruff]
38
+ line-length = 88
39
+ target-version = "py313"
40
+
41
+ [tool.ruff.lint]
42
+ select = ["E", "F", "W", "I", "UP", "B", "S", "SIM", "RUF", "ASYNC", "PL", "SLF"]
43
+ ignore = ["PLR2004", "PLR0913", "PLR0911", "S104"]
44
+
45
+ [tool.ruff.lint.per-file-ignores]
46
+ "tests/*" = ["S101", "S105", "S106", "SLF001"]
47
+ "src/pjlink_advance/emulator.py" = ["S101"]
@@ -0,0 +1,61 @@
1
+ """Asyncio PJLink Class 1 and Class 2 library."""
2
+
3
+ from .client import PJLinkClient
4
+ from .errors import (
5
+ PJLinkAuthError,
6
+ PJLinkCommandError,
7
+ PJLinkConnectionError,
8
+ PJLinkError,
9
+ PJLinkOutOfParameter,
10
+ PJLinkProjectorFailure,
11
+ PJLinkProtocolError,
12
+ PJLinkUnavailableTime,
13
+ PJLinkUndefinedCommand,
14
+ )
15
+ from .listener import PJLinkListener
16
+ from .models import (
17
+ ERROR_CATEGORIES,
18
+ NO_SIGNAL,
19
+ UNKNOWN_RESOLUTION,
20
+ DeviceInfo,
21
+ ErrorLevel,
22
+ ErrorStatus,
23
+ InputSource,
24
+ InputType,
25
+ Lamp,
26
+ MuteState,
27
+ MuteTarget,
28
+ PowerState,
29
+ ProjectorState,
30
+ Resolution,
31
+ ResolutionValue,
32
+ )
33
+
34
+ __all__ = [
35
+ "ERROR_CATEGORIES",
36
+ "NO_SIGNAL",
37
+ "UNKNOWN_RESOLUTION",
38
+ "DeviceInfo",
39
+ "ErrorLevel",
40
+ "ErrorStatus",
41
+ "InputSource",
42
+ "InputType",
43
+ "Lamp",
44
+ "MuteState",
45
+ "MuteTarget",
46
+ "PJLinkAuthError",
47
+ "PJLinkClient",
48
+ "PJLinkCommandError",
49
+ "PJLinkConnectionError",
50
+ "PJLinkError",
51
+ "PJLinkListener",
52
+ "PJLinkOutOfParameter",
53
+ "PJLinkProjectorFailure",
54
+ "PJLinkProtocolError",
55
+ "PJLinkUnavailableTime",
56
+ "PJLinkUndefinedCommand",
57
+ "PowerState",
58
+ "ProjectorState",
59
+ "Resolution",
60
+ "ResolutionValue",
61
+ ]
@@ -0,0 +1,364 @@
1
+ """Asyncio PJLink client with one persistent, serialized connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import logging
8
+ import time
9
+ from collections.abc import Awaitable, Callable
10
+ from typing import Self
11
+
12
+ from . import protocol
13
+ from .errors import (
14
+ PJLinkAuthError,
15
+ PJLinkCommandError,
16
+ PJLinkConnectionError,
17
+ PJLinkError,
18
+ PJLinkProtocolError,
19
+ PJLinkUndefinedCommand,
20
+ )
21
+ from .models import (
22
+ DeviceInfo,
23
+ ErrorStatus,
24
+ InputSource,
25
+ Lamp,
26
+ MuteState,
27
+ MuteTarget,
28
+ PowerState,
29
+ ProjectorState,
30
+ ResolutionValue,
31
+ )
32
+
33
+ _LOGGER = logging.getLogger(__name__)
34
+
35
+ DEFAULT_TIMEOUT = 5.0
36
+ # Projectors close idle sessions after about 30 s; reconnect before that.
37
+ DEFAULT_MAX_IDLE = 25.0
38
+
39
+
40
+ class _StaleConnectionError(Exception):
41
+ """The session died between commands; safe to retry once."""
42
+
43
+
44
+ class PJLinkClient:
45
+ """Talk to one projector.
46
+
47
+ All commands share one TCP session guarded by a lock, because many
48
+ projectors accept only a single PJLink connection at a time.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ host: str,
54
+ port: int = protocol.PORT,
55
+ password: str | None = None,
56
+ *,
57
+ encoding: str = "utf-8",
58
+ timeout: float = DEFAULT_TIMEOUT,
59
+ max_idle: float = DEFAULT_MAX_IDLE,
60
+ ) -> None:
61
+ self.host = host
62
+ self.port = port
63
+ self.password = password
64
+ self.encoding = encoding
65
+ self.timeout = timeout
66
+ self.max_idle = max_idle
67
+ self._lock = asyncio.Lock()
68
+ self._reader: asyncio.StreamReader | None = None
69
+ self._writer: asyncio.StreamWriter | None = None
70
+ self._digest: str | None = None
71
+ self._last_used = 0.0
72
+
73
+ # ------------------------------------------------------------------ session
74
+
75
+ @property
76
+ def connected(self) -> bool:
77
+ """Return True while a session is open."""
78
+ return self._writer is not None and not self._writer.is_closing()
79
+
80
+ async def connect(self) -> None:
81
+ """Open the session now instead of on the first command."""
82
+ async with self._lock:
83
+ if not self.connected:
84
+ await self._connect()
85
+
86
+ async def close(self) -> None:
87
+ """Close the session."""
88
+ async with self._lock:
89
+ await self._disconnect()
90
+
91
+ async def __aenter__(self) -> Self:
92
+ return self
93
+
94
+ async def __aexit__(self, *_: object) -> None:
95
+ await self.close()
96
+
97
+ async def _connect(self) -> None:
98
+ try:
99
+ self._reader, self._writer = await asyncio.wait_for(
100
+ asyncio.open_connection(self.host, self.port), self.timeout
101
+ )
102
+ except (OSError, TimeoutError) as err:
103
+ raise PJLinkConnectionError(
104
+ f"Cannot connect to {self.host}:{self.port}: {err}"
105
+ ) from err
106
+ try:
107
+ salt = protocol.parse_greeting(await self._readline())
108
+ except _StaleConnectionError as err:
109
+ await self._disconnect()
110
+ raise PJLinkConnectionError("Projector closed the connection") from err
111
+ except PJLinkError:
112
+ await self._disconnect()
113
+ raise
114
+ if salt is None:
115
+ self._digest = None
116
+ elif self.password is None:
117
+ await self._disconnect()
118
+ raise PJLinkAuthError("Projector requires a password")
119
+ else:
120
+ self._digest = protocol.auth_digest(salt, self.password)
121
+ self._last_used = time.monotonic()
122
+
123
+ async def _disconnect(self) -> None:
124
+ writer, self._reader, self._writer = self._writer, None, None
125
+ self._digest = None
126
+ if writer is not None:
127
+ writer.close()
128
+ with contextlib.suppress(Exception):
129
+ await writer.wait_closed()
130
+
131
+ async def _readline(self) -> str:
132
+ if self._reader is None:
133
+ raise _StaleConnectionError
134
+ try:
135
+ raw = await asyncio.wait_for(
136
+ self._reader.readuntil(protocol.TERMINATOR), self.timeout
137
+ )
138
+ except TimeoutError as err:
139
+ raise PJLinkConnectionError("Projector did not answer in time") from err
140
+ except asyncio.IncompleteReadError as err:
141
+ raise _StaleConnectionError from err
142
+ except asyncio.LimitOverrunError as err:
143
+ raise PJLinkProtocolError("Response too long") from err
144
+ except ConnectionError as err:
145
+ raise _StaleConnectionError from err
146
+ return self._decode(raw.rstrip(b"\r\n"))
147
+
148
+ def _decode(self, raw: bytes) -> str:
149
+ try:
150
+ return raw.decode(self.encoding)
151
+ except UnicodeDecodeError:
152
+ return raw.decode("latin-1")
153
+
154
+ # ------------------------------------------------------------------ commands
155
+
156
+ async def command(self, pj_class: int, command: str, param: str = "?") -> str:
157
+ """Send one command and return the response value."""
158
+ payload = protocol.encode_command(pj_class, command, param)
159
+ async with self._lock:
160
+ for attempt in range(2):
161
+ if (
162
+ self.connected
163
+ and time.monotonic() - self._last_used > self.max_idle
164
+ ):
165
+ await self._disconnect()
166
+ if not self.connected:
167
+ await self._connect()
168
+ try:
169
+ return await self._exchange(payload, pj_class, command)
170
+ except _StaleConnectionError as err:
171
+ await self._disconnect()
172
+ if attempt:
173
+ raise PJLinkConnectionError(
174
+ "Projector closed the connection"
175
+ ) from err
176
+ except (PJLinkConnectionError, PJLinkAuthError, PJLinkProtocolError):
177
+ await self._disconnect()
178
+ raise
179
+ raise AssertionError("unreachable") # pragma: no cover
180
+
181
+ async def _exchange(self, payload: bytes, pj_class: int, command: str) -> str:
182
+ if self._writer is None:
183
+ raise _StaleConnectionError
184
+ if self._digest:
185
+ payload = self._digest.encode() + payload
186
+ try:
187
+ self._writer.write(payload)
188
+ await self._writer.drain()
189
+ except ConnectionError as err:
190
+ raise _StaleConnectionError from err
191
+ line = await self._readline()
192
+ self._digest = None
193
+ self._last_used = time.monotonic()
194
+ _LOGGER.debug("%s <- %r -> %r", self.host, payload, line)
195
+ return protocol.parse_response(line, pj_class, command)
196
+
197
+ # ------------------------------------------------------------------ Class 1
198
+
199
+ async def get_power(self) -> PowerState:
200
+ """Return the power state."""
201
+ return protocol.decode_power(await self.command(1, "POWR"))
202
+
203
+ async def set_power(self, on: bool) -> None:
204
+ """Turn the projector on or off."""
205
+ await self.command(1, "POWR", "1" if on else "0")
206
+
207
+ async def get_input(self) -> InputSource:
208
+ """Return the selected input."""
209
+ return protocol.decode_input(await self.command(1, "INPT"))
210
+
211
+ async def set_input(self, source: InputSource) -> None:
212
+ """Select an input."""
213
+ await self.command(2 if source.requires_class2 else 1, "INPT", source.code)
214
+
215
+ async def get_inputs(self, pj_class: int = 1) -> list[InputSource]:
216
+ """Return the available inputs."""
217
+ return protocol.decode_inputs(await self.command(pj_class, "INST"))
218
+
219
+ async def get_av_mute(self) -> MuteState:
220
+ """Return the audio/video mute state."""
221
+ return protocol.decode_av_mute(await self.command(1, "AVMT"))
222
+
223
+ async def set_av_mute(self, target: MuteTarget, on: bool) -> None:
224
+ """Mute or unmute video, audio or both."""
225
+ await self.command(1, "AVMT", f"{target.value}{int(on)}")
226
+
227
+ async def get_errors(self) -> ErrorStatus:
228
+ """Return the error status."""
229
+ return protocol.decode_errors(await self.command(1, "ERST"))
230
+
231
+ async def get_lamps(self) -> list[Lamp]:
232
+ """Return hours and state of every lamp / light source."""
233
+ return protocol.decode_lamps(await self.command(1, "LAMP"))
234
+
235
+ async def get_name(self) -> str:
236
+ """Return the projector name."""
237
+ return await self.command(1, "NAME")
238
+
239
+ async def get_manufacturer(self) -> str:
240
+ """Return the manufacturer (INF1)."""
241
+ return await self.command(1, "INF1")
242
+
243
+ async def get_model(self) -> str:
244
+ """Return the model (INF2)."""
245
+ return await self.command(1, "INF2")
246
+
247
+ async def get_other_info(self) -> str:
248
+ """Return other information (INFO)."""
249
+ return await self.command(1, "INFO")
250
+
251
+ async def get_class(self) -> int:
252
+ """Return the PJLink class supported by the projector."""
253
+ value = await self.command(1, "CLSS")
254
+ return 2 if value.strip() == "2" else 1
255
+
256
+ # ------------------------------------------------------------------ Class 2
257
+
258
+ async def get_serial(self) -> str:
259
+ """Return the serial number."""
260
+ return await self.command(2, "SNUM")
261
+
262
+ async def get_software_version(self) -> str:
263
+ """Return the software version."""
264
+ return await self.command(2, "SVER")
265
+
266
+ async def get_input_name(self, source: InputSource) -> str:
267
+ """Return the name of an input terminal."""
268
+ return await self.command(2, "INNM", f"?{source.code}")
269
+
270
+ async def get_input_resolution(self) -> ResolutionValue:
271
+ """Return the resolution of the current input signal."""
272
+ return protocol.decode_resolution(await self.command(2, "IRES"))
273
+
274
+ async def get_recommended_resolution(self) -> ResolutionValue:
275
+ """Return the native resolution recommended by the projector."""
276
+ return protocol.decode_resolution(await self.command(2, "RRES"))
277
+
278
+ async def get_filter_hours(self) -> int:
279
+ """Return the filter usage time in hours."""
280
+ return protocol.decode_int(await self.command(2, "FILT"))
281
+
282
+ async def get_lamp_model(self) -> str:
283
+ """Return the replacement lamp model."""
284
+ return await self.command(2, "RLMP")
285
+
286
+ async def get_filter_model(self) -> str:
287
+ """Return the replacement filter model."""
288
+ return await self.command(2, "RFIL")
289
+
290
+ async def speaker_volume(self, *, up: bool) -> None:
291
+ """Step the speaker volume."""
292
+ await self.command(2, "SVOL", "1" if up else "0")
293
+
294
+ async def mic_volume(self, *, up: bool) -> None:
295
+ """Step the microphone volume."""
296
+ await self.command(2, "MVOL", "1" if up else "0")
297
+
298
+ async def get_freeze(self) -> bool:
299
+ """Return True if the image is frozen."""
300
+ return protocol.decode_bool(await self.command(2, "FREZ"))
301
+
302
+ async def set_freeze(self, on: bool) -> None:
303
+ """Freeze or unfreeze the image."""
304
+ await self.command(2, "FREZ", "1" if on else "0")
305
+
306
+ async def send_raw(self, command: str, param: str = "?", pj_class: int = 1) -> str:
307
+ """Send any command and return the raw response value."""
308
+ return await self.command(pj_class, command, param)
309
+
310
+ # ------------------------------------------------------------------ bulk
311
+
312
+ async def fetch_static(self) -> DeviceInfo:
313
+ """Read information that rarely changes."""
314
+ pj_class = await self.get_class()
315
+ info = DeviceInfo(
316
+ name=await _optional(self.get_name) or "",
317
+ manufacturer=await _optional(self.get_manufacturer) or "",
318
+ model=await _optional(self.get_model) or "",
319
+ other_info=await _optional(self.get_other_info) or "",
320
+ pj_class=pj_class,
321
+ )
322
+ info.inputs = await _optional(lambda: self.get_inputs(pj_class)) or []
323
+ if pj_class < 2:
324
+ return info
325
+ info.serial = await _optional(self.get_serial) or None
326
+ info.software_version = await _optional(self.get_software_version) or None
327
+ for source in info.inputs:
328
+ name = await _optional(lambda source=source: self.get_input_name(source))
329
+ if name:
330
+ info.input_names[source.code] = name
331
+ info.lamp_model = await _optional(self.get_lamp_model) or None
332
+ info.filter_model = await _optional(self.get_filter_model) or None
333
+ info.recommended_resolution = await _optional(self.get_recommended_resolution)
334
+ return info
335
+
336
+ async def fetch_state(self, *, full: bool, pj_class: int) -> ProjectorState:
337
+ """Read the current state. ``full`` adds errors, lamps and filter."""
338
+ state = ProjectorState(power=await self.get_power())
339
+ if state.power.is_on:
340
+ state.input = await _optional(self.get_input)
341
+ state.mute = await _optional(self.get_av_mute)
342
+ if pj_class >= 2:
343
+ state.freeze = await _optional(self.get_freeze)
344
+ state.input_resolution = await _optional(self.get_input_resolution)
345
+ if full:
346
+ state.errors = await _optional(self.get_errors)
347
+ try:
348
+ state.lamps = await self.get_lamps()
349
+ except PJLinkUndefinedCommand:
350
+ state.lamps = []
351
+ except (PJLinkCommandError, PJLinkProtocolError):
352
+ state.lamps = None
353
+ if pj_class >= 2:
354
+ state.filter_hours = await _optional(self.get_filter_hours)
355
+ return state
356
+
357
+
358
+ async def _optional[T](fetch: Callable[[], Awaitable[T]]) -> T | None:
359
+ """Run a query whose failure must not break a bulk read."""
360
+ try:
361
+ return await fetch()
362
+ except (PJLinkCommandError, PJLinkProtocolError) as err:
363
+ _LOGGER.debug("Optional query failed: %s", err)
364
+ return None