grafikeye 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,64 @@
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ build:
12
+ name: Build
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+
18
+ - uses: astral-sh/setup-uv@v6
19
+
20
+ - name: Verify version
21
+ run: |
22
+ python - <<'PY'
23
+ import os
24
+ import tomllib
25
+
26
+ with open("pyproject.toml", "rb") as file:
27
+ version = tomllib.load(file)["project"]["version"]
28
+
29
+ tag = os.environ["GITHUB_REF_NAME"]
30
+
31
+ if tag != f"v{version}":
32
+ raise SystemExit(f"Release tag {tag} does not match package version {version}")
33
+ PY
34
+
35
+ - name: Build package
36
+ run: uv build
37
+
38
+ - name: Upload distributions
39
+ uses: actions/upload-artifact@v4
40
+ with:
41
+ name: distributions
42
+ path: dist/
43
+
44
+ publish:
45
+ name: Publish to PyPI
46
+ needs: build
47
+ runs-on: ubuntu-latest
48
+
49
+ environment:
50
+ name: pypi
51
+ url: https://pypi.org/p/grafikeye
52
+
53
+ permissions:
54
+ id-token: write
55
+
56
+ steps:
57
+ - name: Download distributions
58
+ uses: actions/download-artifact@v4
59
+ with:
60
+ name: distributions
61
+ path: dist/
62
+
63
+ - name: Publish to PyPI
64
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,223 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # uv
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Conda environments
163
+ conda-meta/
164
+
165
+ # Spyder project settings
166
+ .spyderproject
167
+ .spyproject
168
+
169
+ # Rope project settings
170
+ .ropeproject
171
+
172
+ # mkdocs/Zensical documentation
173
+ /site
174
+
175
+ # mypy
176
+ .mypy_cache/
177
+ .dmypy.json
178
+ dmypy.json
179
+
180
+ # Pyre type checker
181
+ .pyre/
182
+
183
+ # pytype static type analyzer
184
+ .pytype/
185
+
186
+ # Cython debug symbols
187
+ cython_debug/
188
+
189
+ # PyCharm
190
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
191
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
192
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
193
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
194
+ # .idea/
195
+
196
+ # Abstra
197
+ # Abstra is an AI-powered process automation framework.
198
+ # Ignore directories containing user credentials, local state, and settings.
199
+ # Learn more at https://abstra.io/docs
200
+ .abstra/
201
+
202
+ # Visual Studio Code
203
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
204
+ # can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
205
+ # and can be added to the global gitignore or merged into this file. However, if you prefer, you
206
+ # could uncomment the following to ignore the entire vscode folder
207
+ # .vscode/
208
+ # Temporary file for partial code execution
209
+ tempCodeRunnerFile.py
210
+
211
+ # Ruff stuff:
212
+ .ruff_cache/
213
+
214
+ # PyPI configuration file
215
+ .pypirc
216
+
217
+ # Marimo
218
+ marimo/_static/
219
+ marimo/_lsp/
220
+ __marimo__/
221
+
222
+ # Streamlit
223
+ .streamlit/secrets.toml
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.5
2
+ Name: grafikeye
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for Lutron GRAFIK Eye 3000 and 4000 Series lighting systems
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: telnetlib3
8
+ Description-Content-Type: text/markdown
9
+
10
+ # GRAFIK Eye
11
+
12
+ Asynchronous Python library for controlling Lutron GRAFIK Eye lighting systems over Telnet.
13
+
14
+ Supports the GRAFIK Eye 3000 and 4000 Series through the GRX-CI-NWK-E Ethernet interface.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install grafikeye
20
+ ```
21
+
22
+ ## Documentation
23
+
24
+ - [GRAFIK Eye RS232/Ethernet Protocol Reference](https://assets.lutron.com/a/documents/040196d.pdf)
25
+ - [GRAFIK Eye Control Interface Operating Instructions](https://assets.lutron.com/a/documents/040229aeng.pdf)
@@ -0,0 +1,16 @@
1
+ # GRAFIK Eye
2
+
3
+ Asynchronous Python library for controlling Lutron GRAFIK Eye lighting systems over Telnet.
4
+
5
+ Supports the GRAFIK Eye 3000 and 4000 Series through the GRX-CI-NWK-E Ethernet interface.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install grafikeye
11
+ ```
12
+
13
+ ## Documentation
14
+
15
+ - [GRAFIK Eye RS232/Ethernet Protocol Reference](https://assets.lutron.com/a/documents/040196d.pdf)
16
+ - [GRAFIK Eye Control Interface Operating Instructions](https://assets.lutron.com/a/documents/040229aeng.pdf)
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "grafikeye"
7
+ version = "0.1.0"
8
+ description = "Asynchronous Python client for Lutron GRAFIK Eye 3000 and 4000 Series lighting systems"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dependencies = [
13
+ "telnetlib3",
14
+ ]
15
+
16
+ [dependency-groups]
17
+ dev = [
18
+ "textual",
19
+ "pytest",
20
+ "pytest-asyncio",
21
+ "ruff",
22
+ "pytest-cov>=7.1.0",
23
+ ]
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/grafikeye"]
27
+
28
+ [tool.pytest.ini_options]
29
+ testpaths = ["tests"]
30
+ addopts = ["--import-mode=importlib"]
31
+ asyncio_mode = "auto"
32
+ asyncio_default_fixture_loop_scope = "function"
33
+
34
+ [tool.ruff]
35
+ target-version = "py310"
36
+ line-length = 88
37
+
38
+ [tool.ruff.lint]
39
+ select = [
40
+ "E4", # Import errors
41
+ "E7", # Statement errors
42
+ "E9", # Runtime errors
43
+ "F", # Pyflakes
44
+ "I", # Import sorting
45
+ "UP", # Modern Python syntax
46
+ "B", # Common bugs
47
+ "ASYNC", # Async programming
48
+ "RUF", # Ruff-specific rules
49
+ ]
50
+
51
+ [tool.ruff.format]
52
+ quote-style = "double"
53
+ indent-style = "space"
54
+
55
+ [tool.uv.workspace]
56
+ members = [
57
+ "test",
58
+ ]
@@ -0,0 +1,19 @@
1
+ from .client import ConnectionStatus, ControlUnit, GrafikEyeClient
2
+ from .exceptions import (
3
+ GrafikEyeAuthenticationError,
4
+ GrafikEyeClientError,
5
+ GrafikEyeConnectionError,
6
+ GrafikEyeConnectionInUseError,
7
+ GrafikEyeConnectionTimeoutError,
8
+ )
9
+
10
+ __all__ = [
11
+ "ConnectionStatus",
12
+ "ControlUnit",
13
+ "GrafikEyeAuthenticationError",
14
+ "GrafikEyeClient",
15
+ "GrafikEyeClientError",
16
+ "GrafikEyeConnectionError",
17
+ "GrafikEyeConnectionInUseError",
18
+ "GrafikEyeConnectionTimeoutError",
19
+ ]
@@ -0,0 +1,294 @@
1
+ import asyncio
2
+ import logging
3
+ import re
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass
6
+ from enum import Enum, auto
7
+
8
+ import telnetlib3
9
+
10
+ from .const import DEFAULT_LOGIN, DEFAULT_PORT
11
+ from .exceptions import (
12
+ GrafikEyeAuthenticationError,
13
+ GrafikEyeConnectionError,
14
+ GrafikEyeConnectionInUseError,
15
+ GrafikEyeConnectionTimeoutError,
16
+ )
17
+
18
+ _LOGGER = logging.getLogger(__name__)
19
+
20
+
21
+ class ConnectionStatus(Enum):
22
+ DISCONNECTED = auto()
23
+ CONNECTING = auto()
24
+ CONNECTED = auto()
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class ControlUnit:
29
+ id: int
30
+ active_scene: int
31
+
32
+
33
+ class GrafikEyeClient:
34
+ SCENE_CODES = "0123456789ABCDEFG"
35
+
36
+ def __init__(
37
+ self,
38
+ host: str,
39
+ port: int = DEFAULT_PORT,
40
+ login: str = DEFAULT_LOGIN,
41
+ poll_interval: float | None = None,
42
+ ) -> None:
43
+ if poll_interval is not None and poll_interval <= 0:
44
+ raise ValueError("Poll interval must be greater than zero")
45
+
46
+ self._host = host
47
+ self._port = port
48
+ self._login = login
49
+ self._poll_interval = poll_interval
50
+ self._connection_status = ConnectionStatus.DISCONNECTED
51
+ self._reader: telnetlib3.TelnetReader | None = None
52
+ self._writer: telnetlib3.TelnetWriter | None = None
53
+ self._reader_task: asyncio.Task[None] | None = None
54
+ self._poll_task: asyncio.Task[None] | None = None
55
+ self._connection_status_callbacks: list[Callable[[ConnectionStatus], None]] = []
56
+ self._disconnect_callbacks: list[Callable[[], None]] = []
57
+ self._active_scenes_callbacks: list[Callable[[dict[int, int]], None]] = []
58
+ self._scene_callbacks: dict[int, list[Callable[[int], None]]] = {
59
+ i + 1: [] for i in range(8)
60
+ }
61
+ self._button_callbacks: dict[int, list[Callable[[int, bool], None]]] = {
62
+ i + 1: [] for i in range(8)
63
+ }
64
+ self._message_handlers: dict[re.Pattern[str], Callable[[re.Match[str]], None]] = {
65
+ re.compile(r":ss\s*([0-9A-HMLR]{8})"): self._handle_active_scenes,
66
+ re.compile(r"^([A-Ha-h])(\d+)$"): self._handle_button,
67
+ }
68
+
69
+ @property
70
+ def connection_status(self) -> ConnectionStatus:
71
+ return self._connection_status
72
+
73
+ async def connect(self) -> None:
74
+ self._set_connection_status(ConnectionStatus.CONNECTING)
75
+ _LOGGER.debug("Connecting to %s:%d", self._host, self._port)
76
+
77
+ try:
78
+ async with asyncio.timeout(10):
79
+ self._reader, self._writer = await telnetlib3.open_connection(
80
+ host=self._host,
81
+ port=self._port,
82
+ connect_minwait=1.0,
83
+ )
84
+ await self._authenticate()
85
+ except BaseException as error:
86
+ await self._cleanup()
87
+ if isinstance(error, GrafikEyeConnectionError):
88
+ raise
89
+ if isinstance(error, TimeoutError):
90
+ raise GrafikEyeConnectionTimeoutError from error
91
+ if isinstance(error, OSError):
92
+ raise GrafikEyeConnectionError from error
93
+ raise
94
+
95
+ _LOGGER.debug("Connected to %s:%d", self._host, self._port)
96
+ self._reader_task = asyncio.create_task(self._read_messages())
97
+
98
+ if self._poll_interval is not None:
99
+ self._poll_task = asyncio.create_task(self._poll_active_scenes())
100
+
101
+ self._set_connection_status(ConnectionStatus.CONNECTED)
102
+
103
+ async def disconnect(self) -> None:
104
+ was_connected = self._connection_status == ConnectionStatus.CONNECTED
105
+
106
+ await self._cleanup()
107
+
108
+ if was_connected:
109
+ _LOGGER.debug("Disconnected from %s:%d", self._host, self._port)
110
+
111
+ async def select_scene(self, scene: int, control_units: int | list[int]) -> None:
112
+ if not 0 <= scene <= 16:
113
+ raise ValueError("Scene must be between 0 and 16")
114
+
115
+ scene_code = self.SCENE_CODES[scene]
116
+ control_units_str = (
117
+ str(control_units)
118
+ if isinstance(control_units, int)
119
+ else "".join(map(str, control_units))
120
+ )
121
+ self._send_command(f"A{scene_code}{control_units_str}")
122
+
123
+ async def get_control_units(self) -> list[ControlUnit]:
124
+ received = asyncio.Event()
125
+ scenes: dict[int, int] = {}
126
+
127
+ def callback(active_scenes: dict[int, int]) -> None:
128
+ nonlocal scenes
129
+ scenes = active_scenes
130
+ received.set()
131
+
132
+ unsubscribe = self._register_active_scenes_callback(callback)
133
+
134
+ try:
135
+ self._send_command("G")
136
+ await asyncio.wait_for(received.wait(), timeout=5)
137
+ return [
138
+ ControlUnit(id=unit_id, active_scene=scene)
139
+ for unit_id, scene in scenes.items()
140
+ ]
141
+ finally:
142
+ unsubscribe()
143
+
144
+ def register_connection_status_callback(
145
+ self,
146
+ callback: Callable[[ConnectionStatus], None],
147
+ ) -> Callable[[], None]:
148
+ self._connection_status_callbacks.append(callback)
149
+ return lambda: self._connection_status_callbacks.remove(callback)
150
+
151
+ def register_disconnect_callback(
152
+ self,
153
+ callback: Callable[[], None],
154
+ ) -> Callable[[], None]:
155
+ self._disconnect_callbacks.append(callback)
156
+ return lambda: self._disconnect_callbacks.remove(callback)
157
+
158
+ def register_scene_callback(
159
+ self,
160
+ control_unit_id: int,
161
+ scene_callback: Callable[[int], None],
162
+ ) -> Callable[[], None]:
163
+ callbacks = self._scene_callbacks[control_unit_id]
164
+ callbacks.append(scene_callback)
165
+ return lambda: callbacks.remove(scene_callback)
166
+
167
+ def register_button_callback(
168
+ self,
169
+ control_unit_id: int,
170
+ button_callback: Callable[[int, bool], None],
171
+ ) -> Callable[[], None]:
172
+ callbacks = self._button_callbacks[control_unit_id]
173
+ callbacks.append(button_callback)
174
+ return lambda: callbacks.remove(button_callback)
175
+
176
+ def _register_active_scenes_callback(
177
+ self,
178
+ callback: Callable[[dict[int, int]], None],
179
+ ) -> Callable[[], None]:
180
+ self._active_scenes_callbacks.append(callback)
181
+ return lambda: self._active_scenes_callbacks.remove(callback)
182
+
183
+ def _set_connection_status(self, status: ConnectionStatus) -> None:
184
+ if self._connection_status == status:
185
+ return
186
+
187
+ was_connected = self._connection_status == ConnectionStatus.CONNECTED
188
+ self._connection_status = status
189
+
190
+ for callback in self._connection_status_callbacks.copy():
191
+ callback(status)
192
+
193
+ if was_connected and status == ConnectionStatus.DISCONNECTED:
194
+ for callback in self._disconnect_callbacks.copy():
195
+ callback()
196
+
197
+ async def _authenticate(self) -> None:
198
+ try:
199
+ await self._reader.readuntil(b"login: ")
200
+ except asyncio.IncompleteReadError as error: # EOF
201
+ raise GrafikEyeConnectionError from error
202
+
203
+ self._writer.write(self._login + "\r\n")
204
+
205
+ while True:
206
+ response = await self._reader.readline()
207
+ if response == "": # EOF
208
+ raise GrafikEyeConnectionError
209
+ if "login incorrect" in response:
210
+ raise GrafikEyeAuthenticationError
211
+ if "connection in use" in response:
212
+ raise GrafikEyeConnectionInUseError
213
+ if "connection established" in response:
214
+ return
215
+
216
+ async def _poll_active_scenes(self) -> None:
217
+ while True:
218
+ try:
219
+ await self.get_control_units()
220
+ except TimeoutError:
221
+ _LOGGER.debug("Timed out polling active scenes")
222
+
223
+ await asyncio.sleep(self._poll_interval)
224
+
225
+ async def _read_messages(self) -> None:
226
+ while True:
227
+ try:
228
+ message = await self._reader.readline()
229
+ except OSError as error:
230
+ _LOGGER.warning("Connection error: %s", error)
231
+ await self.disconnect()
232
+ return
233
+
234
+ if message == "": # EOF
235
+ await self.disconnect()
236
+ return
237
+
238
+ message = message.strip()
239
+ _LOGGER.debug("Received message: %s", message)
240
+
241
+ for pattern, handler in self._message_handlers.items():
242
+ if match := pattern.search(message):
243
+ _LOGGER.debug("Matched message handler %s -> %s", pattern.pattern, handler.__name__)
244
+ handler(match)
245
+ break
246
+
247
+ async def _cleanup(self) -> None:
248
+ for task in (self._poll_task, self._reader_task):
249
+ if task is not None and task is not asyncio.current_task():
250
+ task.cancel()
251
+ try:
252
+ await task
253
+ except asyncio.CancelledError:
254
+ pass
255
+
256
+ self._poll_task = None
257
+ self._reader_task = None
258
+
259
+ if self._writer is not None:
260
+ self._writer.close()
261
+ self._writer = None
262
+
263
+ self._reader = None
264
+ self._set_connection_status(ConnectionStatus.DISCONNECTED)
265
+
266
+ def _handle_active_scenes(self, match: re.Match[str]) -> None:
267
+ scenes = {
268
+ i + 1: self.SCENE_CODES.index(scene)
269
+ for i, scene in enumerate(match.group(1))
270
+ if scene not in "HMRL"
271
+ }
272
+
273
+ _LOGGER.debug("Active scenes updated: %s", scenes)
274
+
275
+ for callback in self._active_scenes_callbacks.copy():
276
+ callback(scenes)
277
+
278
+ for control_unit_id, scene_id in scenes.items():
279
+ for callback in self._scene_callbacks[control_unit_id].copy():
280
+ callback(scene_id)
281
+
282
+ def _handle_button(self, match: re.Match[str]) -> None:
283
+ address = match.group(1)
284
+ control_unit_id = ord(address.upper()) - ord("A") + 1
285
+ button = int(match.group(2))
286
+ pressed = address.isupper()
287
+
288
+ _LOGGER.debug("Control unit %d: button %d %s", control_unit_id, button, "pressed" if pressed else "released")
289
+
290
+ for callback in self._button_callbacks[control_unit_id].copy():
291
+ callback(button, pressed)
292
+
293
+ def _send_command(self, command: str) -> None:
294
+ self._writer.write(command + "\r\n")
@@ -0,0 +1,2 @@
1
+ DEFAULT_PORT = 23
2
+ DEFAULT_LOGIN = "nwk2"