pyjvcprojector-test 1.1.2__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.
@@ -0,0 +1,5 @@
1
+ """A python library for controlling a JVC Projector over a network connection."""
2
+
3
+ # ruff: noqa: F401
4
+
5
+ __version__ = "1.1.2"
@@ -0,0 +1,366 @@
1
+ """Module for representing a JVC Projector command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ import logging
7
+ import re
8
+ from typing import Final, Any
9
+ import math
10
+ from . import const
11
+
12
+ _LOGGER = logging.getLogger(__name__)
13
+
14
+ PJOK: Final = b"PJ_OK"
15
+ PJNG: Final = b"PJ_NG"
16
+ PJREQ: Final = b"PJREQ"
17
+ PJACK: Final = b"PJACK"
18
+ PJNAK: Final = b"PJNAK"
19
+
20
+ UNIT_ID: Final = b"\x89\x01"
21
+ HEAD_OP: Final = b"!" + UNIT_ID
22
+ HEAD_REF: Final = b"?" + UNIT_ID
23
+ HEAD_RES: Final = b"@" + UNIT_ID
24
+ HEAD_ACK: Final = b"\x06" + UNIT_ID
25
+ HEAD_LEN: Final = 1 + len(UNIT_ID)
26
+ END: Final = b"\n"
27
+
28
+ TEST: Final = "\0\0"
29
+
30
+ AUTH_SALT: Final = "JVCKWPJ"
31
+
32
+
33
+ class JvcCommand:
34
+ """Class for representing a JVC Projector command."""
35
+
36
+ def __init__(self, code: str, is_ref=False):
37
+ """Initialize class."""
38
+ self.code = code
39
+ self.is_ref = is_ref
40
+ self.ack = False
41
+ self._response: str | None = None
42
+
43
+ @property
44
+ def response(self) -> str | None:
45
+ """Return command response."""
46
+ if not self.is_ref or self._response is None:
47
+ return None
48
+
49
+ res = self.code + self._response
50
+ val: str = res[len(self.code) :]
51
+
52
+ for pat, fmt in self.formatters.items():
53
+ m = re.search(r"^" + pat + r"$", res)
54
+ if m:
55
+ if isinstance(fmt, list):
56
+ try:
57
+ index = int(m[1], 16)
58
+ if 0 <= index < len(fmt):
59
+ return fmt[index]
60
+ return val # noqa: TRY300
61
+ except ValueError:
62
+ msg = "response '%s' not int for cmd '%s'"
63
+ _LOGGER.warning(msg, val, self.code)
64
+ elif isinstance(fmt, dict):
65
+ try:
66
+ return fmt[m[1]]
67
+ except KeyError:
68
+ msg = "response '%s' not mapped for cmd '%s'"
69
+ _LOGGER.warning(msg, val, self.code)
70
+ elif callable(fmt):
71
+ try:
72
+ return fmt(m)
73
+ except Exception as e: # noqa: BLE001
74
+ msg = "response format failed with %s for '%s (%s)'"
75
+ _LOGGER.warning(msg, e, self.code, val)
76
+ break
77
+
78
+ return val
79
+
80
+ @response.setter
81
+ def response(self, data: str) -> None:
82
+ """Set command response."""
83
+ self._response = data
84
+
85
+ @property
86
+ def is_power(self) -> bool:
87
+ """Return if command is a power command."""
88
+ return self.code.startswith("PW")
89
+
90
+ @staticmethod
91
+ def _build_command_map(
92
+ formatters: dict[str, list | dict | Callable],
93
+ ) -> dict[str, dict[str, Any]]:
94
+ """Use the Formatters object in JvcCommand to build a command map to reduce code duplication."""
95
+ command_map = {}
96
+ for pattern, formatter in formatters.items():
97
+ opcode = pattern.split("(")[0] # Extract opcode from the f-string
98
+ if isinstance(formatter, dict):
99
+ command_map[opcode] = {
100
+ "values": formatter,
101
+ "inverse": {v: k for k, v in formatter.items()},
102
+ }
103
+ elif isinstance(formatter, list):
104
+ command_map[opcode] = {
105
+ "values": {
106
+ str(i): val
107
+ for i, val in enumerate(formatter)
108
+ if val is not None
109
+ },
110
+ "inverse": {
111
+ val: str(i)
112
+ for i, val in enumerate(formatter)
113
+ if val is not None
114
+ },
115
+ }
116
+ elif callable(formatter):
117
+ command_map[opcode] = {"values": {"callable": "callable"}}
118
+ else:
119
+ command_map[opcode] = {"values": formatter}
120
+ return command_map
121
+
122
+ formatters: dict[str, list | dict | Callable] = {
123
+ f"{const.CMD_POWER}(.)": const.VAL_POWER,
124
+ f"{const.CMD_INPUT}(.)": const.VAL_INPUT,
125
+ f"{const.CMD_SOURCE}(.)": const.VAL_SOURCE,
126
+ f"{const.CMD_MODEL}(.+)": lambda r: re.sub(r"-+", "-", r[1].replace(" ", "-")),
127
+ f"{const.CMD_PICTURE_MODE}(..)": const.VAL_PICTURE_MODE,
128
+ f"{const.CMD_PICTURE_MODE_INTELLIGENT_APERTURE}(.)": const.VAL_INTELLIGENT_APERTURE,
129
+ f"{const.CMD_LASER_DIMMING}(.)": const.VAL_LASER_DIMMING,
130
+ f"{const.CMD_PICTURE_MODE_COLOR_PROFILE}(..)": const.VAL_COLOR_PROFILE,
131
+ f"{const.CMD_PICTURE_MODE_COLOR_TEMP}(..)": const.VAL_COLOR_TEMP,
132
+ f"{const.CMD_PICTURE_MODE_COLOR_CORRECTION}(..)": const.VAL_COLOR_CORRECTION,
133
+ f"{const.CMD_PICTURE_MODE_GAMMA_TABLE}(..)": const.VAL_GAMMA_TABLE,
134
+ f"{const.CMD_PICTURE_MODE_COLOR_MANAGEMENT}(.)": const.VAL_TOGGLE,
135
+ f"{const.CMD_PICTURE_MODE_LOW_LATENCY}(.)": const.VAL_TOGGLE,
136
+ f"{const.CMD_PICTURE_MODE_8K_ESHIFT}(.)": const.VAL_TOGGLE,
137
+ f"{const.CMD_PICTURE_MODE_CLEAR_MOTION_DRIVE}(.)": const.VAL_CLEAR_MOTION_DRIVE,
138
+ f"{const.CMD_PICTURE_MODE_LASER_VALUE}(.+)": lambda r: math.floor(
139
+ ((int(r[1], 16) - 109) / 1.1) + 0.5
140
+ ),
141
+ f"{const.CMD_PICTURE_MODE_MOTION_ENHANCE}(.)": const.VAL_MOTION_ENHANCE,
142
+ f"{const.CMD_PICTURE_MODE_LASER_POWER}(.)": const.VAL_LASER_POWER,
143
+ f"{const.CMD_PICTURE_MODE_GRAPHICS_MODE}(.)": const.VAL_GRAPHICS_MODE,
144
+ f"{const.CMD_INPUT_SIGNAL_HDMI_INPUT_LEVEL}(.)": const.VAL_HDMI_INPUT_LEVEL,
145
+ f"{const.CMD_INPUT_SIGNAL_HDMI_COLOR_SPACE}(.)": const.VAL_HDMI_COLOR_SPACE,
146
+ f"{const.CMD_INPUT_SIGNAL_HDMI_2D_3D}(.)": const.VAL_HDMI_2D_3D,
147
+ f"{const.CMD_INPUT_SIGNAL_ASPECT}(.)": const.VAL_ASPECT,
148
+ f"{const.CMD_INPUT_SIGNAL_MASK}(.)": const.VAL_MASK,
149
+ f"{const.CMD_INSTALLATION_MODE}(.)": const.VAL_INSTALLATION_MODE,
150
+ f"{const.CMD_INSTALLATION_LENS_CONTROL}(.)": const.VAL_LENS_CONTROL,
151
+ f"{const.CMD_INSTALLATION_LENS_IMAGE_PATTERN}(.)": const.VAL_TOGGLE,
152
+ f"{const.CMD_INSTALLATION_LENS_LOCK}(.)": const.VAL_TOGGLE,
153
+ f"{const.CMD_INSTALLATION_SCREEN_ADJUST}(.)": const.VAL_TOGGLE,
154
+ f"{const.CMD_INSTALLATION_STYLE}(.)": const.VAL_INSTALLATION_STYLE,
155
+ f"{const.CMD_INSTALLATION_ANAMORPHIC}(.)": const.VAL_ANAMORPHIC,
156
+ f"{const.CMD_DISPLAY_BACK_COLOR}(.)": const.VAL_BACK_COLOR,
157
+ f"{const.CMD_DISPLAY_MENU_POSITION}(.)": const.VAL_MENU_POSITION,
158
+ f"{const.CMD_DISPLAY_SOURCE_DISPLAY}(.)": const.VAL_TOGGLE,
159
+ f"{const.CMD_DISPLAY_LOGO}(.)": const.VAL_TOGGLE,
160
+ f"{const.CMD_FUNCTION_TRIGGER}(.)": const.VAL_TRIGGER,
161
+ f"{const.CMD_FUNCTION_OFF_TIMER}(.)": const.VAL_OFF_TIMER,
162
+ f"{const.CMD_FUNCTION_ECO_MODE}(.)": const.VAL_TOGGLE,
163
+ f"{const.CMD_FUNCTION_CONTROL4}(.)": const.VAL_TOGGLE,
164
+ f"{const.CMD_FUNCTION_INPUT}(.)": const.VAL_FUNCTION_INPUT,
165
+ f"{const.CMD_FUNCTION_SOURCE}(..)": const.VAL_FUNCTION_SOURCE,
166
+ f"{const.CMD_FUNCTION_DEEP_COLOR}(.)": const.VAL_DEEP_COLOR,
167
+ f"{const.CMD_FUNCTION_COLOR_SPACE}(.)": const.VAL_COLOR_SPACE,
168
+ f"{const.CMD_FUNCTION_COLORIMETRY}(.)": const.VAL_COLORIMETRY,
169
+ f"{const.CMD_FUNCTION_HDR}(.)": const.VAL_HDR,
170
+ f"{const.CMD_FUNCTION_LASER_TIME}(.+)": lambda r: int(r[1], 16),
171
+ f"{const.CMD_PICTURE_MODE_HDR_LEVEL}(.)": const.VAL_HDR_LEVEL,
172
+ f"{const.CMD_PICTURE_MODE_HDR_PROCESSING}(.)": const.VAL_HDR_PROCESSING,
173
+ f"{const.CMD_PICTURE_MODE_HDR_CONTENT_TYPE}(.)": const.VAL_HDR_CONTENT_TYPE,
174
+ f"{const.CMD_PICTURE_MODE_THEATER_OPTIMIZER}(.)": const.VAL_TOGGLE,
175
+ f"{const.CMD_PICTURE_MODE_THEATER_OPTIMIZER_LEVEL}(.)": const.VAL_THEATER_OPTIMIZER_LEVEL,
176
+ f"{const.CMD_PICTURE_MODE_THEATER_OPTIMIZER_PROCESSING}(.)": const.VAL_THEATER_OPTIMIZER_PROCESSING,
177
+ f"{const.CMD_LAN_SETUP_DHCP}(.)": const.VAL_TOGGLE,
178
+ f"{const.CMD_LAN_SETUP_MAC_ADDRESS}(.+)": lambda r: re.sub(
179
+ r"-+", "-", r[1].replace(" ", "-")
180
+ ),
181
+ f"{const.CMD_LAN_SETUP_IP_ADDRESS}(..)(..)(..)(..)": lambda r: f"{int(r[1], 16)}.{int(r[2], 16)}.{int(r[3], 16)}.{int(r[4], 16)}",
182
+ }
183
+
184
+ command_map: dict[str, dict[str, Any]] = _build_command_map(formatters)
185
+
186
+ @staticmethod
187
+ def get_available_commands() -> dict[str, str]:
188
+ """Return a map of commands to their allowed values/responses based on the available command_map."""
189
+
190
+ human_commands: dict[str, str] = {}
191
+ for cmd, values in JvcCommandHelpers.get_available_commands().items():
192
+ human_commands[cmd] = values["values"]
193
+ return human_commands
194
+
195
+
196
+ class JvcCommandHelpers:
197
+ """Helper methods for JVC Command handling and documentation."""
198
+
199
+ # Define override maps for commands where input values differ from return values
200
+ COMMAND_VALUE_OVERRIDES = {
201
+ "power": [
202
+ "on",
203
+ "standby",
204
+ ], # Can only send standby/on, even though we might receive other states
205
+ "source": None, # Read-only, can't send values
206
+ "laser_time": None, # Read-only, can't send values
207
+ }
208
+
209
+ @staticmethod
210
+ def format_value_name(value: str) -> str:
211
+ """Format a command value into a human-readable string."""
212
+ # Replace underscores with spaces
213
+ formatted = value.replace("_", " ")
214
+
215
+ # make sure all words are lowercase
216
+ return " ".join(word.lower() for word in formatted.split())
217
+
218
+ @staticmethod
219
+ def format_command_name(command: str) -> str:
220
+ """Format a command name into a human-readable string."""
221
+ # Remove KEY_ prefix if present
222
+ command = re.sub(r"^KEY_", "", command)
223
+ # Replace underscores with spaces
224
+ formatted = command.replace("_", " ")
225
+ # Capitalize first letter of each word
226
+ return " ".join(word.capitalize() for word in formatted.split())
227
+
228
+ @staticmethod
229
+ def format_value_list(values: list[str] | dict[str, str]) -> list[str]:
230
+ """Format a list or dict of values into human-readable strings."""
231
+ if isinstance(values, dict):
232
+ # For dictionaries, we only want the values, not the keys
233
+ value_list = list(values.values())
234
+ else:
235
+ value_list = values
236
+
237
+ return [JvcCommandHelpers.format_value_name(str(val)) for val in value_list]
238
+
239
+ @classmethod
240
+ def get_command_values(
241
+ cls, command: str, values: list[str] | dict[str, str]
242
+ ) -> list[str] | None:
243
+ """Get the appropriate command values, taking into account any overrides.
244
+
245
+ Args:
246
+ command: The command key
247
+ values: The default values from the command map
248
+
249
+ Returns:
250
+ List of valid input values for the command or None if read-only
251
+
252
+ """
253
+ # Check if we have an override for this command
254
+ if command in cls.COMMAND_VALUE_OVERRIDES:
255
+ return cls.COMMAND_VALUE_OVERRIDES[command]
256
+
257
+ # No override, process normal values
258
+ return cls.format_value_list(values)
259
+
260
+ @classmethod
261
+ def get_available_commands(cls) -> dict[str, dict[str, Any]]:
262
+ """Return a detailed map of commands and their allowed values/responses.
263
+
264
+ Returns:
265
+ Dict with structure:
266
+ {
267
+ "command_name": {
268
+ "name": "Human Readable Name",
269
+ "values": ["Value 1", "Value 2"],
270
+ "description": "Command description",
271
+ "type": "enum|range|read_only",
272
+ "command": "PJ_COMMAND" # The raw projector command
273
+ }
274
+ }
275
+
276
+ """
277
+ human_commands: dict[str, dict[str, Any]] = {}
278
+
279
+ # Command category descriptions
280
+ categories = {
281
+ "POWER": "Controls projector power state",
282
+ "INPUT": "Selects input source",
283
+ "PICTURE_MODE": "Controls picture mode settings",
284
+ "INSTALLATION": "Controls installation and setup options",
285
+ "HDR": "Controls HDR-related settings",
286
+ "LASER": "Controls laser and brightness settings",
287
+ "COLOR": "Controls color-related settings",
288
+ "MOTION": "Controls motion-related settings",
289
+ }
290
+
291
+ for human_cmd, pj_cmd in const.KEY_MAP_TO_COMMAND.items():
292
+ command_data = JvcCommand.command_map.get(pj_cmd, {})
293
+
294
+ # Skip if no command data found
295
+ if not command_data:
296
+ continue
297
+
298
+ # Determine command category
299
+ category = next(
300
+ (cat for cat in categories if cat in human_cmd.upper()),
301
+ "GENERAL",
302
+ )
303
+
304
+ values = command_data.get("values", {})
305
+
306
+ command_info = {
307
+ "name": cls.format_command_name(human_cmd),
308
+ "category": category,
309
+ "description": categories.get(category, "General setting"),
310
+ "command": pj_cmd,
311
+ }
312
+
313
+ # Handle different value types
314
+ if values == "callable":
315
+ command_info["values"] = '["0-100"]'
316
+ command_info["type"] = "range"
317
+ elif isinstance(values, (list, dict)):
318
+ command_values = cls.get_command_values(human_cmd, values)
319
+ if command_values is None:
320
+ command_info["values"] = ""
321
+ command_info["type"] = "read_only"
322
+ else:
323
+ command_info["values"] = ", ".join(
324
+ f'"{val}"' for val in command_values
325
+ )
326
+ command_info["type"] = "enum"
327
+ else:
328
+ command_info["values"] = ""
329
+ command_info["type"] = "unknown"
330
+
331
+ human_commands[human_cmd] = command_info
332
+
333
+ return human_commands
334
+
335
+ @classmethod
336
+ def get_command_help(cls, command: str) -> str:
337
+ """Generate a human-readable help string for a specific command.
338
+
339
+ Args:
340
+ command: The command key to get help for
341
+
342
+ Returns:
343
+ A formatted help string with command details
344
+
345
+ """
346
+ commands = cls.get_available_commands()
347
+ if command not in commands:
348
+ return f"Unknown command: {command}"
349
+
350
+ cmd_info = commands[command]
351
+
352
+ help_text = [
353
+ f"Command: {cmd_info['name']}",
354
+ f"Category: {cmd_info['category']}",
355
+ f"Description: {cmd_info['description']}",
356
+ ]
357
+
358
+ if cmd_info["type"] == "read_only":
359
+ help_text.append("Type: Read Only")
360
+ elif cmd_info["type"] == "range":
361
+ help_text.append("Accepts values: 0-100")
362
+ elif cmd_info["values"]:
363
+ help_text.append("Available values:")
364
+ help_text.extend(f" - {value}" for value in cmd_info["values"])
365
+
366
+ return "\n".join(help_text)
@@ -0,0 +1,77 @@
1
+ """Module for representing a JVC Projector network connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import socket
7
+
8
+ import aiodns
9
+
10
+ from .error import JvcProjectorConnectError
11
+
12
+
13
+ class JvcConnection:
14
+ """Class for representing a JVC Projector network connection."""
15
+
16
+ def __init__(self, ip: str, port: int, timeout: float):
17
+ """Initialize class."""
18
+ self._ip = ip
19
+ self._port = port
20
+ self._timeout = timeout
21
+ self._reader: asyncio.StreamReader | None = None
22
+ self._writer: asyncio.StreamWriter | None = None
23
+
24
+ @property
25
+ def ip(self) -> str:
26
+ """Return ip address."""
27
+ return self._ip
28
+
29
+ @property
30
+ def port(self) -> int:
31
+ """Return port."""
32
+ return self._port
33
+
34
+ def is_connected(self) -> bool:
35
+ """Return if connected to device."""
36
+ return self._reader is not None and self._writer is not None
37
+
38
+ async def connect(self) -> None:
39
+ """Connect to device."""
40
+ assert self._reader is None and self._writer is None
41
+ conn = asyncio.open_connection(self._ip, self._port)
42
+ self._reader, self._writer = await asyncio.wait_for(conn, timeout=self._timeout)
43
+
44
+ async def read(self, n: int) -> bytes:
45
+ """Read n bytes from device."""
46
+ assert self._reader
47
+ return await asyncio.wait_for(self._reader.read(n), timeout=self._timeout)
48
+
49
+ async def readline(self) -> bytes:
50
+ """Read all bytes up to newline from device."""
51
+ assert self._reader
52
+ return await asyncio.wait_for(self._reader.readline(), timeout=self._timeout)
53
+
54
+ async def write(self, data: bytes) -> None:
55
+ """Write data to device."""
56
+ assert self._writer
57
+ self._writer.write(data)
58
+ await self._writer.drain()
59
+
60
+ async def disconnect(self) -> None:
61
+ """Disconnect from device."""
62
+ if self._writer:
63
+ self._writer.close()
64
+ self._writer = None
65
+ self._reader = None
66
+
67
+
68
+ async def resolve(host: str) -> str:
69
+ """Resolve hostname to ip address."""
70
+ try:
71
+ res = await aiodns.DNSResolver().gethostbyname(host, socket.AF_INET)
72
+ if len(res.addresses) < 1:
73
+ raise JvcProjectorConnectError("Unexpected zero length addresses response")
74
+ except aiodns.error.DNSError as err:
75
+ raise JvcProjectorConnectError(f"Failed to resolve host {host}") from err
76
+
77
+ return res.addresses[0]