chromalib 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 peterservices
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,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: chromalib
3
+ Version: 0.1.0
4
+ Summary:
5
+ Author: Ticataco
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Natural Language :: English
11
+ Classifier: Operating System :: Microsoft :: Windows
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: pydantic>=2.12.1,<3.0.0
21
+ Requires-Dist: websockets>=17.0,<18.0
22
+ Requires-Python: >=3.11
23
+ Project-URL: Repository, https://github.com/peterservices/ChromaLib.git
24
+ Project-URL: Issues, https://github.com/peterservices/ChromaLib/issues
25
+ Description-Content-Type: text/markdown
26
+
27
+ # ChromaLib
28
+
29
+ [![Build](https://github.com/peterservices/ChromaLib/actions/workflows/build.yml/badge.svg)](https://github.com/peterservices/ChromaLib/actions/workflows/build.yml)
30
+ [![Ruff](https://github.com/peterservices/ChromaLib/actions/workflows/ruff.yml/badge.svg)](https://github.com/peterservices/ChromaLib/actions/workflows/ruff.yml)
31
+
32
+ A typed library for Razer Chroma that supports effect layering, updates, and expiry while managing the connection with the Chroma SDK over a websocket, allowing you to focus on creating effects.
33
+
34
+ > [!NOTE]
35
+ > This library is in alpha and there may be breaking API changes in minor versions!
36
+ >
37
+ > Currently, Windows is the only supported platform, but support for Linux and macOS will be looked into.
38
+
39
+ ## **Installing**
40
+
41
+ **Python 3.11 to 3.15 is supported**
42
+
43
+ ```
44
+ pip install git+https://github.com/peterservices/ChromaLib.git
45
+ ```
46
+
47
+ ## **Simple Example**
48
+
49
+ <details>
50
+
51
+ <summary>Example</summary>
52
+
53
+ ```python
54
+ import asyncio
55
+
56
+ from chromalib import (
57
+ AppCategory,
58
+ AppConfiguration,
59
+ AuthorConfiguration,
60
+ ChromaApp,
61
+ Color,
62
+ DeviceType,
63
+ EffectMethod,
64
+ KeyboardEffect,
65
+ create_explosion_colors,
66
+ generate_explosion_updater,
67
+ )
68
+
69
+ configuration = AppConfiguration(
70
+ title="Red Integration",
71
+ description="Sets all devices to red",
72
+ author=AuthorConfiguration(
73
+ name="YourName",
74
+ contact="YourWebsite"
75
+ ),
76
+ supported_devices=[
77
+ DeviceType.KEYBOARD
78
+ ],
79
+ category=AppCategory.APPLICATION,
80
+ effect_id_hierarchy=[
81
+ "background",
82
+ "foreground"
83
+ ] # Optional
84
+ )
85
+
86
+ app = ChromaApp(config=configuration)
87
+
88
+ async def main():
89
+ await app.start()
90
+ colors = [[Color(blue=1)] * 24] * 8 # 24 columns x 8 rows (Yes this is not optimal, will be improved later)
91
+ app.add_effect(KeyboardEffect(
92
+ colors=colors,
93
+ method=EffectMethod.FILL,
94
+ id="background"
95
+ ))
96
+
97
+ await asyncio.sleep(0.5)
98
+
99
+ color = Color()
100
+ color.RGB_int = (255, 0, 0) # Another way to specify color values
101
+ app.add_effect(KeyboardEffect(
102
+ colors=create_explosion_colors(color),
103
+ method=EffectMethod.FILL_NON_ZERO,
104
+ update=generate_explosion_updater(),
105
+ update_rate_seconds=0.12,
106
+ expires_after_updates=15,
107
+ id="foreground"
108
+ ))
109
+
110
+ await asyncio.sleep(4)
111
+ await app.stop()
112
+ asyncio.run(main())
113
+ ```
114
+
115
+ </details>
116
+
117
+ ## **Features**
118
+
119
+ * Supports all major device types
120
+ * Supports custom effect update functions
121
+ * Utilizes Pydantic models for easy type validation
122
+ * Fully typed with docstrings
123
+ * Asynchronous background loop
124
+
125
+ > [!IMPORTANT]
126
+ > ChromaLib is not affiliated or endorsed in any way by Razer or any of its subsidaries
@@ -0,0 +1,100 @@
1
+ # ChromaLib
2
+
3
+ [![Build](https://github.com/peterservices/ChromaLib/actions/workflows/build.yml/badge.svg)](https://github.com/peterservices/ChromaLib/actions/workflows/build.yml)
4
+ [![Ruff](https://github.com/peterservices/ChromaLib/actions/workflows/ruff.yml/badge.svg)](https://github.com/peterservices/ChromaLib/actions/workflows/ruff.yml)
5
+
6
+ A typed library for Razer Chroma that supports effect layering, updates, and expiry while managing the connection with the Chroma SDK over a websocket, allowing you to focus on creating effects.
7
+
8
+ > [!NOTE]
9
+ > This library is in alpha and there may be breaking API changes in minor versions!
10
+ >
11
+ > Currently, Windows is the only supported platform, but support for Linux and macOS will be looked into.
12
+
13
+ ## **Installing**
14
+
15
+ **Python 3.11 to 3.15 is supported**
16
+
17
+ ```
18
+ pip install git+https://github.com/peterservices/ChromaLib.git
19
+ ```
20
+
21
+ ## **Simple Example**
22
+
23
+ <details>
24
+
25
+ <summary>Example</summary>
26
+
27
+ ```python
28
+ import asyncio
29
+
30
+ from chromalib import (
31
+ AppCategory,
32
+ AppConfiguration,
33
+ AuthorConfiguration,
34
+ ChromaApp,
35
+ Color,
36
+ DeviceType,
37
+ EffectMethod,
38
+ KeyboardEffect,
39
+ create_explosion_colors,
40
+ generate_explosion_updater,
41
+ )
42
+
43
+ configuration = AppConfiguration(
44
+ title="Red Integration",
45
+ description="Sets all devices to red",
46
+ author=AuthorConfiguration(
47
+ name="YourName",
48
+ contact="YourWebsite"
49
+ ),
50
+ supported_devices=[
51
+ DeviceType.KEYBOARD
52
+ ],
53
+ category=AppCategory.APPLICATION,
54
+ effect_id_hierarchy=[
55
+ "background",
56
+ "foreground"
57
+ ] # Optional
58
+ )
59
+
60
+ app = ChromaApp(config=configuration)
61
+
62
+ async def main():
63
+ await app.start()
64
+ colors = [[Color(blue=1)] * 24] * 8 # 24 columns x 8 rows (Yes this is not optimal, will be improved later)
65
+ app.add_effect(KeyboardEffect(
66
+ colors=colors,
67
+ method=EffectMethod.FILL,
68
+ id="background"
69
+ ))
70
+
71
+ await asyncio.sleep(0.5)
72
+
73
+ color = Color()
74
+ color.RGB_int = (255, 0, 0) # Another way to specify color values
75
+ app.add_effect(KeyboardEffect(
76
+ colors=create_explosion_colors(color),
77
+ method=EffectMethod.FILL_NON_ZERO,
78
+ update=generate_explosion_updater(),
79
+ update_rate_seconds=0.12,
80
+ expires_after_updates=15,
81
+ id="foreground"
82
+ ))
83
+
84
+ await asyncio.sleep(4)
85
+ await app.stop()
86
+ asyncio.run(main())
87
+ ```
88
+
89
+ </details>
90
+
91
+ ## **Features**
92
+
93
+ * Supports all major device types
94
+ * Supports custom effect update functions
95
+ * Utilizes Pydantic models for easy type validation
96
+ * Fully typed with docstrings
97
+ * Asynchronous background loop
98
+
99
+ > [!IMPORTANT]
100
+ > ChromaLib is not affiliated or endorsed in any way by Razer or any of its subsidaries
@@ -0,0 +1,60 @@
1
+ import logging
2
+
3
+ from .app import ChromaApp
4
+ from .colors import Color
5
+ from .configurations import (
6
+ AppCategory,
7
+ AppConfiguration,
8
+ AuthorConfiguration,
9
+ DeviceType,
10
+ )
11
+ from .default_effects import (
12
+ WaveDirection,
13
+ WaveLineOrientation,
14
+ WaveMode,
15
+ create_explosion_colors,
16
+ create_wave_colors,
17
+ generate_decay_updater,
18
+ generate_explosion_updater,
19
+ generate_wave_updater,
20
+ )
21
+ from .effects import (
22
+ ChromaLinkEffect,
23
+ Effect,
24
+ EffectMethod,
25
+ HeadsetEffect,
26
+ KeyboardEffect,
27
+ KeypadEffect,
28
+ MouseEffect,
29
+ MousepadEffect,
30
+ )
31
+ from .exceptions import InitializedError, UninitializedError
32
+
33
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
34
+
35
+ __all__ = [
36
+ "AppCategory",
37
+ "AppConfiguration",
38
+ "AuthorConfiguration",
39
+ "ChromaApp",
40
+ "ChromaLinkEffect",
41
+ "Color",
42
+ "DeviceType",
43
+ "Effect",
44
+ "EffectMethod",
45
+ "HeadsetEffect",
46
+ "InitializedError",
47
+ "KeyboardEffect",
48
+ "KeypadEffect",
49
+ "MouseEffect",
50
+ "MousepadEffect",
51
+ "UninitializedError",
52
+ "WaveDirection",
53
+ "WaveLineOrientation",
54
+ "WaveMode",
55
+ "create_explosion_colors",
56
+ "create_wave_colors",
57
+ "generate_decay_updater",
58
+ "generate_explosion_updater",
59
+ "generate_wave_updater",
60
+ ]
@@ -0,0 +1,332 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import time
5
+ from contextlib import suppress
6
+ from copy import deepcopy
7
+ from typing import Any, Self
8
+
9
+ import websockets
10
+
11
+ from .colors import Color
12
+ from .configurations import AppConfiguration, DeviceType
13
+ from .effects import Effect, EffectMethod, EffectState
14
+ from .exceptions import InitializedError, UninitializedError
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ class ChromaApp:
19
+ """
20
+ An application to control Razer Chroma enabled devices.
21
+ """
22
+ update_tolerance_seconds = 1 / 100 # (0.01s) How many seconds early effect updates can fire
23
+ websocket_uri = "ws://localhost:13337/razer/chromasdk"
24
+
25
+ def __init__(self: Self, config: AppConfiguration) -> None:
26
+ self.config = config
27
+ self.started_event = asyncio.Event()
28
+
29
+ self._state: EffectState | None = None
30
+ self._websocket: websockets.ClientConnection | None = None
31
+ self._effect_update_task: asyncio.Task | None = None
32
+
33
+ async def start(self: Self) -> None:
34
+ """
35
+ Intialize the Razer Chroma App.
36
+ """
37
+ if self.started_event.is_set():
38
+ raise InitializedError("The app has already been initialized.")
39
+ self._websocket = await websockets.connect(self.websocket_uri, ping_interval=10)
40
+ await self._send({
41
+ "title": self.config.title,
42
+ "description": self.config.description,
43
+ "author": {
44
+ "name": self.config.author.name,
45
+ "contact": self.config.author.contact
46
+ },
47
+ "device_supported": self.config.supported_devices,
48
+ "category": self.config.category
49
+ }, try_reconnect=False)
50
+
51
+ await asyncio.sleep(2) # Give the Chroma SDK time to intialize the app before resetting device RGB
52
+ for device in self.config.supported_devices:
53
+ await self._send({
54
+ "endpoint": device,
55
+ "effect": "CHROMA_NONE"
56
+ }, try_reconnect=False) # Clear Chroma effects for all active devices
57
+ await asyncio.sleep(1)
58
+
59
+ if self._state is None:
60
+ self._state = EffectState()
61
+ if self._effect_update_task is None or self._effect_update_task.done():
62
+ self._effect_update_task = asyncio.create_task(self._update_effects())
63
+ self.started_event.set()
64
+ self._state._effects_changed.set()
65
+ logger.info("Connected to the Razer Chroma SDK (%s)", self.websocket_uri)
66
+
67
+ async def stop(self: Self, *, complete: bool = True) -> None:
68
+ """
69
+ Deinitialize the Razer Chroma App.
70
+
71
+ Args:
72
+ complete: Whether a complete shutdown should be performed. (Clear current effect state)
73
+ """
74
+ self.started_event.clear()
75
+ if complete:
76
+ if self._effect_update_task is not None:
77
+ self._effect_update_task.cancel()
78
+ with suppress(asyncio.CancelledError):
79
+ await self._effect_update_task
80
+ self._effect_update_task = None
81
+ self._state = None
82
+ if self._websocket is not None:
83
+ await self._websocket.close()
84
+ self._websocket = None
85
+
86
+ logger.info("Disconnected from the Razer Chroma SDK (%s)", self.websocket_uri)
87
+
88
+ def find_effects_by_id(self: Self, id: str, device: DeviceType) -> list[Effect]:
89
+ """
90
+ Find an effect in the specified effects list by its id.
91
+
92
+ Args:
93
+ id: The effect id to look for.
94
+ device: The device type of the effect to look for.
95
+
96
+ Returns:
97
+ The effects matching the provided id. (Lowest to highest hierarchy)
98
+ """
99
+ if self._state is None:
100
+ raise UninitializedError("The app must be initialized before interacting with this method.")
101
+
102
+ effects = self._state.effects[device]
103
+
104
+ found_effects: list[Effect] = []
105
+ if id is not None:
106
+ for effect in effects:
107
+ if effect.id == id:
108
+ found_effects.append(effect)
109
+ return found_effects
110
+
111
+ def add_effect(self: Self, effect: Effect) -> None:
112
+ """
113
+ Add an effect to it's device's effects list, respecting ids in `self.effect_id_hierarchy`.
114
+
115
+ If an effect does not have a valid id, it will be treated as highest hierarchy.
116
+ If two effects share the same id, the newest effect will have the higher hierarchy,
117
+
118
+ Args:
119
+ effect: The effect to be added.
120
+ """
121
+ if self._state is None:
122
+ raise UninitializedError("The app must be initialized before interacting with this method.")
123
+
124
+ effects = self._state.effects[effect._device_type]
125
+
126
+ self._state._effects_changed.set()
127
+ if effect.id is not None and len(effects) > 0 and effect.id in self.config.effect_id_hierarchy:
128
+ highest_available_index = 0
129
+ for id in self.config.effect_id_hierarchy:
130
+ found_effects = self.find_effects_by_id(id, effect._device_type)
131
+ if len(found_effects) > 0:
132
+ highest_available_index = effects.index(found_effects[-1]) + 1 # Newer effects are treated as higher hierarchy than older effects
133
+
134
+ # There is no point in checking the rest of the hierarchy if no other effects are in the list
135
+ if highest_available_index == len(effects):
136
+ effects.append(effect)
137
+ return
138
+
139
+ if id == effect.id:
140
+ effects.insert(highest_available_index, effect)
141
+ return
142
+ else:
143
+ effects.append(effect)
144
+
145
+ def remove_effect(self: Self, effect: Effect) -> None:
146
+ """
147
+ Remove an effect from it's device's effects list.
148
+
149
+ Args:
150
+ effect: The effect to be removed.
151
+ """
152
+ if self._state is None:
153
+ raise UninitializedError("The app must be initialized before interacting with this method.")
154
+
155
+ effects = self._state.effects[effect._device_type]
156
+
157
+ if effect in effects:
158
+ effects.remove(effect)
159
+ self._state._effects_changed.set()
160
+
161
+ def remove_effects_by_ids(self: Self, ids: list[str], devices: list[DeviceType]) -> None:
162
+ """
163
+ Remove effects by their ids from the specified effects lists by their ids.
164
+
165
+ Args:
166
+ ids: The effect ids to remove.
167
+ devices: The device types of the effects to remove.
168
+ """
169
+ if self._state is None:
170
+ raise UninitializedError("The app must be initialized before interacting with this method.")
171
+
172
+ for id in ids:
173
+ for device_type in devices:
174
+ effects = self.find_effects_by_id(id, device_type)
175
+ for effect in effects:
176
+ self.remove_effect(effect)
177
+
178
+ async def _send(self: Self, payload: Any, *, try_reconnect: bool = True) -> None:
179
+ """
180
+ Send data through the Razer Chroma SDK.
181
+
182
+ Args:
183
+ try_reconnect: Whether a reconnection should be attempted if the websocket is unexpectedly closed.
184
+ """
185
+ if self._websocket is not None:
186
+ try:
187
+ await self._websocket.send(json.dumps(payload))
188
+ return logger.debug("Sent payload to Razer Chroma SDK")
189
+ except (ConnectionError, websockets.ConnectionClosed):
190
+ if try_reconnect and self.started_event.is_set():
191
+ await self.stop(complete=False) # Don't clear current effects
192
+ await self.start()
193
+ return await self._send(payload, try_reconnect=False)
194
+ raise
195
+ raise UninitializedError("The app must be intialized to send data through the websocket.")
196
+
197
+ async def _update_effects(self: Self) -> None:
198
+ """
199
+ Update the colors of devices with active effects, update any effect animations, and remove expired effects.
200
+ """
201
+ next_update_seconds: float | None = None
202
+ while True:
203
+ if self._state is not None:
204
+ if next_update_seconds is None:
205
+ # Await effect changed if no current effects will update
206
+ await self._state._effects_changed.wait()
207
+ else:
208
+ # Await the next update time or effect changed, whichever comes first
209
+ with suppress(TimeoutError):
210
+ await asyncio.wait_for(self._state._effects_changed.wait(), timeout=next_update_seconds)
211
+
212
+ next_update_seconds = None
213
+ decimal_colors: dict[DeviceType, list[list[int]] | None] = {key: [] for key in self.config.supported_devices}
214
+ for device in self.config.supported_devices:
215
+ effects = self._state.effects[device]
216
+ expiring_effects = []
217
+ effect_changed = False
218
+
219
+ for effect in effects:
220
+ if effect.update_rate_seconds is not None:
221
+ toleranced_update_rate = effect.update_rate_seconds - self.update_tolerance_seconds
222
+ if time.monotonic() - effect._last_update_time >= (toleranced_update_rate):
223
+ if effect.expires_after_updates is not None:
224
+ if effect.expires_after_updates == 0:
225
+ expiring_effects.append(effect)
226
+ continue
227
+ effect.expires_after_updates -= 1
228
+ if effect.update is not None:
229
+ effect.colors = effect.update(deepcopy(effect.colors))
230
+ effect_changed = True
231
+ effect._last_update_time = time.monotonic()
232
+ # Set how many seconds until an effect will update
233
+ effect_next_update = toleranced_update_rate - (time.monotonic() - effect._last_update_time)
234
+ next_update_seconds = effect_next_update if next_update_seconds is None else min(next_update_seconds, effect_next_update)
235
+ for effect in expiring_effects:
236
+ self.remove_effect(effect)
237
+ effect_changed = True
238
+
239
+ effect_changed = effect_changed or self._state._effects_changed.is_set()
240
+
241
+ if effect_changed and len(effects) > 0:
242
+ device_color_columns = effects[0]._colors_columns
243
+ device_color_rows = effects[0]._colors_rows
244
+
245
+ colors = [[Color() for _ in range(device_color_columns)] for _ in range(device_color_rows)]
246
+ for effect in effects:
247
+ match effect.method:
248
+ case EffectMethod.ADD:
249
+ # Add everything
250
+ for row, row_v in enumerate(effect.colors):
251
+ for column, column_v in enumerate(row_v):
252
+ colors[row][column] += column_v
253
+ case EffectMethod.ADD_NON_ZERO:
254
+ # Add everything, except to values that are already zeros
255
+ for row, row_v in enumerate(effect.colors):
256
+ for column, column_v in enumerate(row_v):
257
+ if colors[row][column].RGB_float != (0.0, 0.0, 0.0):
258
+ colors[row][column] += column_v
259
+ case EffectMethod.SUBTRACT:
260
+ # Subtract everything
261
+ for row, row_v in enumerate(effect.colors):
262
+ for column, column_v in enumerate(row_v):
263
+ colors[row][column] -= column_v
264
+ case EffectMethod.FILL:
265
+ # Fill everything
266
+ colors = deepcopy(effect.colors)
267
+ case EffectMethod.FILL_ZERO:
268
+ # Fill only remaining zero values
269
+ for row, row_v in enumerate(effect.colors):
270
+ for column, column_v in enumerate(row_v):
271
+ if colors[row][column].RGB_float == (0.0, 0.0, 0.0):
272
+ colors[row][column] = column_v.model_copy()
273
+ case EffectMethod.FILL_NON_ZERO:
274
+ # Fill everything, except with zeros
275
+ for row, row_v in enumerate(effect.colors):
276
+ for column, column_v in enumerate(row_v):
277
+ if column_v.RGB_float != (0.0, 0.0, 0.0):
278
+ colors[row][column] = column_v.model_copy()
279
+ case EffectMethod.MULTIPLY:
280
+ # Multiply everything
281
+ for row, row_v in enumerate(effect.colors):
282
+ for column, column_v in enumerate(row_v):
283
+ colors[row][column] *= column_v
284
+ case EffectMethod.DIVIDE:
285
+ # Divide everything
286
+ for row, row_v in enumerate(effect.colors):
287
+ for column, column_v in enumerate(row_v):
288
+ colors[row][column] /= column_v
289
+ # Convert the float colors to decimal colors usable by the Chroma SDK API
290
+ decimals = [[0 for _ in range(device_color_columns)] for _ in range(device_color_rows)]
291
+ for row, row_v in enumerate(colors):
292
+ for column, column_v in enumerate(row_v):
293
+ decimals[row][column] = column_v.BGR_decimal
294
+ decimal_colors[device] = decimals
295
+ elif effect_changed:
296
+ decimal_colors[device] = None
297
+ self._state._effects_changed.clear() # Reset effects changed event
298
+
299
+ if self.started_event.is_set(): # Only send data if we are connected
300
+ for device, colors in decimal_colors.items():
301
+ if colors is None:
302
+ await self._send({
303
+ "endpoint": device,
304
+ "effect": "CHROMA_NONE"
305
+ })
306
+ else:
307
+ if len(colors) == 1:
308
+ colors = colors[0] # Devices that have one row don't accept 2D lists
309
+ match device:
310
+ case DeviceType.KEYBOARD:
311
+ await self._send({
312
+ "endpoint": device,
313
+ "effect": "CHROMA_CUSTOM2",
314
+ "param": {
315
+ "color": colors,
316
+ "key": [[0 for _ in range(22)] for _ in range(6)] # Make key param all zeros because it's not needed
317
+ }
318
+ })
319
+ case DeviceType.MOUSE:
320
+ await self._send({
321
+ "endpoint": device,
322
+ "effect": "CHROMA_CUSTOM2",
323
+ "param": colors
324
+ })
325
+ case _:
326
+ await self._send({
327
+ "endpoint": device,
328
+ "effect": "CHROMA_CUSTOM",
329
+ "param": colors
330
+ })
331
+ else:
332
+ await self.started_event.wait() # self._state should only become non-None when the app is started
@@ -0,0 +1,8 @@
1
+ from pydantic import BaseModel, ConfigDict
2
+
3
+
4
+ class ValidateBaseModel(BaseModel):
5
+ """
6
+ A BaseModel with `validate_assignment` enabled.
7
+ """
8
+ model_config = ConfigDict(validate_assignment=True)
@@ -0,0 +1,88 @@
1
+ from typing import Self
2
+
3
+ from pydantic import field_validator
4
+
5
+ from .basemodel import ValidateBaseModel
6
+
7
+
8
+ class Color(ValidateBaseModel):
9
+ """
10
+ An RGB float color with added support for RGB integer and BGR decimal colors.
11
+
12
+ Supports addition, subtraction, multiplication, and division.
13
+ Please note that float color values are automatically clamped between 0 and 1.
14
+ """
15
+ red: float = 0.0
16
+ green: float = 0.0
17
+ blue: float = 0.0
18
+
19
+ def __add__(self: Self, other: "Color") -> "Color":
20
+ try:
21
+ return Color(red=self.red + other.red, green=self.green + other.green, blue=self.blue + other.blue)
22
+ except AttributeError:
23
+ raise NotImplementedError from None
24
+
25
+ def __sub__(self: Self, other: "Color") -> "Color":
26
+ try:
27
+ return Color(red=self.red - other.red, green=self.green - other.green, blue=self.blue - other.blue)
28
+ except AttributeError:
29
+ raise NotImplementedError from None
30
+
31
+ def __mul__(self: Self, other: "Color") -> "Color":
32
+ try:
33
+ return Color(red=self.red * other.red, green=self.green * other.green, blue=self.blue * other.blue)
34
+ except AttributeError:
35
+ raise NotImplementedError from None
36
+
37
+ def __truediv__(self: Self, other: "Color") -> "Color":
38
+ try:
39
+ # Set the color to 1 if division by 0 is attempted
40
+ red = 1 if other.red == 0 else self.red / other.red
41
+ green = 1 if other.green == 0 else self.green / other.green
42
+ blue = 1 if other.blue == 0 else self.blue / other.blue
43
+ return Color(red=red, green=green, blue=blue)
44
+ except AttributeError:
45
+ raise NotImplementedError from None
46
+
47
+ @property
48
+ def BGR_decimal(self: Self) -> int:
49
+ """
50
+ The color as a BGR decimal between 0 and 16777215.
51
+ """
52
+ int_color = self.RGB_int
53
+ return int_color[2] * 256 ** 2 + int_color[1] * 256 + int_color[0]
54
+
55
+ @property
56
+ def RGB_float(self: Self) -> tuple[float, float, float]:
57
+ """
58
+ The color as RGB floats between 0 and 1.
59
+ """
60
+ return (self.red, self.green, self.blue)
61
+
62
+ @property
63
+ def RGB_int(self: Self) -> tuple[int, int, int]:
64
+ """
65
+ The color as RGB integers between 0 and 255.
66
+ """
67
+ return (round(self.red * 255), round(self.green * 255), round(self.blue * 255))
68
+
69
+ @BGR_decimal.setter
70
+ def BGR_decimal(self: Self, value: int) -> None:
71
+ self.RGB_int = (value % 256, (value // 256) % 256, (value // 256 ** 2) % 256)
72
+
73
+ @RGB_float.setter
74
+ def RGB_float(self: Self, values: tuple[float, float, float]) -> None:
75
+ self.red = values[0]
76
+ self.green = values[1]
77
+ self.blue = values[2]
78
+
79
+ @RGB_int.setter
80
+ def RGB_int(self: Self, values: tuple[int, int, int]) -> None:
81
+ self.red = values[0] / 255
82
+ self.green = values[1] / 255
83
+ self.blue = values[2] / 255
84
+
85
+ @field_validator("red", "blue", "green", mode="after")
86
+ @classmethod
87
+ def validate_colors(cls, value: float) -> float:
88
+ return max(0.0, min(value, 1.0)) # Clamp color values between 0 and 1
@@ -0,0 +1,31 @@
1
+ from collections.abc import Sequence
2
+ from enum import StrEnum
3
+
4
+ from pydantic import Field
5
+
6
+ from .basemodel import ValidateBaseModel
7
+
8
+
9
+ class AppCategory(StrEnum):
10
+ APPLICATION = "application"
11
+ GAME = "game"
12
+
13
+ class DeviceType(StrEnum):
14
+ KEYBOARD = "keyboard"
15
+ MOUSE = "mouse"
16
+ MOUSEPAD = "mousepad"
17
+ HEADSET = "headset"
18
+ KEYPAD = "keypad"
19
+ CHROMALINK = "chromalink"
20
+
21
+ class AuthorConfiguration(ValidateBaseModel):
22
+ name: str = Field(max_length=64)
23
+ contact: str = Field(max_length=64)
24
+
25
+ class AppConfiguration(ValidateBaseModel):
26
+ title: str = Field(max_length=64)
27
+ description: str = Field(max_length=256)
28
+ author: AuthorConfiguration
29
+ supported_devices: Sequence[DeviceType]
30
+ category: AppCategory
31
+ effect_id_hierarchy: Sequence[str] = Field(default_factory=list)
@@ -0,0 +1,220 @@
1
+ from collections.abc import Callable
2
+ from copy import deepcopy
3
+ from enum import Enum
4
+
5
+ from .colors import Color
6
+
7
+
8
+ class WaveDirection(Enum):
9
+ UP = 1
10
+ DOWN = 2
11
+ LEFT = 3
12
+ RIGHT = 4
13
+
14
+ class WaveLineOrientation(Enum):
15
+ VERTICAL = 1
16
+ HORIZONTAL = 2
17
+
18
+ class WaveMode(Enum):
19
+ ALTERNATING = 1
20
+ CLUSTER = 2
21
+
22
+ def create_explosion_colors(color: Color) -> list[list[Color]]:
23
+ """
24
+ Create a matrix of float colors to be used for an explosion effect using the supplied color in RGB format.
25
+
26
+ Args:
27
+ color: The RGB color to be used for the effect.
28
+
29
+ Returns:
30
+ The generated explosion effect.
31
+ """
32
+ # Make a blank background
33
+ pattern = [[Color() for _ in range(24)] for _ in range(8)]
34
+
35
+ # Create a 2x2 colored square in the center of the matrix
36
+ pattern[3][11] = color.model_copy()
37
+ pattern[3][12] = color.model_copy()
38
+ pattern[4][11] = color.model_copy()
39
+ pattern[4][12] = color.model_copy()
40
+
41
+ return pattern
42
+
43
+ def create_wave_colors(colors: list[Color], line_orientation: WaveLineOrientation, mode: WaveMode) -> list[list[Color]]:
44
+ """
45
+ Create a matrix of colors to be used for a wave effect using the supplied colors.
46
+
47
+ Args:
48
+ colors: List of colors to be used to create the colors.
49
+ line_orientation:
50
+ `WaveMode.VERTICAL`: Max 24 colors.
51
+ `WaveMode.HORIZONTAL`: Max 8 colors.
52
+ mode:
53
+ `WaveMode.ALTERNATING`: Colors repeat seperated. (Looks best when the number of colors is a factor of the number of colors.)
54
+ `WaveMode.CLUSTER`: Colors repeat clumped with themselves.
55
+
56
+ Returns:
57
+ The generated matrix of wave colors.
58
+ """
59
+ if len(colors) < 2:
60
+ raise ValueError(f"Expected `colors` to have a length no less than 2, got {len(colors)}")
61
+ if line_orientation == WaveLineOrientation.VERTICAL and len(colors) > 24:
62
+ raise ValueError(f"Expected `colors` to have a length no greater than 24, got {len(colors)}")
63
+ if line_orientation == WaveLineOrientation.HORIZONTAL and len(colors) > 8:
64
+ raise ValueError(f"Expected `colors` to have a length no greater than 8, got {len(colors)}")
65
+
66
+ match line_orientation:
67
+ case WaveLineOrientation.VERTICAL:
68
+ row_pattern = colors.copy()
69
+ color = 0
70
+ match mode:
71
+ case WaveMode.ALTERNATING:
72
+ while len(row_pattern) < 24:
73
+ row_pattern.append(colors[color].model_copy())
74
+ color += 1
75
+ if color >= len(colors):
76
+ color = 0
77
+ case WaveMode.CLUSTER:
78
+ while len(row_pattern) < 24:
79
+ index = row_pattern.index(colors[color])
80
+ row_pattern.insert(index, colors[color].model_copy())
81
+ color += 1
82
+ if color >= len(colors):
83
+ color = 0
84
+ pattern = [deepcopy(row_pattern) for _ in range(8)] # Ensure every Color object in the pattern is unique
85
+ case WaveLineOrientation.HORIZONTAL:
86
+ column_pattern = colors.copy()
87
+ color = 0
88
+ match mode:
89
+ case WaveMode.ALTERNATING:
90
+ while len(column_pattern) < 8:
91
+ column_pattern.append(colors[color].model_copy())
92
+ color += 1
93
+ if color >= len(colors):
94
+ color = 0
95
+ case WaveMode.CLUSTER:
96
+ while len(column_pattern) < 8:
97
+ index = column_pattern.index(colors[color].model_copy())
98
+ column_pattern.insert(index, colors[color])
99
+ color += 1
100
+ if color >= len(colors):
101
+ color = 0
102
+ pattern = [[color.model_copy() for _ in range(24)] for color in column_pattern] # Ensure every Color object in the pattern is unique
103
+ return pattern
104
+
105
+ def generate_decay_updater(decay: Color) -> Callable[[list[list[Color]]], list[list[Color]]]:
106
+ """
107
+ Return a function that decreases a Color's values by a Color `decay`.
108
+ """
109
+ decay = decay.model_copy()
110
+ def _decay(colors: list[list[Color]]) -> list[list[Color]]:
111
+ for row in colors:
112
+ for color in row:
113
+ color.red -= decay.red
114
+ color.green -= decay.green
115
+ color.blue -= decay.blue
116
+ return colors
117
+ return _decay
118
+
119
+ def generate_explosion_updater() -> Callable[[list[list[Color]]], list[list[Color]]]:
120
+ """
121
+ Return a function that updates an explosion effect.
122
+ """
123
+ def _explosion(colors: list[list[Color]]) -> list[list[Color]]:
124
+ # Expand left half
125
+ for i in range(3, 5):
126
+ explosion_color = colors[i][11]
127
+ index = colors[i].index(explosion_color, 0, 12)
128
+ if index != 0:
129
+ colors[i][index - 1] = explosion_color.model_copy()
130
+
131
+ if i == 3:
132
+ first = 2
133
+ second = 1
134
+ third = 0
135
+ else:
136
+ first = 5
137
+ second = 6
138
+ third = 7
139
+ try:
140
+ index = colors[first].index(explosion_color, 0, 12)
141
+ if index != 0:
142
+ colors[first][index - 1] = explosion_color.model_copy()
143
+
144
+ try:
145
+ index = colors[second].index(explosion_color, 0, 12)
146
+ if index != 0:
147
+ colors[second][index - 1] = explosion_color.model_copy()
148
+
149
+ try:
150
+ index = colors[third].index(explosion_color, 0, 12)
151
+ if index != 0:
152
+ colors[third][index - 1] = explosion_color.model_copy()
153
+ except ValueError:
154
+ colors[third][11] = explosion_color.model_copy()
155
+ except ValueError:
156
+ colors[second][11] = explosion_color.model_copy()
157
+ except ValueError:
158
+ colors[first][11] = explosion_color.model_copy()
159
+
160
+ # Expand right half
161
+ for i in range(3, 5):
162
+ explosion_color = colors[i][12]
163
+ index = 23 - colors[i][::-1].index(explosion_color, 0, 12)
164
+ if index != 23:
165
+ colors[i][index + 1] = explosion_color.model_copy()
166
+
167
+ if i == 3:
168
+ first = 2
169
+ second = 1
170
+ third = 0
171
+ else:
172
+ first = 5
173
+ second = 6
174
+ third = 7
175
+ try:
176
+ index = 23 - colors[first][::-1].index(explosion_color, 0, 12)
177
+ if index != 23:
178
+ colors[first][index + 1] = explosion_color.model_copy()
179
+
180
+ try:
181
+ index = 23 - colors[second][::-1].index(explosion_color, 0, 12)
182
+ if index != 23:
183
+ colors[second][index + 1] = explosion_color.model_copy()
184
+
185
+ try:
186
+ index = 23 - colors[third][::-1].index(explosion_color, 0, 12)
187
+ if index != 23:
188
+ colors[third][index + 1] = explosion_color.model_copy()
189
+ except ValueError:
190
+ colors[third][12] = explosion_color.model_copy()
191
+ except ValueError:
192
+ colors[second][12] = explosion_color.model_copy()
193
+ except ValueError:
194
+ colors[first][12] = explosion_color.model_copy()
195
+ return colors
196
+ return _explosion
197
+
198
+ def generate_wave_updater(direction: WaveDirection) -> Callable[[list[list[Color]]], list[list[Color]]]:
199
+ """
200
+ Return a function that updates a wave effect in an direction `WaveDirection`.
201
+ """
202
+ def _wave(colors: list[list[Color]]) -> list[list[Color]]:
203
+ match direction:
204
+ case WaveDirection.UP:
205
+ first = colors.pop(0)
206
+ colors.append(first)
207
+ case WaveDirection.RIGHT:
208
+ for _, v in enumerate(colors):
209
+ last = v.pop()
210
+ v.insert(0, last)
211
+ case WaveDirection.DOWN:
212
+ last = colors.pop()
213
+ colors.insert(0, last)
214
+ case WaveDirection.LEFT:
215
+ for _, v in enumerate(colors):
216
+ first = v.pop(0)
217
+ v.append(first)
218
+ return colors
219
+ return _wave
220
+
@@ -0,0 +1,137 @@
1
+ import asyncio
2
+ from collections.abc import Callable
3
+ from enum import Enum
4
+ from typing import Self
5
+
6
+ from pydantic import (
7
+ Field,
8
+ NonNegativeFloat,
9
+ NonNegativeInt,
10
+ PositiveFloat,
11
+ PositiveInt,
12
+ PrivateAttr,
13
+ model_validator,
14
+ )
15
+
16
+ from .basemodel import ValidateBaseModel
17
+ from .colors import Color
18
+ from .configurations import DeviceType
19
+
20
+
21
+ def device_type_dict() -> dict[DeviceType, list]:
22
+ """
23
+ Return a dict with the values of `DeviceType` as keys.
24
+ """
25
+ return {key: [] for key in list(DeviceType)}
26
+
27
+ class EffectMethod(Enum):
28
+ """
29
+ Method of combining with lower hierarchy effects.
30
+ """
31
+ ADD = 1
32
+ ADD_NON_ZERO = 2
33
+ SUBTRACT = 3
34
+ MULTIPLY = 4
35
+ DIVIDE = 5
36
+ FILL = 6
37
+ FILL_NON_ZERO = 7
38
+ FILL_ZERO = 8
39
+
40
+ class Effect(ValidateBaseModel):
41
+ """
42
+ BaseModel for effects.
43
+ """
44
+ colors: list[list[Color]]
45
+ method: EffectMethod
46
+ expires_after_updates: NonNegativeInt | None = None
47
+ id: str | None = None
48
+ update: Callable[[list[list[Color]]], list[list[Color]]] | None = None
49
+ update_rate_seconds: PositiveFloat | None = None
50
+
51
+ _colors_rows: PositiveInt
52
+ _colors_columns: PositiveInt
53
+ _device_type: DeviceType
54
+ _last_update_time: NonNegativeFloat = 0
55
+
56
+ @model_validator(mode="after")
57
+ def validate_colors_dimensions(self: Self) -> Self:
58
+ if len(self.colors) != self._colors_rows:
59
+ raise ValueError(f"Expected outer list to have a length of {self._colors_rows}, got {len(self.colors)}")
60
+ for inner_list in self.colors:
61
+ if len(inner_list) != self._colors_columns:
62
+ raise ValueError(f"Expected inner lists to have a length of {self._colors_columns}, got {len(inner_list)}")
63
+ return self
64
+
65
+ @model_validator(mode="after")
66
+ def validate_update_fields(self: Self) -> Self:
67
+ if self.update_rate_seconds is None and (self.update is not None or self.expires_after_updates is not None):
68
+ raise ValueError("update_rate must be specified if update or expires_after_updates is specified.")
69
+ return self
70
+
71
+ class KeyboardEffect(Effect):
72
+ """
73
+ Keyboard effect.
74
+
75
+ colors: 8 x 24 list
76
+ """
77
+ _colors_rows = 8
78
+ _colors_columns = 24
79
+ _device_type = DeviceType.KEYBOARD
80
+
81
+ class MouseEffect(Effect):
82
+ """
83
+ Mouse effect.
84
+
85
+ colors: 9 x 7 list
86
+ """
87
+ _colors_rows = 9
88
+ _colors_columns = 7
89
+ _device_type = DeviceType.MOUSE
90
+
91
+ class MousepadEffect(Effect):
92
+ """
93
+ Mousepad effect.
94
+
95
+ colors: 1 x 20 list
96
+ """
97
+ _colors_rows = 1
98
+ _colors_columns = 20
99
+ _device_type = DeviceType.MOUSEPAD
100
+
101
+ class HeadsetEffect(Effect):
102
+ """
103
+ Headset effect.
104
+
105
+ colors: 1 x 5 list
106
+ """
107
+ _colors_rows = 1
108
+ _colors_columns = 5
109
+ _device_type = DeviceType.HEADSET
110
+
111
+ class KeypadEffect(Effect):
112
+ """
113
+ Keypad effect.
114
+
115
+ colors: 4 x 5 list
116
+ """
117
+ _colors_rows = 4
118
+ _colors_columns = 5
119
+ _device_type = DeviceType.KEYPAD
120
+
121
+ class ChromaLinkEffect(Effect):
122
+ """
123
+ Chroma Link effect.
124
+
125
+ colors: 1 x 5 list
126
+ """
127
+ _colors_rows = 1
128
+ _colors_columns = 5
129
+ _device_type = DeviceType.CHROMALINK
130
+
131
+ class EffectState(ValidateBaseModel):
132
+ """
133
+ A state object that tracks a list of effects and whether the list has changed since last update.
134
+ """
135
+ effects: dict[DeviceType, list[Effect]] = Field(default_factory=device_type_dict)
136
+
137
+ _effects_changed: asyncio.Event = PrivateAttr(default_factory=asyncio.Event)
@@ -0,0 +1,9 @@
1
+ class InitializedError(Exception):
2
+ """
3
+ Raised when trying to initialize an already initialized object.
4
+ """
5
+
6
+ class UninitializedError(Exception):
7
+ """
8
+ Raised when trying to interact with an uninitialized object.
9
+ """
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "chromalib"
3
+ license = "MIT"
4
+ license-files = ["LICENSE"]
5
+ version = "0.1.0"
6
+ description = ""
7
+ readme = "README.md"
8
+ requires-python = ">= 3.11"
9
+ dependencies = [
10
+ "pydantic >=2.12.1, <3.0.0",
11
+ "websockets >=17.0, <18.0",
12
+ ]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "Natural Language :: English",
17
+ "Operating System :: Microsoft :: Windows",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: 3.15",
24
+ "Topic :: Software Development :: Libraries :: Python Modules",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ [[project.authors]]
29
+ name = "Ticataco"
30
+
31
+ [project.urls]
32
+ Repository = "https://github.com/peterservices/ChromaLib.git"
33
+ Issues = "https://github.com/peterservices/ChromaLib/issues"
34
+
35
+ [dependency-groups]
36
+ dev = ["pre-commit >= 4.0.0, <5.0.0"]
37
+
38
+ [build-system]
39
+ requires = ["uv_build >= 0.13 , <0.14"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.uv.build-backend]
43
+ module-root = "."
44
+ module-name = "chromalib"
45
+
46
+ [tool.ruff.lint]
47
+ extend-select = [
48
+ "B",
49
+ "C4",
50
+ "E",
51
+ "F",
52
+ "FBT",
53
+ "I",
54
+ "ICN",
55
+ "ISC",
56
+ "PTH",
57
+ "PYI",
58
+ "RET",
59
+ "RUF",
60
+ "S",
61
+ "SIM",
62
+ "SIM",
63
+ "TID",
64
+ "UP",
65
+ "W",
66
+ ]
67
+ ignore = ["E501"]
68
+
69
+ [tool.pyrefly]
70
+ preset = "default"
71
+ project-includes = ["**/*.py*"]
@@ -0,0 +1,77 @@
1
+ [project]
2
+ name = "chromalib"
3
+ license = "MIT"
4
+ license-files = ["LICENSE"]
5
+ version = "0.1.0"
6
+ description = ""
7
+ readme = "README.md"
8
+ authors = [
9
+ { name = "Ticataco" }
10
+ ]
11
+ requires-python = ">= 3.11"
12
+ dependencies = [
13
+ "pydantic >=2.12.1, <3.0.0",
14
+ "websockets >=17.0, <18.0"
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Natural Language :: English",
20
+ "Operating System :: Microsoft :: Windows",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: 3.15",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ "Typing :: Typed"
29
+ ]
30
+
31
+ [project.urls]
32
+ Repository = "https://github.com/peterservices/ChromaLib.git"
33
+ Issues = "https://github.com/peterservices/ChromaLib/issues"
34
+
35
+ [dependency-groups]
36
+ dev = [
37
+ "pre-commit >= 4.0.0, <5.0.0",
38
+ ]
39
+
40
+ [build-system]
41
+ requires = ["uv_build >= 0.13 , <0.14"]
42
+ build-backend = "uv_build"
43
+
44
+ [tool.uv.build-backend]
45
+ module-root = "."
46
+ module-name = "chromalib"
47
+
48
+ [tool.ruff.lint]
49
+ extend-select = [
50
+ "B",
51
+ "C4",
52
+ "E",
53
+ "F",
54
+ "FBT",
55
+ "I",
56
+ "ICN",
57
+ "ISC",
58
+ "PTH",
59
+ "PYI",
60
+ "RET",
61
+ "RUF",
62
+ "S",
63
+ "SIM",
64
+ "SIM",
65
+ "TID",
66
+ "UP",
67
+ "W"
68
+ ]
69
+ ignore = [
70
+ "E501"
71
+ ]
72
+
73
+ [tool.pyrefly]
74
+ preset = "default"
75
+ project-includes = [
76
+ "**/*.py*",
77
+ ]